From e686107ee8988fc3e548b88787177b14c5dd09f5 Mon Sep 17 00:00:00 2001 From: Cameron McCormack Date: Thu, 29 Dec 2016 15:04:32 +0800 Subject: [PATCH 001/229] Bug 1324983 - Don't persist styles on elements not in the document. r=emilio MozReview-Commit-ID: 4Z8IxPS6rfE --- dom/xbl/nsXBLService.cpp | 9 ++++++++- layout/style/ServoBindings.cpp | 6 ++++++ layout/style/ServoBindings.h | 1 + 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/dom/xbl/nsXBLService.cpp b/dom/xbl/nsXBLService.cpp index 57503a51f306..f17ad5abe0d6 100644 --- a/dom/xbl/nsXBLService.cpp +++ b/dom/xbl/nsXBLService.cpp @@ -462,7 +462,14 @@ nsXBLService::LoadBindings(nsIContent* aContent, nsIURI* aURL, // anonymous content created in this function, explicit children for which we // defer styling until after XBL bindings are applied, and elements whose existing // style was invalidated by a call to SetXBLInsertionParent. - AutoStyleNewChildren styleNewChildren(aContent->AsElement()); + // + // However, we skip this styling if aContent is not in the document, since we + // should keep such elements unstyled. (There are some odd cases where we do + // apply bindings to elements not in the document.) + Maybe styleNewChildren; + if (aContent->IsInComposedDoc()) { + styleNewChildren.emplace(aContent->AsElement()); + } nsXBLBinding *binding = aContent->GetXBLBinding(); if (binding) { diff --git a/layout/style/ServoBindings.cpp b/layout/style/ServoBindings.cpp index 9677f5d3fc10..86299c8adfb2 100644 --- a/layout/style/ServoBindings.cpp +++ b/layout/style/ServoBindings.cpp @@ -59,6 +59,12 @@ Gecko_NodeIsElement(RawGeckoNodeBorrowed aNode) return aNode->IsElement(); } +bool +Gecko_IsInDocument(RawGeckoNodeBorrowed aNode) +{ + return aNode->IsInComposedDoc(); +} + RawGeckoNodeBorrowedOrNull Gecko_GetParentNode(RawGeckoNodeBorrowed aNode) { diff --git a/layout/style/ServoBindings.h b/layout/style/ServoBindings.h index 8eeabbdf8540..3aa73933d847 100644 --- a/layout/style/ServoBindings.h +++ b/layout/style/ServoBindings.h @@ -83,6 +83,7 @@ NS_DECL_HOLDER_FFI_REFCOUNTING(nsIURI, URI) // DOM Traversal. uint32_t Gecko_ChildrenCount(RawGeckoNodeBorrowed node); bool Gecko_NodeIsElement(RawGeckoNodeBorrowed node); +bool Gecko_IsInDocument(RawGeckoNodeBorrowed node); RawGeckoNodeBorrowedOrNull Gecko_GetParentNode(RawGeckoNodeBorrowed node); RawGeckoNodeBorrowedOrNull Gecko_GetFirstChild(RawGeckoNodeBorrowed node); RawGeckoNodeBorrowedOrNull Gecko_GetLastChild(RawGeckoNodeBorrowed node); From 63cefa68755fbcc680407eeece076de17bf86b39 Mon Sep 17 00:00:00 2001 From: Andreas Pehrson Date: Wed, 28 Sep 2016 16:12:20 +0200 Subject: [PATCH 002/229] Bug 1305949 - Refactor code that feeds video stream sink when it gets added. r=ctai This mostly simplifies the code, but there are two changes to the logic as well. 1) The decision to install the listener or not used to be based on if the track existed in mUpdateTracks, while feeding the sink would look at the StreamTracks as well. This now looks at StreamTracks since an ended track is kept there but removed from mUpdateTracks. That means that we also NotifyEnded() if the track was in the StreamTracks but not in mUpdateTracks. 2) I removed the code that feeds a video stream sink with the last chunk in case the graph's current time has passed the end of the track. Tests should be written so that we have guarantees that there will be video data when a video stream sink gets added. If this fails we should fix the root cause of such a timing issue instead of wallpapering it with an old frame. I think this could be masking other issues. We'll see how this acts out on try. MozReview-Commit-ID: KKr9JhVpxZt --HG-- extra : rebase_source : f775fcfbe9647e29ee107ecc7b1f39c2d91f3b0d extra : histedit_source : 4fa675ce93dc67d7db972a07bb3236f34707e7d3 --- dom/media/MediaStreamGraph.cpp | 64 +++++++++++++++------------------- 1 file changed, 28 insertions(+), 36 deletions(-) diff --git a/dom/media/MediaStreamGraph.cpp b/dom/media/MediaStreamGraph.cpp index a1f32a2fb53f..ec5aeb948623 100644 --- a/dom/media/MediaStreamGraph.cpp +++ b/dom/media/MediaStreamGraph.cpp @@ -2899,8 +2899,8 @@ SourceMediaStream::AddDirectTrackListenerImpl(already_AddRefed listener = aListener; @@ -2909,44 +2909,30 @@ SourceMediaStream::AddDirectTrackListenerImpl(already_AddRefedmData->GetType() == MediaSegment::AUDIO; - isVideo = data->mData->GetType() == MediaSegment::VIDEO; + updateData = FindDataForTrack(aTrackID); + track = FindTrack(aTrackID); + if (track) { + isAudio = track->GetType() == MediaSegment::AUDIO; + isVideo = track->GetType() == MediaSegment::VIDEO; } - // The track might be removed from mUpdateTrack but still exist in - // mTracks. - auto streamTrack = FindTrack(aTrackID); - bool foundTrack = !!streamTrack; - if (foundTrack) { - MediaStreamVideoSink* videoSink = listener->AsMediaStreamVideoSink(); + MediaStreamVideoSink* videoSink = listener->AsMediaStreamVideoSink(); + if (track && isVideo && videoSink) { // Re-send missed VideoSegment to new added MediaStreamVideoSink. - if (streamTrack->GetType() == MediaSegment::VIDEO && videoSink) { - VideoSegment videoSegment; - if (mTracks.GetForgottenDuration() < streamTrack->GetSegment()->GetDuration()) { - videoSegment.AppendSlice(*streamTrack->GetSegment(), - mTracks.GetForgottenDuration(), - streamTrack->GetSegment()->GetDuration()); - } else { - VideoSegment* streamTrackSegment = static_cast(streamTrack->GetSegment()); - VideoChunk* lastChunk = streamTrackSegment->GetLastChunk(); - if (lastChunk) { - StreamTime startTime = streamTrackSegment->GetDuration() - lastChunk->GetDuration(); - videoSegment.AppendSlice(*streamTrackSegment, - startTime, - streamTrackSegment->GetDuration()); - } - } - if (found) { - videoSegment.AppendSlice(*data->mData, 0, data->mData->GetDuration()); - } - videoSink->SetCurrentFrames(videoSegment); + VideoSegment* trackSegment = static_cast(track->GetSegment()); + VideoSegment videoSegment; + if (mTracks.GetForgottenDuration() < trackSegment->GetDuration()) { + videoSegment.AppendSlice(*trackSegment, + mTracks.GetForgottenDuration(), + trackSegment->GetDuration()); } + if (updateData) { + videoSegment.AppendSlice(*updateData->mData, 0, updateData->mData->GetDuration()); + } + videoSink->SetCurrentFrames(videoSegment); } - if (found && (isAudio || isVideo)) { + if (track && (isAudio || isVideo)) { for (auto entry : mDirectTrackListeners) { if (entry.mListener == listener && (entry.mTrackID == TRACK_ANY || entry.mTrackID == aTrackID)) { @@ -2962,7 +2948,7 @@ SourceMediaStream::AddDirectTrackListenerImpl(already_AddRefedmTrackID = aTrackID; } } - if (!found) { + if (!track) { STREAM_LOG(LogLevel::Warning, ("Couldn't find source track for direct track listener %p", listener.get())); listener->NotifyDirectListenerInstalled( @@ -2976,9 +2962,15 @@ SourceMediaStream::AddDirectTrackListenerImpl(already_AddRefedNotifyDirectListenerInstalled( DirectMediaStreamTrackListener::InstallationResult::SUCCESS); + if (!updateData) { + // The track exists but the mUpdateTracks entry was removed. + // This means that the track has ended. + listener->NotifyEnded(); + } } void From c66e1073f93f9b82827600ceb262012b2c4f427e Mon Sep 17 00:00:00 2001 From: Andreas Pehrson Date: Thu, 13 Oct 2016 11:18:53 +0200 Subject: [PATCH 003/229] Bug 1305949 - Use the same path for passing on missed data to video sink, as during normal operation. r=ctai MozReview-Commit-ID: FDKFf1skYVe --HG-- extra : rebase_source : 83a1b9ec57e3b83807a482009558a78c80e1774a extra : histedit_source : b4f61d91f7832c70585a79ce5381eafcdc5c761f --- dom/media/MediaStreamGraph.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/dom/media/MediaStreamGraph.cpp b/dom/media/MediaStreamGraph.cpp index ec5aeb948623..038437df7d91 100644 --- a/dom/media/MediaStreamGraph.cpp +++ b/dom/media/MediaStreamGraph.cpp @@ -2916,8 +2916,7 @@ SourceMediaStream::AddDirectTrackListenerImpl(already_AddRefedGetType() == MediaSegment::VIDEO; } - MediaStreamVideoSink* videoSink = listener->AsMediaStreamVideoSink(); - if (track && isVideo && videoSink) { + if (track && isVideo && listener->AsMediaStreamVideoSink()) { // Re-send missed VideoSegment to new added MediaStreamVideoSink. VideoSegment* trackSegment = static_cast(track->GetSegment()); VideoSegment videoSegment; @@ -2929,7 +2928,7 @@ SourceMediaStream::AddDirectTrackListenerImpl(already_AddRefedmData, 0, updateData->mData->GetDuration()); } - videoSink->SetCurrentFrames(videoSegment); + listener->NotifyRealtimeTrackData(Graph(), 0, videoSegment); } if (track && (isAudio || isVideo)) { From 84bdb5118bbd09c9e1432c60972e703a5be84607 Mon Sep 17 00:00:00 2001 From: Andreas Pehrson Date: Thu, 13 Oct 2016 11:21:39 +0200 Subject: [PATCH 004/229] Bug 1305949 - Use only one listener in MediaPipelineTransmit. r=ctai MozReview-Commit-ID: KcxdmeUDmCY --HG-- extra : rebase_source : 9cdf00f5023e4383a64680d954baf40371f42c1b extra : histedit_source : b7a3fabeff9556c6777fe46d9384dcca500ea231 --- .../src/mediapipeline/MediaPipeline.cpp | 118 ++++++------------ .../src/mediapipeline/MediaPipeline.h | 2 - .../webrtc/signaling/test/FakeMediaStreams.h | 3 +- 3 files changed, 39 insertions(+), 84 deletions(-) diff --git a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp index c78f923f482a..9d9eb5ecdd63 100644 --- a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp +++ b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp @@ -1203,7 +1203,7 @@ void MediaPipeline::PacketReceived(TransportLayer *layer, } class MediaPipelineTransmit::PipelineListener - : public DirectMediaStreamTrackListener + : public MediaStreamVideoSink { friend class MediaPipelineTransmit; public: @@ -1291,15 +1291,17 @@ public: void NotifyDirectListenerInstalled(InstallationResult aResult) override; void NotifyDirectListenerUninstalled() override; + // Implement MediaStreamVideoSink + void SetCurrentFrames(const VideoSegment& aSegment) override; + void ClearFrames() override {} + private: void UnsetTrackIdImpl() { MutexAutoLock lock(mMutex); track_id_ = track_id_external_ = TRACK_INVALID; } - void NewData(MediaStreamGraph* graph, - StreamTime offset, - const MediaSegment& media); + void NewData(const MediaSegment& media, TrackRate aRate = 0); RefPtr conduit_; RefPtr audio_processing_; @@ -1388,34 +1390,6 @@ protected: }; #endif -class MediaPipelineTransmit::PipelineVideoSink : - public MediaStreamVideoSink -{ -public: - explicit PipelineVideoSink(const RefPtr& conduit, - MediaPipelineTransmit::PipelineListener* listener) - : conduit_(conduit) - , pipelineListener_(listener) - { - } - - virtual void SetCurrentFrames(const VideoSegment& aSegment) override; - virtual void ClearFrames() override {} - -private: - ~PipelineVideoSink() { - // release conduit on mainthread. Must use forget()! - nsresult rv = NS_DispatchToMainThread(new - ConduitDeleteEvent(conduit_.forget())); - MOZ_ASSERT(!NS_FAILED(rv),"Could not dispatch conduit shutdown to main"); - if (NS_FAILED(rv)) { - MOZ_CRASH(); - } - } - RefPtr conduit_; - MediaPipelineTransmit::PipelineListener* pipelineListener_; -}; - MediaPipelineTransmit::MediaPipelineTransmit( const std::string& pc, nsCOMPtr main_thread, @@ -1430,7 +1404,6 @@ MediaPipelineTransmit::MediaPipelineTransmit( MediaPipeline(pc, TRANSMIT, main_thread, sts_thread, track_id, level, conduit, rtp_transport, rtcp_transport, filter), listener_(new PipelineListener(conduit)), - video_sink_(new PipelineVideoSink(conduit, listener_)), domtrack_(domtrack) { if (!IsVideo()) { @@ -1488,10 +1461,6 @@ void MediaPipelineTransmit::AttachToTrack(const std::string& track_id) { domtrack_->AddDirectListener(listener_); domtrack_->AddListener(listener_); -#if !defined(MOZILLA_EXTERNAL_LINKAGE) - domtrack_->AddDirectListener(video_sink_); -#endif - #ifndef MOZILLA_INTERNAL_API // this enables the unit tests that can't fiddle with principals and the like listener_->SetEnabled(true); @@ -1540,7 +1509,6 @@ MediaPipelineTransmit::DetachMedia() if (domtrack_) { domtrack_->RemoveDirectListener(listener_); domtrack_->RemoveListener(listener_); - domtrack_->RemoveDirectListener(video_sink_); domtrack_ = nullptr; } // Let the listener be destroyed with the pipeline (or later). @@ -1743,7 +1711,14 @@ NotifyRealtimeTrackData(MediaStreamGraph* graph, this << ", offset=" << offset << ", duration=" << media.GetDuration()); - NewData(graph, offset, media); + if (media.GetType() == MediaSegment::VIDEO) { + // We have to call the upstream NotifyRealtimeTrackData and + // MediaStreamVideoSink will route them to SetCurrentFrames. + MediaStreamVideoSink::NotifyRealtimeTrackData(graph, offset, media); + return; + } + + NewData(media, graph->GraphRate()); } void MediaPipelineTransmit::PipelineListener:: @@ -1752,10 +1727,17 @@ NotifyQueuedChanges(MediaStreamGraph* graph, const MediaSegment& queued_media) { MOZ_MTLOG(ML_DEBUG, "MediaPipeline::NotifyQueuedChanges()"); - // ignore non-direct data if we're also getting direct data - if (!direct_connect_) { - NewData(graph, offset, queued_media); + if (queued_media.GetType() == MediaSegment::VIDEO) { + // We always get video from SetCurrentFrames(). + return; } + + if (direct_connect_) { + // ignore non-direct data if we're also getting direct data + return; + } + + NewData(queued_media, graph->GraphRate()); } void MediaPipelineTransmit::PipelineListener:: @@ -1774,9 +1756,7 @@ NotifyDirectListenerUninstalled() { } void MediaPipelineTransmit::PipelineListener:: -NewData(MediaStreamGraph* graph, - StreamTime offset, - const MediaSegment& media) { +NewData(const MediaSegment& media, TrackRate aRate /* = 0 */) { if (!active_) { MOZ_MTLOG(ML_DEBUG, "Discarding packets because transport not ready"); return; @@ -1794,49 +1774,27 @@ NewData(MediaStreamGraph* graph, // track type and it's destined for us // See bug 784517 if (media.GetType() == MediaSegment::AUDIO) { - AudioSegment* audio = const_cast( - static_cast(&media)); + MOZ_RELEASE_ASSERT(aRate > 0); - AudioSegment::ChunkIterator iter(*audio); - while(!iter.IsEnded()) { - TrackRate rate; -#ifdef USE_FAKE_MEDIA_STREAMS - rate = Fake_MediaStream::GraphRate(); -#else - rate = graph->GraphRate(); -#endif - audio_processing_->QueueAudioChunk(rate, *iter, enabled_); - iter.Next(); + AudioSegment* audio = const_cast(static_cast(&media)); + for(AudioSegment::ChunkIterator iter(*audio); !iter.IsEnded(); iter.Next()) { + audio_processing_->QueueAudioChunk(aRate, *iter, enabled_); } +#if !defined(MOZILLA_EXTERNAL_LINKAGE) } else { - // Ignore + VideoSegment* video = const_cast(static_cast(&media)); + VideoSegment::ChunkIterator iter(*video); + for(VideoSegment::ChunkIterator iter(*video); !iter.IsEnded(); iter.Next()) { + converter_->QueueVideoChunk(*iter, !enabled_); + } +#endif // MOZILLA_EXTERNAL_LINKAGE } } -void MediaPipelineTransmit::PipelineVideoSink:: +void MediaPipelineTransmit::PipelineListener:: SetCurrentFrames(const VideoSegment& aSegment) { - MOZ_ASSERT(pipelineListener_); - - if (!pipelineListener_->active_) { - MOZ_MTLOG(ML_DEBUG, "Discarding packets because transport not ready"); - return; - } - - if (conduit_->type() != MediaSessionConduit::VIDEO) { - // Ignore data of wrong kind in case we have a muxed stream - return; - } - -#if !defined(MOZILLA_EXTERNAL_LINKAGE) - VideoSegment* video = const_cast(&aSegment); - - VideoSegment::ChunkIterator iter(*video); - while(!iter.IsEnded()) { - pipelineListener_->converter_->QueueVideoChunk(*iter, !pipelineListener_->enabled_); - iter.Next(); - } -#endif + NewData(aSegment); } class TrackAddedCallback { diff --git a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.h b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.h index 4265fb99d887..38cc0bf9ab33 100644 --- a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.h +++ b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.h @@ -348,7 +348,6 @@ public: // Separate classes to allow ref counting class PipelineListener; class VideoFrameFeeder; - class PipelineVideoSink; protected: ~MediaPipelineTransmit(); @@ -360,7 +359,6 @@ public: RefPtr feeder_; RefPtr converter_; #endif - RefPtr video_sink_; dom::MediaStreamTrack* domtrack_; }; diff --git a/media/webrtc/signaling/test/FakeMediaStreams.h b/media/webrtc/signaling/test/FakeMediaStreams.h index 117d269055d4..0325bb700b93 100644 --- a/media/webrtc/signaling/test/FakeMediaStreams.h +++ b/media/webrtc/signaling/test/FakeMediaStreams.h @@ -70,6 +70,7 @@ public: gGraph = new MediaStreamGraph(); return gGraph; } + uint32_t GraphRate() { return 16000; } }; } @@ -186,8 +187,6 @@ class Fake_MediaStream { public: Fake_MediaStream () : mListeners(), mTrackListeners(), mMutex("Fake MediaStream") {} - static uint32_t GraphRate() { return 16000; } - void AddListener(Fake_MediaStreamListener *aListener) { mozilla::MutexAutoLock lock(mMutex); mListeners.insert(aListener); From 147f6756fa14ededcce0b0d59b4be1b21a874aa4 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 14 Dec 2016 17:16:01 -0500 Subject: [PATCH 005/229] Bug 1323100 - Use NS_NewNamedThread to name the proxy resolution thread. r=froydnj MozReview-Commit-ID: Fqxr4XmvS7I --HG-- extra : rebase_source : 70a09ac76919d104092e7c35ec3383191243f130 --- netwerk/base/nsPACMan.cpp | 18 +++--------------- netwerk/base/nsPACMan.h | 1 - 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/netwerk/base/nsPACMan.cpp b/netwerk/base/nsPACMan.cpp index 37d3e8b6bba2..43c569d8b3fd 100644 --- a/netwerk/base/nsPACMan.cpp +++ b/netwerk/base/nsPACMan.cpp @@ -742,27 +742,15 @@ nsPACMan::AsyncOnChannelRedirect(nsIChannel *oldChannel, nsIChannel *newChannel, return NS_OK; } -void -nsPACMan::NamePACThread() -{ - MOZ_ASSERT(!NS_IsMainThread(), "wrong thread"); - PR_SetCurrentThreadName("Proxy Resolution"); -} - nsresult nsPACMan::Init(nsISystemProxySettings *systemProxySettings) { mSystemProxySettings = systemProxySettings; - nsresult rv = NS_NewThread(getter_AddRefs(mPACThread), nullptr); - if (NS_FAILED(rv)) - return rv; + nsresult rv = + NS_NewNamedThread("ProxyResolution", getter_AddRefs(mPACThread)); - // don't check return value as it is not a big deal for this to fail. - mPACThread->Dispatch(NewRunnableMethod(this, &nsPACMan::NamePACThread), - nsIEventTarget::DISPATCH_NORMAL); - - return NS_OK; + return rv; } } // namespace net diff --git a/netwerk/base/nsPACMan.h b/netwerk/base/nsPACMan.h index def0843cb80a..df952ff9ee25 100644 --- a/netwerk/base/nsPACMan.h +++ b/netwerk/base/nsPACMan.h @@ -214,7 +214,6 @@ private: void PostProcessPendingQ(); void PostCancelPendingQ(nsresult); bool ProcessPending(); - void NamePACThread(); private: ProxyAutoConfig mPAC; From d8ab6b83de0955107ca8fe857901c5da21b24e7f Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:26:48 +0100 Subject: [PATCH 006/229] Bug 1323100 - Use NS_NewNamedThread for IndexedDB threads. r=froydnj MozReview-Commit-ID: Do4l5QL2qSG --HG-- extra : rebase_source : 858b23dc85847849393e54709a68564d735bb638 --- dom/indexedDB/ActorsParent.cpp | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp index fc70257c2b81..1f84a832a0f0 100644 --- a/dom/indexedDB/ActorsParent.cpp +++ b/dom/indexedDB/ActorsParent.cpp @@ -5720,6 +5720,11 @@ public: return mSerialNumber; } + nsCString GetThreadName() const + { + return nsPrintfCString("IndexedDB #%lu", mSerialNumber); + } + private: ~ThreadRunnable() override; @@ -12571,7 +12576,10 @@ ConnectionPool::ScheduleTransaction(TransactionInfo* aTransactionInfo, RefPtr runnable = new ThreadRunnable(); nsCOMPtr newThread; - if (NS_SUCCEEDED(NS_NewThread(getter_AddRefs(newThread), runnable))) { + nsresult rv = + NS_NewNamedThread(runnable->GetThreadName(), + getter_AddRefs(newThread), runnable); + if (NS_SUCCEEDED(rv)) { MOZ_ASSERT(newThread); IDB_DEBUG_LOG(("ConnectionPool created thread %lu", @@ -13284,10 +13292,6 @@ nsresult ConnectionPool:: ThreadRunnable::Run() { -#ifdef MOZ_ENABLE_PROFILER_SPS - char stackTopGuess; -#endif // MOZ_ENABLE_PROFILER_SPS - MOZ_ASSERT(!IsOnBackgroundThread()); MOZ_ASSERT(mContinueRunning); @@ -13298,18 +13302,6 @@ ThreadRunnable::Run() mFirstRun = false; - { - // Scope for the thread name. Both PR_SetCurrentThreadName() and - // profiler_register_thread() copy the string so we don't need to keep it. - const nsPrintfCString threadName("IndexedDB #%lu", mSerialNumber); - - PR_SetCurrentThreadName(threadName.get()); - -#ifdef MOZ_ENABLE_PROFILER_SPS - profiler_register_thread(threadName.get(), &stackTopGuess); -#endif // MOZ_ENABLE_PROFILER_SPS - } - { // Scope for the profiler label. PROFILER_LABEL("IndexedDB", @@ -13351,10 +13343,6 @@ ThreadRunnable::Run() } } -#ifdef MOZ_ENABLE_PROFILER_SPS - profiler_unregister_thread(); -#endif // MOZ_ENABLE_PROFILER_SPS - return NS_OK; } From def3372d8379b93327d64a689af6b7bd0a342426 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:31:15 +0100 Subject: [PATCH 007/229] Bug 1323100 - Use NS_NewNamedThread for the Android Audio thread. r=froydnj MozReview-Commit-ID: IcKsOZCZVwB --HG-- extra : rebase_source : 2b5381faf2370792e715dfb20a7b274644f775f2 --- dom/plugins/base/android/ANPAudio.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/dom/plugins/base/android/ANPAudio.cpp b/dom/plugins/base/android/ANPAudio.cpp index bc47e8999e7a..dd4f0b29cdbe 100644 --- a/dom/plugins/base/android/ANPAudio.cpp +++ b/dom/plugins/base/android/ANPAudio.cpp @@ -122,8 +122,6 @@ public: NS_IMETHODIMP AudioRunnable::Run() { - PR_SetCurrentThreadName("Android Audio"); - JNIEnv* const jenv = mozilla::jni::GetEnvForThread(); mozilla::AutoLocalJNIFrame autoFrame(jenv, 2); @@ -321,7 +319,7 @@ anp_audio_start(ANPAudioTrack* s) RefPtr runnable = new AudioRunnable(s); nsCOMPtr thread; - NS_NewThread(getter_AddRefs(thread), runnable); + NS_NewNamedThread("Android Audio", getter_AddRefs(thread), runnable); } void From b50127ee0bd8c173b86b110526e94e76157b50dd Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:32:39 +0100 Subject: [PATCH 008/229] Bug 1323100 - Use NS_NewNamedThread for the Link Monitor thread. r=froydnj MozReview-Commit-ID: ETOGkxMgknN --HG-- extra : rebase_source : 253161c0028458c79f162b5b4d8fd9d57f36944c --- netwerk/system/win32/nsNotifyAddrListener.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/netwerk/system/win32/nsNotifyAddrListener.cpp b/netwerk/system/win32/nsNotifyAddrListener.cpp index 5d1ec3a61fe1..bebbf4d0efc9 100644 --- a/netwerk/system/win32/nsNotifyAddrListener.cpp +++ b/netwerk/system/win32/nsNotifyAddrListener.cpp @@ -323,8 +323,6 @@ nsNotifyAddrListener::nextCoalesceWaitTime() NS_IMETHODIMP nsNotifyAddrListener::Run() { - PR_SetCurrentThreadName("Link Monitor"); - mStartTime = TimeStamp::Now(); calculateNetworkId(); @@ -421,7 +419,7 @@ nsNotifyAddrListener::Init(void) mCheckEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); NS_ENSURE_TRUE(mCheckEvent, NS_ERROR_OUT_OF_MEMORY); - rv = NS_NewThread(getter_AddRefs(mThread), this); + rv = NS_NewNamedThread("Link Monitor", getter_AddRefs(mThread), this); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; From 948b3e46ecabeda21f824cd3593c100c21461009 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:33:21 +0100 Subject: [PATCH 009/229] Bug 1323100 - Use NS_NewNamedThread for the Wifi Monitor thread. r=froydnj MozReview-Commit-ID: 25lwf8WdANT --HG-- extra : rebase_source : 3f9accf44b8fd9f269d2e2a6b46aa1c8440d3a9c --- netwerk/wifi/nsWifiMonitor.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/netwerk/wifi/nsWifiMonitor.cpp b/netwerk/wifi/nsWifiMonitor.cpp index 4613a107dc61..2c1885f2be78 100644 --- a/netwerk/wifi/nsWifiMonitor.cpp +++ b/netwerk/wifi/nsWifiMonitor.cpp @@ -84,7 +84,7 @@ NS_IMETHODIMP nsWifiMonitor::StartWatching(nsIWifiListener *aListener) } if (!mThread) { - rv = NS_NewThread(getter_AddRefs(mThread), this); + rv = NS_NewNamedThread("Wifi Monitor", getter_AddRefs(mThread), this); if (NS_FAILED(rv)) return rv; } @@ -155,8 +155,6 @@ NS_IMETHODIMP nsWifiMonitor::Run() { LOG(("@@@@@ wifi monitor run called\n")); - PR_SetCurrentThreadName("Wifi Monitor"); - nsresult rv = DoScan(); LOG(("@@@@@ wifi monitor run::doscan complete %x\n", rv)); From 1725009245f4dd3165c90da37d4c88d4a2dce88d Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:34:36 +0100 Subject: [PATCH 010/229] Bug 1323100 - Use NS_NewNamedThread for the Filewatcher IO thread. r=froydnj MozReview-Commit-ID: 18qfXNx8BtJ --HG-- extra : rebase_source : 406d59b7e840466af49aa5197e12201764f3ed34 --- toolkit/components/filewatcher/NativeFileWatcherWin.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp index 8bb40bfd4d89..8e2ed8a7278e 100644 --- a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp +++ b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp @@ -1253,7 +1253,8 @@ NativeFileWatcherService::Init() // Start the IO worker thread. mWorkerIORunnable = new NativeFileWatcherIOTask(completionPort); - nsresult rv = NS_NewThread(getter_AddRefs(mIOThread), mWorkerIORunnable); + nsresult rv = NS_NewNamedThread("FileWatcher IO", getter_AddRefs(mIOThread), + mWorkerIORunnable); if (NS_FAILED(rv)) { FILEWATCHERLOG( "NativeFileWatcherIOTask::Init - Unable to create and dispatch the worker thread (%x).", @@ -1261,9 +1262,6 @@ NativeFileWatcherService::Init() return rv; } - // Set the name for the worker thread. - NS_SetThreadName(mIOThread, "FileWatcher IO"); - mIOCompletionPort = completionPort.forget(); return NS_OK; From 2e4dfba4763a54d8675e82e51c8990699a922e45 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 22 Dec 2016 00:05:51 +0100 Subject: [PATCH 011/229] Bug 1323100 - Create a version of NS_NewNamedThread that accepts an nsACString. r=froydnj MozReview-Commit-ID: LhRjdzZeWCB --HG-- extra : rebase_source : 350ec2fbdc535a72eed34dc20d67765e4602da4b --- xpcom/glue/nsThreadUtils.h | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index 309729a1e99a..3644f48b1238 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -71,9 +71,8 @@ NS_NewThread(nsIThread** aResult, /** * Creates a named thread, otherwise the same as NS_NewThread */ -template inline nsresult -NS_NewNamedThread(const char (&aName)[LEN], +NS_NewNamedThread(const nsACString& aName, nsIThread** aResult, nsIRunnable* aInitialEvent = nullptr, uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) @@ -84,7 +83,7 @@ NS_NewNamedThread(const char (&aName)[LEN], if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - NS_SetThreadName(thread, aName); + NS_SetThreadName(thread, aName); if (aInitialEvent) { rv = thread->Dispatch(aInitialEvent, NS_DISPATCH_NORMAL); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Initial event dispatch failed"); @@ -95,6 +94,19 @@ NS_NewNamedThread(const char (&aName)[LEN], return rv; } +template +inline nsresult +NS_NewNamedThread(const char (&aName)[LEN], + nsIThread** aResult, + nsIRunnable* aInitialEvent = nullptr, + uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) +{ + static_assert(LEN <= 16, + "Thread name must be no more than 16 characters"); + return NS_NewNamedThread(nsDependentCString(aName, LEN - 1), + aResult, aInitialEvent, aStackSize); +} + /** * Get a reference to the current thread. * From 1c1cc663394aa6ce26854062d2fbe3277bfcb5f2 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Mon, 12 Dec 2016 19:17:51 -0500 Subject: [PATCH 012/229] Bug 1323100 - Use NS_NewNamedThread in SingletonThreadHolder. r=froydnj MozReview-Commit-ID: Jcf5DfSrxrf --HG-- extra : rebase_source : 8ba5017efc93289570f4358fb1694692d935ba48 --- media/mtransport/nr_socket_prsock.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/media/mtransport/nr_socket_prsock.cpp b/media/mtransport/nr_socket_prsock.cpp index f22229df86f5..1aab40f8b478 100644 --- a/media/mtransport/nr_socket_prsock.cpp +++ b/media/mtransport/nr_socket_prsock.cpp @@ -212,10 +212,9 @@ public: nsrefcnt count = ++mUseCount; if (count == 1) { // idle -> in-use - nsresult rv = NS_NewThread(getter_AddRefs(mThread)); + nsresult rv = NS_NewNamedThread(mName, getter_AddRefs(mThread)); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && mThread, "Should successfully create mtransport I/O thread"); - NS_SetThreadName(mThread, mName); r_log(LOG_GENERIC,LOG_DEBUG,"Created wrapped SingletonThread %p", mThread.get()); } From 275c8d787e066390cfc3317cfa319a2ad0b83306 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:27:18 +0100 Subject: [PATCH 013/229] Bug 1323100 - Use NS_NewNamedThread for CryptoTask threads. r=froydnj MozReview-Commit-ID: 6c6iDuGyE2X --HG-- extra : rebase_source : 91520bffd5d9bd31caa27fb52cf7bd9aac86a732 --- security/manager/ssl/CryptoTask.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/security/manager/ssl/CryptoTask.cpp b/security/manager/ssl/CryptoTask.cpp index 71b8ac88d5b3..2ffc1d93159a 100644 --- a/security/manager/ssl/CryptoTask.cpp +++ b/security/manager/ssl/CryptoTask.cpp @@ -31,13 +31,13 @@ CryptoTask::Dispatch(const nsACString& taskThreadName) } // Can't add 'this' as the event to run, since mThread may not be set yet - nsresult rv = NS_NewThread(getter_AddRefs(mThread), nullptr, - nsIThreadManager::DEFAULT_STACK_SIZE); + nsresult rv = NS_NewNamedThread(taskThreadName, getter_AddRefs(mThread), + nullptr, + nsIThreadManager::DEFAULT_STACK_SIZE); if (NS_FAILED(rv)) { return rv; } - NS_SetThreadName(mThread, taskThreadName); // Note: event must not null out mThread! return mThread->Dispatch(this, NS_DISPATCH_NORMAL); } From 1cebff73d2a382128c32d4d1c6aa0384b35d6b56 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:43:50 +0100 Subject: [PATCH 014/229] Bug 1323100 - Assign names to all remaining threads that are created through NS_NewThread and create them using NS_NewNamedThread instead. r=froydnj MozReview-Commit-ID: 7W1dt2BBKJZ --HG-- extra : rebase_source : ad47978ef81d048a90b9803803201eee32974024 --- dom/gamepad/cocoa/CocoaGamepad.cpp | 5 +- dom/gamepad/windows/WindowsGamepad.cpp | 2 +- dom/media/FileBlockCache.cpp | 7 ++- .../android/AndroidMediaResourceServer.cpp | 2 +- dom/media/gtest/TestMP4Reader.cpp | 2 +- .../gonk/GonkGPSGeolocationProvider.cpp | 2 +- gfx/layers/LayerScope.cpp | 2 +- hal/gonk/GonkHal.cpp | 2 +- image/test/gtest/TestDecodeToSurface.cpp | 3 +- netwerk/base/BackgroundFileSaver.cpp | 2 +- netwerk/sctp/datachannel/DataChannel.cpp | 5 +- netwerk/test/TestFileInput2.cpp | 61 ++++++++++--------- .../test_service_init_background_thread.cpp | 2 +- .../url-classifier/tests/gtest/Common.cpp | 3 +- toolkit/crashreporter/nsExceptionHandler.cpp | 2 +- toolkit/identity/IdentityCryptoService.cpp | 5 +- toolkit/xre/nsUpdateDriver.cpp | 3 +- widget/windows/LSPAnnotator.cpp | 2 +- widget/windows/nsSound.cpp | 7 ++- xpcom/tests/gtest/TestPipes.cpp | 10 +-- .../tests/gtest/TestRacingServiceManager.cpp | 2 +- xpcom/tests/gtest/TestThreads.cpp | 11 ++-- xpcom/tests/gtest/TestTimers.cpp | 2 +- xpcom/threads/LazyIdleThread.cpp | 2 +- xpcom/threads/TimerThread.cpp | 3 +- 25 files changed, 84 insertions(+), 65 deletions(-) diff --git a/dom/gamepad/cocoa/CocoaGamepad.cpp b/dom/gamepad/cocoa/CocoaGamepad.cpp index e7c986e22a60..0000d616e223 100644 --- a/dom/gamepad/cocoa/CocoaGamepad.cpp +++ b/dom/gamepad/cocoa/CocoaGamepad.cpp @@ -541,8 +541,9 @@ DarwinGamepadService::StartupInternal() void DarwinGamepadService::Startup() { - Unused << NS_NewThread(getter_AddRefs(mMonitorThread), - new DarwinGamepadServiceStartupRunnable(this)); + Unused << NS_NewNamedThread("Gamepad", + getter_AddRefs(mMonitorThread), + new DarwinGamepadServiceStartupRunnable(this)); } void DarwinGamepadService::Shutdown() diff --git a/dom/gamepad/windows/WindowsGamepad.cpp b/dom/gamepad/windows/WindowsGamepad.cpp index 5f60fd0b79d8..7c2819ed05df 100644 --- a/dom/gamepad/windows/WindowsGamepad.cpp +++ b/dom/gamepad/windows/WindowsGamepad.cpp @@ -1065,7 +1065,7 @@ StartGamepadMonitoring() return; } sIsShutdown = false; - NS_NewThread(getter_AddRefs(gMonitorThread)); + NS_NewNamedThread("Gamepad", getter_AddRefs(gMonitorThread)); gMonitorThread->Dispatch(new StartWindowsGamepadServiceRunnable(), NS_DISPATCH_NORMAL); } diff --git a/dom/media/FileBlockCache.cpp b/dom/media/FileBlockCache.cpp index d85e6cd016de..16a3a0043f39 100644 --- a/dom/media/FileBlockCache.cpp +++ b/dom/media/FileBlockCache.cpp @@ -22,9 +22,10 @@ nsresult FileBlockCache::Open(PRFileDesc* aFD) } { MonitorAutoLock mon(mDataMonitor); - nsresult res = NS_NewThread(getter_AddRefs(mThread), - nullptr, - SharedThreadPool::kStackSize); + nsresult res = NS_NewNamedThread("FileBlockCache", + getter_AddRefs(mThread), + nullptr, + SharedThreadPool::kStackSize); mIsOpen = NS_SUCCEEDED(res); return res; } diff --git a/dom/media/android/AndroidMediaResourceServer.cpp b/dom/media/android/AndroidMediaResourceServer.cpp index bd76a8c68c49..f6ca13f5aa61 100644 --- a/dom/media/android/AndroidMediaResourceServer.cpp +++ b/dom/media/android/AndroidMediaResourceServer.cpp @@ -375,7 +375,7 @@ ResourceSocketListener::OnSocketAccepted(nsIServerSocket* aServ, if (NS_FAILED(rv)) return rv; nsCOMPtr thread; - rv = NS_NewThread(getter_AddRefs(thread)); + rv = NS_NewNamedThread("ServeResource", getter_AddRefs(thread)); if (NS_FAILED(rv)) return rv; nsCOMPtr event = new ServeResourceEvent(input.get(), output.get(), mServer); diff --git a/dom/media/gtest/TestMP4Reader.cpp b/dom/media/gtest/TestMP4Reader.cpp index f08f7a40da3c..2cf72681585c 100644 --- a/dom/media/gtest/TestMP4Reader.cpp +++ b/dom/media/gtest/TestMP4Reader.cpp @@ -44,7 +44,7 @@ public: void Init() { nsCOMPtr thread; nsCOMPtr r = NewRunnableMethod(this, &TestBinding::ReadMetadata); - nsresult rv = NS_NewThread(getter_AddRefs(thread), r); + nsresult rv = NS_NewNamedThread("ReadMetadata", getter_AddRefs(thread), r); EXPECT_EQ(NS_OK, rv); thread->Shutdown(); } diff --git a/dom/system/gonk/GonkGPSGeolocationProvider.cpp b/dom/system/gonk/GonkGPSGeolocationProvider.cpp index 9ce6ce2e5a30..b3336f02af12 100644 --- a/dom/system/gonk/GonkGPSGeolocationProvider.cpp +++ b/dom/system/gonk/GonkGPSGeolocationProvider.cpp @@ -556,7 +556,7 @@ GonkGPSGeolocationProvider::Startup() } if (!mInitThread) { - nsresult rv = NS_NewThread(getter_AddRefs(mInitThread)); + nsresult rv = NS_NewNamedThread("Gonk GPS", getter_AddRefs(mInitThread)); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/gfx/layers/LayerScope.cpp b/gfx/layers/LayerScope.cpp index a3b7778ef40f..55f87023d6d7 100644 --- a/gfx/layers/LayerScope.cpp +++ b/gfx/layers/LayerScope.cpp @@ -1569,7 +1569,7 @@ LayerScopeWebSocketManager::SocketHandler::CloseConnection() LayerScopeWebSocketManager::LayerScopeWebSocketManager() : mHandlerMutex("LayerScopeWebSocketManager::mHandlerMutex") { - NS_NewThread(getter_AddRefs(mDebugSenderThread)); + NS_NewNamedThread("LayerScope", getter_AddRefs(mDebugSenderThread)); mServerSocket = do_CreateInstance(NS_SERVERSOCKET_CONTRACTID); int port = gfxPrefs::LayerScopePort(); diff --git a/hal/gonk/GonkHal.cpp b/hal/gonk/GonkHal.cpp index 05d9295a225d..e2ca40fbbac6 100644 --- a/hal/gonk/GonkHal.cpp +++ b/hal/gonk/GonkHal.cpp @@ -395,7 +395,7 @@ EnsureVibratorThreadInitialized() sVibratorRunnable = new VibratorRunnable(); nsCOMPtr thread; - NS_NewThread(getter_AddRefs(thread), sVibratorRunnable); + NS_NewNamedThread("Gonk Vibrator", getter_AddRefs(thread), sVibratorRunnable); } } // namespace diff --git a/image/test/gtest/TestDecodeToSurface.cpp b/image/test/gtest/TestDecodeToSurface.cpp index bd52e75901c8..278cdb1fdc89 100644 --- a/image/test/gtest/TestDecodeToSurface.cpp +++ b/image/test/gtest/TestDecodeToSurface.cpp @@ -69,7 +69,8 @@ RunDecodeToSurface(const ImageTestCase& aTestCase) ASSERT_TRUE(inputStream != nullptr); nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), nullptr); + nsresult rv = + NS_NewNamedThread("DecodeToSurface", getter_AddRefs(thread), nullptr); ASSERT_TRUE(NS_SUCCEEDED(rv)); // We run the DecodeToSurface tests off-main-thread to ensure that diff --git a/netwerk/base/BackgroundFileSaver.cpp b/netwerk/base/BackgroundFileSaver.cpp index e4bc05826249..ee81113006b3 100644 --- a/netwerk/base/BackgroundFileSaver.cpp +++ b/netwerk/base/BackgroundFileSaver.cpp @@ -152,7 +152,7 @@ BackgroundFileSaver::Init() rv = NS_GetCurrentThread(getter_AddRefs(mControlThread)); NS_ENSURE_SUCCESS(rv, rv); - rv = NS_NewThread(getter_AddRefs(mWorkerThread)); + rv = NS_NewNamedThread("BgFileSaver", getter_AddRefs(mWorkerThread)); NS_ENSURE_SUCCESS(rv, rv); sThreadCount++; diff --git a/netwerk/sctp/datachannel/DataChannel.cpp b/netwerk/sctp/datachannel/DataChannel.cpp index 98810061bb24..b5adef05ab66 100644 --- a/netwerk/sctp/datachannel/DataChannel.cpp +++ b/netwerk/sctp/datachannel/DataChannel.cpp @@ -2326,8 +2326,9 @@ DataChannelConnection::SendBlob(uint16_t stream, nsIInputStream *aBlob) NS_ENSURE_TRUE(channel, 0); // Spawn a thread to send the data if (!mInternalIOThread) { - nsresult res = NS_NewThread(getter_AddRefs(mInternalIOThread)); - if (NS_FAILED(res)) { + nsresult rv = NS_NewNamedThread("DataChannel IO", + getter_AddRefs(mInternalIOThread)); + if (NS_FAILED(rv)) { return -1; } } diff --git a/netwerk/test/TestFileInput2.cpp b/netwerk/test/TestFileInput2.cpp index f51988010e20..a23437891b9d 100644 --- a/netwerk/test/TestFileInput2.cpp +++ b/netwerk/test/TestFileInput2.cpp @@ -315,7 +315,7 @@ NS_IMPL_ISUPPORTS(FileChannelWorker, nsIRunnable) //////////////////////////////////////////////////////////////////////////////// void -Test(CreateFun create, uint32_t count, +Test(CreateFun create, const char* name, uint32_t count, nsIFile* inDirSpec, nsIFile* outDirSpec, uint32_t bufSize) { nsresult rv; @@ -375,7 +375,8 @@ Test(CreateFun create, uint32_t count, bufSize); if (NS_FAILED(rv)) goto done; - rv = NS_NewThread(getter_AddRefs(thread), worker, 0, PR_JOINABLE_THREAD); + rv = NS_NewNamedThread(name, getter_AddRefs(thread), + worker, 0, PR_JOINABLE_THREAD); if (NS_FAILED(rv)) goto done; bool inserted = threads.InsertObjectAt(thread, i); @@ -433,42 +434,44 @@ main(int argc, char* argv[]) if (NS_FAILED(rv)) return rv; CreateFun create = FileChannelWorker::Create; + const char* name = "FileChannelWorker"; Test(create, 1, inDirFile, outDirFile, 16 * 1024); #if 1 printf("FileChannelWorker *****************************\n"); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); #endif create = FileSpecWorker::Create; + name = "FileSpecWorker"; printf("FileSpecWorker ********************************\n"); #if 1 - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); #endif #if 1 - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); #endif } // this scopes the nsCOMPtrs // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM diff --git a/storage/test/gtest/test_service_init_background_thread.cpp b/storage/test/gtest/test_service_init_background_thread.cpp index 022026cbaefd..e811e249702b 100644 --- a/storage/test/gtest/test_service_init_background_thread.cpp +++ b/storage/test/gtest/test_service_init_background_thread.cpp @@ -46,7 +46,7 @@ TEST(storage_service_init_background_thread_DeathTest, Test) do_check_true(event); nsCOMPtr thread; - do_check_success(NS_NewThread(getter_AddRefs(thread))); + do_check_success(NS_NewNamedThread("StorageService", getter_AddRefs(thread))); do_check_success(thread->Dispatch(event, NS_DISPATCH_NORMAL)); diff --git a/toolkit/components/url-classifier/tests/gtest/Common.cpp b/toolkit/components/url-classifier/tests/gtest/Common.cpp index b5f024b38e41..b2c9bad8bc41 100644 --- a/toolkit/components/url-classifier/tests/gtest/Common.cpp +++ b/toolkit/components/url-classifier/tests/gtest/Common.cpp @@ -14,7 +14,8 @@ template void RunTestInNewThread(Function&& aFunction) { nsCOMPtr r = NS_NewRunnableFunction(mozilla::Forward(aFunction)); nsCOMPtr testingThread; - nsresult rv = NS_NewThread(getter_AddRefs(testingThread), r); + nsresult rv = + NS_NewNamedThread("Testing Thread", getter_AddRefs(testingThread), r); ASSERT_EQ(rv, NS_OK); testingThread->Shutdown(); } diff --git a/toolkit/crashreporter/nsExceptionHandler.cpp b/toolkit/crashreporter/nsExceptionHandler.cpp index 9fd69f504830..5922b9b80c2d 100644 --- a/toolkit/crashreporter/nsExceptionHandler.cpp +++ b/toolkit/crashreporter/nsExceptionHandler.cpp @@ -3609,7 +3609,7 @@ InjectCrashReporterIntoProcess(DWORD processID, InjectorCrashCallback* cb) OOPInit(); if (!sInjectorThread) { - if (NS_FAILED(NS_NewThread(&sInjectorThread))) + if (NS_FAILED(NS_NewNamedThread("CrashRep Inject", &sInjectorThread))) return; } diff --git a/toolkit/identity/IdentityCryptoService.cpp b/toolkit/identity/IdentityCryptoService.cpp index 0aeaed2f3f94..5ad3fd19c9d4 100644 --- a/toolkit/identity/IdentityCryptoService.cpp +++ b/toolkit/identity/IdentityCryptoService.cpp @@ -205,7 +205,8 @@ IdentityCryptoService::GenerateKeyPair( nsCOMPtr r = new KeyGenRunnable(keyType, callback); nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), r); + nsresult rv = NS_NewNamedThread("GenerateKeyPair", getter_AddRefs(thread), + r); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -309,7 +310,7 @@ KeyPair::Sign(const nsACString & textToSign, callback); nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), r); + nsresult rv = NS_NewNamedThread("KeyPair Sign", getter_AddRefs(thread), r); return rv; } diff --git a/toolkit/xre/nsUpdateDriver.cpp b/toolkit/xre/nsUpdateDriver.cpp index ce60c652187a..8c1bb9bca843 100644 --- a/toolkit/xre/nsUpdateDriver.cpp +++ b/toolkit/xre/nsUpdateDriver.cpp @@ -1246,7 +1246,8 @@ nsUpdateProcessor::ProcessUpdate(nsIUpdate* aUpdate) MOZ_ASSERT(NS_IsMainThread(), "not main thread"); nsCOMPtr r = NewRunnableMethod(this, &nsUpdateProcessor::StartStagedUpdate); - return NS_NewThread(getter_AddRefs(mProcessWatcher), r); + return NS_NewNamedThread("Update Watcher", getter_AddRefs(mProcessWatcher), + r); } diff --git a/widget/windows/LSPAnnotator.cpp b/widget/windows/LSPAnnotator.cpp index 5b0c1d14b484..5e8f465116e1 100644 --- a/widget/windows/LSPAnnotator.cpp +++ b/widget/windows/LSPAnnotator.cpp @@ -151,7 +151,7 @@ void LSPAnnotate() nsCOMPtr thread; nsCOMPtr runnable = do_QueryObject(new LSPAnnotationGatherer()); - NS_NewThread(getter_AddRefs(thread), runnable); + NS_NewNamedThread("LSP Annotate", getter_AddRefs(thread), runnable); } } // namespace crashreporter diff --git a/widget/windows/nsSound.cpp b/widget/windows/nsSound.cpp index 5635f8356b9d..a22e048df3ef 100644 --- a/widget/windows/nsSound.cpp +++ b/widget/windows/nsSound.cpp @@ -241,7 +241,9 @@ NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias) return NS_OK; nsCOMPtr player = new nsSoundPlayer(this, aSoundAlias); NS_ENSURE_TRUE(player, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = NS_NewThread(getter_AddRefs(mPlayerThread), player); + nsresult rv = + NS_NewNamedThread("PlaySystemSound", getter_AddRefs(mPlayerThread), + player); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } @@ -299,7 +301,8 @@ NS_IMETHODIMP nsSound::PlayEventSound(uint32_t aEventId) nsCOMPtr player = new nsSoundPlayer(this, sound); NS_ENSURE_TRUE(player, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = NS_NewThread(getter_AddRefs(mPlayerThread), player); + nsresult rv = + NS_NewNamedThread("PlayEventSound", getter_AddRefs(mPlayerThread), player); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } diff --git a/xpcom/tests/gtest/TestPipes.cpp b/xpcom/tests/gtest/TestPipes.cpp index 87b923008258..5bf31c94197e 100644 --- a/xpcom/tests/gtest/TestPipes.cpp +++ b/xpcom/tests/gtest/TestPipes.cpp @@ -107,7 +107,7 @@ TestPipe(nsIInputStream* in, nsIOutputStream* out) nsresult rv; nsCOMPtr thread; - rv = NS_NewThread(getter_AddRefs(thread), receiver); + rv = NS_NewNamedThread("TestPipe", getter_AddRefs(thread), receiver); if (NS_FAILED(rv)) return rv; uint32_t total = 0; @@ -225,7 +225,8 @@ TestShortWrites(nsIInputStream* in, nsIOutputStream* out) nsresult rv; nsCOMPtr thread; - rv = NS_NewThread(getter_AddRefs(thread), receiver); + rv = NS_NewNamedThread("TestShortWrites", getter_AddRefs(thread), + receiver); if (NS_FAILED(rv)) return rv; uint32_t total = 0; @@ -330,14 +331,15 @@ TEST(Pipes, ChainedPipes) if (pump == nullptr) return; nsCOMPtr thread; - rv = NS_NewThread(getter_AddRefs(thread), pump); + rv = NS_NewNamedThread("ChainedPipePump", getter_AddRefs(thread), pump); if (NS_FAILED(rv)) return; RefPtr receiver = new nsReceiver(in2); if (receiver == nullptr) return; nsCOMPtr receiverThread; - rv = NS_NewThread(getter_AddRefs(receiverThread), receiver); + rv = NS_NewNamedThread("ChainedPipeRecv", getter_AddRefs(receiverThread), + receiver); if (NS_FAILED(rv)) return; uint32_t total = 0; diff --git a/xpcom/tests/gtest/TestRacingServiceManager.cpp b/xpcom/tests/gtest/TestRacingServiceManager.cpp index b0638db02f48..1309083ed853 100644 --- a/xpcom/tests/gtest/TestRacingServiceManager.cpp +++ b/xpcom/tests/gtest/TestRacingServiceManager.cpp @@ -255,7 +255,7 @@ TEST(RacingServiceManager, Test) // Run the classID test nsCOMPtr newThread; - rv = NS_NewThread(getter_AddRefs(newThread), runnable); + rv = NS_NewNamedThread("RacingServMan", getter_AddRefs(newThread), runnable); ASSERT_TRUE(NS_SUCCEEDED(rv)); { diff --git a/xpcom/tests/gtest/TestThreads.cpp b/xpcom/tests/gtest/TestThreads.cpp index 4f6055dce9b9..4d47f2649415 100644 --- a/xpcom/tests/gtest/TestThreads.cpp +++ b/xpcom/tests/gtest/TestThreads.cpp @@ -49,7 +49,7 @@ TEST(Threads, Main) EXPECT_TRUE(event); nsCOMPtr runner; - rv = NS_NewThread(getter_AddRefs(runner), event); + rv = NS_NewNamedThread("TestThreadsMain", getter_AddRefs(runner), event); EXPECT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr thread; @@ -112,7 +112,8 @@ TEST(Threads, Stress) for (k = 0; k < threads; k++) { nsCOMPtr t; - nsresult rv = NS_NewThread(getter_AddRefs(t), new nsStressRunner(k)); + nsresult rv = NS_NewNamedThread("StressRunner", getter_AddRefs(t), + new nsStressRunner(k)); EXPECT_TRUE(NS_SUCCEEDED(rv)); NS_ADDREF(array[k] = t); } @@ -169,7 +170,8 @@ public: { mozilla::MonitorAutoLock lock(*gBeginAsyncShutdownMonitor); - rv = NS_NewThread(getter_AddRefs(t), new AsyncShutdownPreparer()); + rv = NS_NewNamedThread("AsyncShutdownPr", getter_AddRefs(t), + new AsyncShutdownPreparer()); EXPECT_TRUE(NS_SUCCEEDED(rv)); lock.Wait(); @@ -221,7 +223,8 @@ TEST(Threads, AsyncShutdown) { mozilla::MonitorAutoLock lock(*gAsyncShutdownReadyMonitor); - rv = NS_NewThread(getter_AddRefs(t), new AsyncShutdownWaiter()); + rv = NS_NewNamedThread("AsyncShutdownWt", getter_AddRefs(t), + new AsyncShutdownWaiter()); EXPECT_TRUE(NS_SUCCEEDED(rv)); lock.Wait(); diff --git a/xpcom/tests/gtest/TestTimers.cpp b/xpcom/tests/gtest/TestTimers.cpp index fe7520ab1018..524e1e8b3f7b 100644 --- a/xpcom/tests/gtest/TestTimers.cpp +++ b/xpcom/tests/gtest/TestTimers.cpp @@ -31,7 +31,7 @@ class AutoTestThread public: AutoTestThread() { nsCOMPtr newThread; - nsresult rv = NS_NewThread(getter_AddRefs(newThread)); + nsresult rv = NS_NewNamedThread("AutoTestThread", getter_AddRefs(newThread)); if (NS_FAILED(rv)) return; diff --git a/xpcom/threads/LazyIdleThread.cpp b/xpcom/threads/LazyIdleThread.cpp index 527cc681962f..b6218e959292 100644 --- a/xpcom/threads/LazyIdleThread.cpp +++ b/xpcom/threads/LazyIdleThread.cpp @@ -169,7 +169,7 @@ LazyIdleThread::EnsureThread() return NS_ERROR_UNEXPECTED; } - rv = NS_NewThread(getter_AddRefs(mThread), runnable); + rv = NS_NewNamedThread("Lazy Idle", getter_AddRefs(mThread), runnable); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/xpcom/threads/TimerThread.cpp b/xpcom/threads/TimerThread.cpp index 8536f0395ab7..da4bc6edba26 100644 --- a/xpcom/threads/TimerThread.cpp +++ b/xpcom/threads/TimerThread.cpp @@ -323,7 +323,8 @@ TimerThread::Init() if (mInitInProgress.exchange(true) == false) { // We hold on to mThread to keep the thread alive. - nsresult rv = NS_NewThread(getter_AddRefs(mThread), this); + nsresult rv = + NS_NewNamedThread("Timer Thread", getter_AddRefs(mThread), this); if (NS_FAILED(rv)) { mThread = nullptr; } else { From 5c622cb38b6d86c3f4c204af39cc7c8d6ed4f39d Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 22 Dec 2016 00:38:41 +0100 Subject: [PATCH 015/229] Bug 1323100 - Create nsThreadPoolNaming::GetNextThreadName. r=froydnj MozReview-Commit-ID: F0ZFFa5VkAW --HG-- extra : rebase_source : 9ebc1118e30bf841af2a2d1df3ada4d31e4035bd --- xpcom/glue/nsThreadUtils.cpp | 13 ++++++++++--- xpcom/glue/nsThreadUtils.h | 11 +++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index 994f71de7d25..7374f54d9251 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -440,13 +440,20 @@ NS_GetCurrentThread() #endif // nsThreadPoolNaming +nsCString +nsThreadPoolNaming::GetNextThreadName(const nsACString& aPoolName) +{ + nsCString name(aPoolName); + name.AppendLiteral(" #"); + name.AppendInt(++mCounter, 10); // The counter is declared as atomic + return name; +} + void nsThreadPoolNaming::SetThreadPoolName(const nsACString& aPoolName, nsIThread* aThread) { - nsCString name(aPoolName); - name.AppendLiteral(" #"); - name.AppendInt(++mCounter, 10); // The counter is declared as volatile + nsCString name = GetNextThreadName(aPoolName); if (aThread) { // Set on the target thread diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index 3644f48b1238..d9671b160fb2 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -1037,6 +1037,17 @@ class nsThreadPoolNaming public: nsThreadPoolNaming() : mCounter(0) {} + /** + * Returns a thread name as " #" and increments the counter. + */ + nsCString GetNextThreadName(const nsACString& aPoolName); + + template + nsCString GetNextThreadName(const char (&aPoolName)[LEN]) + { + return GetNextThreadName(nsDependentCString(aPoolName, LEN - 1)); + } + /** * Creates and sets next thread name as " #" * on the specified thread. If no thread is specified (aThread From d37515f5e652109c46b0741d091d8e9636530617 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:20:15 +0100 Subject: [PATCH 016/229] Bug 1323100 - Use nsThreadPoolNaming::GetNextThreadName and NS_NewNamedThread for the mozStorage thread. r=froydnj MozReview-Commit-ID: 145CjwiQawB --HG-- extra : rebase_source : 9403849151907d2437f6874f8a7bd4d539394417 --- storage/mozStorageConnection.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/storage/mozStorageConnection.cpp b/storage/mozStorageConnection.cpp index 2ad50fb51d21..6129ac4442a1 100644 --- a/storage/mozStorageConnection.cpp +++ b/storage/mozStorageConnection.cpp @@ -589,14 +589,13 @@ Connection::getAsyncExecutionTarget() return nullptr; if (!mAsyncExecutionThread) { - nsresult rv = ::NS_NewThread(getter_AddRefs(mAsyncExecutionThread)); + static nsThreadPoolNaming naming; + nsresult rv = NS_NewNamedThread(naming.GetNextThreadName("mozStorage"), + getter_AddRefs(mAsyncExecutionThread)); if (NS_FAILED(rv)) { NS_WARNING("Failed to create async thread."); return nullptr; } - static nsThreadPoolNaming naming; - naming.SetThreadPoolName(NS_LITERAL_CSTRING("mozStorage"), - mAsyncExecutionThread); } #ifdef DEBUG From 5eb94382181da5c2bb0d761a6d2f57a21271e3b5 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:20:48 +0100 Subject: [PATCH 017/229] Bug 1323100 - Use nsThreadPoolNaming::GetNextThreadName and NS_NewNamedThread in the DecodePool. r=froydnj MozReview-Commit-ID: CAbaAe0bKe8 --HG-- extra : rebase_source : bc0db71ff4dd1031ea74c292b2162e0ac8f302f2 --- image/DecodePool.cpp | 27 +++++++-------------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/image/DecodePool.cpp b/image/DecodePool.cpp index 9aa3d58229f4..8053b2f9d19d 100644 --- a/image/DecodePool.cpp +++ b/image/DecodePool.cpp @@ -60,14 +60,6 @@ public: , mShuttingDown(false) { } - /// Initialize the current thread for use by the decode pool. - void InitCurrentThread() - { - MOZ_ASSERT(!NS_IsMainThread()); - - mThreadNaming.SetThreadPoolName(NS_LITERAL_CSTRING("ImgDecoder")); - } - /// Shut down the provided decode pool thread. static void ShutdownThread(nsIThread* aThisThread) { @@ -135,6 +127,12 @@ public: } while (true); } + nsresult CreateThread(nsIThread** aThread, nsIRunnable* aInitialEvent) + { + return NS_NewNamedThread(mThreadNaming.GetNextThreadName("ImgDecoder"), + aThread, aInitialEvent); + } + private: ~DecodePoolImpl() { } @@ -166,22 +164,11 @@ public: NS_IMETHOD Run() override { -#ifdef MOZ_ENABLE_PROFILER_SPS - char stackBaseGuess; // Need to be the first variable of main loop function. -#endif // MOZ_ENABLE_PROFILER_SPS - MOZ_ASSERT(!NS_IsMainThread()); - mImpl->InitCurrentThread(); - nsCOMPtr thisThread; nsThreadManager::get().GetCurrentThread(getter_AddRefs(thisThread)); -#ifdef MOZ_ENABLE_PROFILER_SPS - // InitCurrentThread() has assigned the thread name. - profiler_register_thread(PR_GetThreadName(PR_GetCurrentThread()), &stackBaseGuess); -#endif // MOZ_ENABLE_PROFILER_SPS - do { Work work = mImpl->PopWork(); switch (work.mType) { @@ -272,7 +259,7 @@ DecodePool::DecodePool() for (uint32_t i = 0 ; i < limit ; ++i) { nsCOMPtr worker = new DecodePoolWorker(mImpl); nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), worker); + nsresult rv = mImpl->CreateThread(getter_AddRefs(thread), worker); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && thread, "Should successfully create image decoding threads"); mThreads.AppendElement(Move(thread)); From db237ad713ffe79491a12b8d88b58bb1d7ae4999 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 22 Dec 2016 00:14:30 +0100 Subject: [PATCH 018/229] Bug 1323100 - Use nsThreadPoolNaming::GetNextThreadName and NS_NewNamedThread in nsThreadPool. r=froydnj MozReview-Commit-ID: 6IB5yvJtAQm --HG-- extra : rebase_source : d4d9bf2dab3e75821e931a11fa0a16f6ee1eb970 --- xpcom/threads/nsThreadPool.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/xpcom/threads/nsThreadPool.cpp b/xpcom/threads/nsThreadPool.cpp index 241fad39dcc2..f1d849ed1a85 100644 --- a/xpcom/threads/nsThreadPool.cpp +++ b/xpcom/threads/nsThreadPool.cpp @@ -104,8 +104,9 @@ nsThreadPool::PutEvent(already_AddRefed aEvent, uint32_t aFlags) } nsCOMPtr thread; - nsThreadManager::get().NewThread(0, stackSize, getter_AddRefs(thread)); - if (NS_WARN_IF(!thread)) { + nsresult rv = NS_NewNamedThread(mThreadNaming.GetNextThreadName(mName), + getter_AddRefs(thread), nullptr, stackSize); + if (NS_WARN_IF(NS_FAILED(rv))) { return NS_ERROR_UNEXPECTED; } @@ -152,8 +153,6 @@ nsThreadPool::ShutdownThread(nsIThread* aThread) NS_IMETHODIMP nsThreadPool::Run() { - mThreadNaming.SetThreadPoolName(mName); - LOG(("THRD-P(%p) enter %s\n", this, mName.BeginReading())); nsCOMPtr current; From 34233ed3270eafa65202f30c516652342550ff57 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:21:34 +0100 Subject: [PATCH 019/229] Bug 1323100 - Use nsThreadPoolNaming::GetNextThreadName for the DNS resolver thread. r=froydnj MozReview-Commit-ID: EQvKoIIorKG --HG-- extra : rebase_source : a386139905d17c7c5bcfb9dad887dbb9b82597fd --- netwerk/dns/nsHostResolver.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index f2e26cadd4eb..78cdfebf0909 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -1438,7 +1438,9 @@ nsHostResolver::ThreadFunc(void *arg) LOG(("DNS lookup thread - starting execution.\n")); static nsThreadPoolNaming naming; - naming.SetThreadPoolName(NS_LITERAL_CSTRING("DNS Resolver")); + nsCString name = naming.GetNextThreadName("DNS Resolver"); + + PR_SetCurrentThreadName(name.BeginReading()); #if defined(RES_RETRY_ON_FAILURE) nsResState rs; From e05e8b464889f86c7fec6c1957095bd094e8b643 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Mon, 19 Dec 2016 16:16:50 +0100 Subject: [PATCH 020/229] Bug 1323100 - Remove nsThreadPoolNaming::SetThreadPoolName because it's now unused. r=froydnj MozReview-Commit-ID: CYgF2NGD6pt --HG-- extra : rebase_source : cc09c212670d845c00629903b477674806618699 extra : source : 1cd63b3998c4a4c2ef5c59eee24bd344b2d3bc6d --- xpcom/glue/nsThreadUtils.cpp | 17 ----------------- xpcom/glue/nsThreadUtils.h | 8 -------- 2 files changed, 25 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index 7374f54d9251..a6d570a534c0 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -448,23 +448,6 @@ nsThreadPoolNaming::GetNextThreadName(const nsACString& aPoolName) name.AppendInt(++mCounter, 10); // The counter is declared as atomic return name; } - -void -nsThreadPoolNaming::SetThreadPoolName(const nsACString& aPoolName, - nsIThread* aThread) -{ - nsCString name = GetNextThreadName(aPoolName); - - if (aThread) { - // Set on the target thread - NS_SetThreadName(aThread, name); - } else { - // Set on the current thread -#ifndef XPCOM_GLUE_AVOID_NSPR - PR_SetCurrentThreadName(name.BeginReading()); -#endif - } -} // nsAutoLowPriorityIO nsAutoLowPriorityIO::nsAutoLowPriorityIO() diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index d9671b160fb2..87d9dbcd3076 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -1048,14 +1048,6 @@ public: return GetNextThreadName(nsDependentCString(aPoolName, LEN - 1)); } - /** - * Creates and sets next thread name as " #" - * on the specified thread. If no thread is specified (aThread - * is null) then the name is synchronously set on the current thread. - */ - void SetThreadPoolName(const nsACString& aPoolName, - nsIThread* aThread = nullptr); - private: mozilla::Atomic mCounter; From 32ca34d9771d0328c88c837c3a17249ad80731e0 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 15:10:20 +0100 Subject: [PATCH 021/229] Bug 1323100 - Add nsThreadManager::NewNamedThread API. r=froydnj The point of this exercise is to make the thread name available in the thread func of the thread, so that we can register the thread with the profiler from the very start of its lifetime, and so that registration and unregistration can be inside the same function. MozReview-Commit-ID: DiiMKUQVr55 --HG-- extra : rebase_source : aa1d0c19250765c80c8e8ae59d2752bb4ad7eeac --- xpcom/threads/nsIThreadManager.idl | 14 ++++++++++++++ xpcom/threads/nsThread.cpp | 26 +++++++++++++++++++++++--- xpcom/threads/nsThread.h | 4 ++-- xpcom/threads/nsThreadManager.cpp | 10 +++++++++- 4 files changed, 48 insertions(+), 6 deletions(-) diff --git a/xpcom/threads/nsIThreadManager.idl b/xpcom/threads/nsIThreadManager.idl index 9b4fc126f9b3..fa0f037c2712 100644 --- a/xpcom/threads/nsIThreadManager.idl +++ b/xpcom/threads/nsIThreadManager.idl @@ -35,6 +35,20 @@ interface nsIThreadManager : nsISupports */ nsIThread newThread(in unsigned long creationFlags, [optional] in unsigned long stackSize); + /** + * Create a new thread (a global, user PRThread) with the specified name. + * + * @param name + * The name of the thread. Passing an empty name is equivalent to + * calling newThread(0, stackSize), i.e. the thread will not be named. + * @param stackSize + * Number of bytes to reserve for the thread's stack. + * + * @returns + * The newly created nsIThread object. + */ + [noscript] nsIThread newNamedThread(in ACString name, [optional] in unsigned long stackSize); + /** * Get the nsIThread object (if any) corresponding to the given PRThread. * This method returns null if there is no corresponding nsIThread. diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp index 6c0f898240ae..fd45e79c4ea7 100644 --- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -432,15 +432,30 @@ SetupCurrentThreadForChaosMode() } } +namespace { + +struct ThreadInitData { + nsThread* thread; + const nsACString& name; +}; + +} + /*static*/ void nsThread::ThreadFunc(void* aArg) { using mozilla::ipc::BackgroundChild; - nsThread* self = static_cast(aArg); // strong reference + ThreadInitData* initData = static_cast(aArg); + nsThread* self = initData->thread; // strong reference + self->mThread = PR_GetCurrentThread(); SetupCurrentThreadForChaosMode(); + if (initData->name.Length() > 0) { + PR_SetCurrentThreadName(initData->name.BeginReading()); + } + // Inform the ThreadManager nsThreadManager::get().RegisterCurrentThread(*self); @@ -455,6 +470,9 @@ nsThread::ThreadFunc(void* aArg) return; } } + + initData = nullptr; // clear before unblocking nsThread::Init + event->Run(); // unblocks nsThread::Init event = nullptr; @@ -628,7 +646,7 @@ nsThread::~nsThread() } nsresult -nsThread::Init() +nsThread::Init(const nsACString& aName) { // spawn thread and wait until it is fully setup RefPtr startup = new nsThreadStartupEvent(); @@ -639,8 +657,10 @@ nsThread::Init() mShutdownRequired = true; + ThreadInitData initData = { this, aName }; + // ThreadFunc is responsible for setting mThread - if (!PR_CreateThread(PR_USER_THREAD, ThreadFunc, this, + if (!PR_CreateThread(PR_USER_THREAD, ThreadFunc, &initData, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, mStackSize)) { NS_RELEASE_THIS(); diff --git a/xpcom/threads/nsThread.h b/xpcom/threads/nsThread.h index 836123747aad..fd8209b0b5c4 100644 --- a/xpcom/threads/nsThread.h +++ b/xpcom/threads/nsThread.h @@ -48,8 +48,8 @@ public: nsThread(MainThreadFlag aMainThread, uint32_t aStackSize); - // Initialize this as a wrapper for a new PRThread. - nsresult Init(); + // Initialize this as a wrapper for a new PRThread, and optionally give it a name. + nsresult Init(const nsACString& aName = NS_LITERAL_CSTRING("")); // Initialize this as a wrapper for the current PRThread. nsresult InitCurrentThread(); diff --git a/xpcom/threads/nsThreadManager.cpp b/xpcom/threads/nsThreadManager.cpp index d1eb84b8f84c..217e557a8274 100644 --- a/xpcom/threads/nsThreadManager.cpp +++ b/xpcom/threads/nsThreadManager.cpp @@ -248,6 +248,14 @@ NS_IMETHODIMP nsThreadManager::NewThread(uint32_t aCreationFlags, uint32_t aStackSize, nsIThread** aResult) +{ + return NewNamedThread(NS_LITERAL_CSTRING(""), aStackSize, aResult); +} + +NS_IMETHODIMP +nsThreadManager::NewNamedThread(const nsACString& aName, + uint32_t aStackSize, + nsIThread** aResult) { // Note: can be called from arbitrary threads @@ -257,7 +265,7 @@ nsThreadManager::NewThread(uint32_t aCreationFlags, } RefPtr thr = new nsThread(nsThread::NOT_MAIN_THREAD, aStackSize); - nsresult rv = thr->Init(); // Note: blocks until the new thread has been set up + nsresult rv = thr->Init(aName); // Note: blocks until the new thread has been set up if (NS_FAILED(rv)) { return rv; } From f7a18ffd6a4a02de0970f9a1a4f28d0c130b80c2 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:18:22 +0100 Subject: [PATCH 022/229] Bug 1323100 - Make NS_NewNamedThread use nsThreadManager::NewNamedThread. r=froydnj MozReview-Commit-ID: 7e6l1A89he9 --HG-- extra : rebase_source : 0bbd888a568937710d3bb6cd5b856063e3405ae6 --- xpcom/glue/nsThreadUtils.cpp | 17 +++++++++++++---- xpcom/glue/nsThreadUtils.h | 21 ++------------------- 2 files changed, 15 insertions(+), 23 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index a6d570a534c0..8f9cb092e15b 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -95,13 +95,16 @@ IncrementalRunnable::SetDeadline(TimeStamp aDeadline) //----------------------------------------------------------------------------- nsresult -NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) +NS_NewNamedThread(const nsACString& aName, + nsIThread** aResult, + nsIRunnable* aEvent, + uint32_t aStackSize) { nsCOMPtr thread; #ifdef MOZILLA_INTERNAL_API nsresult rv = - nsThreadManager::get().nsThreadManager::NewThread(0, aStackSize, - getter_AddRefs(thread)); + nsThreadManager::get().nsThreadManager::NewNamedThread(aName, aStackSize, + getter_AddRefs(thread)); #else nsresult rv; nsCOMPtr mgr = @@ -110,7 +113,7 @@ NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) return rv; } - rv = mgr->NewThread(0, aStackSize, getter_AddRefs(thread)); + rv = mgr->NewNamedThread(aName, aStackSize, getter_AddRefs(thread)); #endif if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -128,6 +131,12 @@ NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) return NS_OK; } +nsresult +NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) +{ + return NS_NewNamedThread(NS_LITERAL_CSTRING(""), aResult, aEvent, aStackSize); +} + nsresult NS_GetCurrentThread(nsIThread** aResult) { diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index 87d9dbcd3076..a398e6c91c8f 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -71,28 +71,11 @@ NS_NewThread(nsIThread** aResult, /** * Creates a named thread, otherwise the same as NS_NewThread */ -inline nsresult +extern nsresult NS_NewNamedThread(const nsACString& aName, nsIThread** aResult, nsIRunnable* aInitialEvent = nullptr, - uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) -{ - // Hold a ref while dispatching the initial event to match NS_NewThread() - nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), nullptr, aStackSize); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - NS_SetThreadName(thread, aName); - if (aInitialEvent) { - rv = thread->Dispatch(aInitialEvent, NS_DISPATCH_NORMAL); - NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Initial event dispatch failed"); - } - - *aResult = nullptr; - thread.swap(*aResult); - return rv; -} + uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE); template inline nsresult From 83a9b3b26b3331572346b4d4ab665e90547453cf Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:43:11 +0100 Subject: [PATCH 023/229] Bug 1323100 - Remove NS_SetThreadName which is now unused. r=froydnj MozReview-Commit-ID: 7je5PhV1TsU --HG-- extra : rebase_source : 74a4339b3c7338e85caf9287b225d75a556b2938 --- xpcom/glue/nsThreadUtils.cpp | 50 ------------------------------------ xpcom/glue/nsThreadUtils.h | 18 ------------- 2 files changed, 68 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index 8f9cb092e15b..d2f5c88bcb6f 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -390,56 +390,6 @@ NS_ProcessNextEvent(nsIThread* aThread, bool aMayWait) return NS_SUCCEEDED(aThread->ProcessNextEvent(aMayWait, &val)) && val; } -#ifndef XPCOM_GLUE_AVOID_NSPR - -namespace { - -class nsNameThreadRunnable final : public nsIRunnable -{ - ~nsNameThreadRunnable() {} - -public: - explicit nsNameThreadRunnable(const nsACString& aName) : mName(aName) {} - - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSIRUNNABLE - -protected: - const nsCString mName; -}; - -NS_IMPL_ISUPPORTS(nsNameThreadRunnable, nsIRunnable) - -NS_IMETHODIMP -nsNameThreadRunnable::Run() -{ - PR_SetCurrentThreadName(mName.BeginReading()); - return NS_OK; -} - -} // namespace - -void -NS_SetThreadName(nsIThread* aThread, const nsACString& aName) -{ - if (!aThread) { - return; - } - - aThread->Dispatch(new nsNameThreadRunnable(aName), - nsIEventTarget::DISPATCH_NORMAL); -} - -#else // !XPCOM_GLUE_AVOID_NSPR - -void -NS_SetThreadName(nsIThread* aThread, const nsACString& aName) -{ - // No NSPR, no love. -} - -#endif - #ifdef MOZILLA_INTERNAL_API nsIThread* NS_GetCurrentThread() diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index a398e6c91c8f..82ed1294cdfc 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -32,24 +32,6 @@ // These methods are alternatives to the methods on nsIThreadManager, provided // for convenience. -/** - * Set name of the target thread. This operation is asynchronous. - */ -extern void NS_SetThreadName(nsIThread* aThread, const nsACString& aName); - -/** - * Static length version of the above function checking length of the - * name at compile time. - */ -template -inline void -NS_SetThreadName(nsIThread* aThread, const char (&aName)[LEN]) -{ - static_assert(LEN <= 16, - "Thread name must be no more than 16 characters"); - NS_SetThreadName(aThread, nsDependentCString(aName)); -} - /** * Create a new thread, and optionally provide an initial event for the thread. * From 85f0b506c0e23c72fd13626ba6b8d700cdb9d9f5 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 14 Dec 2016 19:50:11 -0500 Subject: [PATCH 024/229] Bug 1323100 - Register named threads with the profiler. r=froydnj MozReview-Commit-ID: FbE4BTcnfEh --HG-- extra : rebase_source : 4690ebcaf3b71008e9a4d5db31486683dcdb3f91 --- xpcom/threads/nsThread.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp index fd45e79c4ea7..119e0c788471 100644 --- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -38,6 +38,7 @@ #include "nsIIncrementalRunnable.h" #include "nsThreadSyncDispatch.h" #include "LeakRefPtr.h" +#include "GeckoProfiler.h" #ifdef MOZ_CRASHREPORTER #include "nsServiceManagerUtils.h" @@ -446,6 +447,8 @@ nsThread::ThreadFunc(void* aArg) { using mozilla::ipc::BackgroundChild; + char stackTop; + ThreadInitData* initData = static_cast(aArg); nsThread* self = initData->thread; // strong reference @@ -454,6 +457,8 @@ nsThread::ThreadFunc(void* aArg) if (initData->name.Length() > 0) { PR_SetCurrentThreadName(initData->name.BeginReading()); + + profiler_register_thread(initData->name.BeginReading(), &stackTop); } // Inform the ThreadManager @@ -519,6 +524,8 @@ nsThread::ThreadFunc(void* aArg) // Inform the threadmanager that this thread is going away nsThreadManager::get().UnregisterCurrentThread(*self); + profiler_unregister_thread(); + // Dispatch shutdown ACK NotNull context = WrapNotNull(self->mShutdownContext); From 855d8ef93cf8f01dd3210f408157dbffde23c230 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 17:57:07 +0100 Subject: [PATCH 025/229] Bug 1323100 - Stop double-registering the Socket Transport thread. r=froydnj MozReview-Commit-ID: 7YEC79PwUGg --HG-- extra : rebase_source : 17b5fa5358507d0cd87e07068434472967f317e1 --- netwerk/base/nsSocketTransportService2.cpp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/netwerk/base/nsSocketTransportService2.cpp b/netwerk/base/nsSocketTransportService2.cpp index 4705a6055d94..b47eee88e6c4 100644 --- a/netwerk/base/nsSocketTransportService2.cpp +++ b/netwerk/base/nsSocketTransportService2.cpp @@ -833,11 +833,6 @@ nsSocketTransportService::MarkTheLastElementOfPendingQueue() NS_IMETHODIMP nsSocketTransportService::Run() { -#ifdef MOZ_ENABLE_PROFILER_SPS - char stackBaseGuess; // Need to be the first variable of main loop function. - profiler_register_thread(PR_GetThreadName(PR_GetCurrentThread()), &stackBaseGuess); -#endif // MOZ_ENABLE_PROFILER_SPS - SOCKET_LOG(("STS thread init %d sockets\n", gMaxCount)); psm::InitializeSSLServerCertVerificationThreads(); @@ -1019,10 +1014,6 @@ nsSocketTransportService::Run() SOCKET_LOG(("STS thread exit\n")); -#ifdef MOZ_ENABLE_PROFILER_SPS - profiler_unregister_thread(); -#endif // MOZ_ENABLE_PROFILER_SPS - return NS_OK; } From ca0b39f067e7ed96d547c584550ac37e2b878b6c Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 23:06:45 +0100 Subject: [PATCH 026/229] Bug 1323100 - Stop double-registering the MediaStreamGraph thread with the profiler. r=froydnj MozReview-Commit-ID: 7WxNLZpBWL4 --HG-- extra : rebase_source : ce8fe0481c8e3c3d3efd3d1c15480490943ee202 --- dom/media/GraphDriver.cpp | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/dom/media/GraphDriver.cpp b/dom/media/GraphDriver.cpp index 33001cd332cc..ecb0acaecd49 100644 --- a/dom/media/GraphDriver.cpp +++ b/dom/media/GraphDriver.cpp @@ -39,19 +39,6 @@ namespace mozilla { StaticRefPtr AsyncCubebTask::sThreadPool; -struct AutoProfilerUnregisterThread -{ - // The empty ctor is used to silence a pre-4.8.0 GCC unused variable warning. - AutoProfilerUnregisterThread() - { - } - - ~AutoProfilerUnregisterThread() - { - profiler_unregister_thread(); - } -}; - GraphDriver::GraphDriver(MediaStreamGraphImpl* aGraphImpl) : mIterationStart(0), mIterationEnd(0), @@ -196,9 +183,7 @@ public: } NS_IMETHOD Run() override { - char aLocal; STREAM_LOG(LogLevel::Debug, ("Starting system thread")); - profiler_register_thread("MediaStreamGraph", &aLocal); LIFECYCLE_LOG("Starting a new system driver for graph %p\n", mDriver->mGraphImpl); @@ -316,8 +301,6 @@ SystemClockDriver::IsFallback() void ThreadedDriver::RunThread() { - AutoProfilerUnregisterThread autoUnregister; - bool stillProcessing = true; while (stillProcessing) { mIterationStart = IterationEnd(); From 2afac635fb64e272709009659d28c6cd8d3bfefb Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 23:06:56 +0100 Subject: [PATCH 027/229] Bug 1323100 - Stop double-registering the Media_Encoder thread with the profiler. r=froydnj MozReview-Commit-ID: 8TQMVhbw13s --HG-- extra : rebase_source : 6ebeba2b28f643a4b555e889b2f4f99a55e68485 --- dom/media/MediaRecorder.cpp | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/dom/media/MediaRecorder.cpp b/dom/media/MediaRecorder.cpp index 2deeb906d86b..4b4070257ccb 100644 --- a/dom/media/MediaRecorder.cpp +++ b/dom/media/MediaRecorder.cpp @@ -283,8 +283,6 @@ class MediaRecorder::Session: public nsIObserver, } else { // Flush out remaining encoded data. mSession->Extract(true); - if (mSession->mIsRegisterProfiler) - profiler_unregister_thread(); if (NS_FAILED(NS_DispatchToMainThread( new DestroyRunnable(mSession)))) { MOZ_ASSERT(false, "NS_DispatchToMainThread DestroyRunnable failed"); @@ -419,7 +417,6 @@ public: , mTimeSlice(aTimeSlice) , mStopIssued(false) , mIsStartEventFired(false) - , mIsRegisterProfiler(false) , mNeedSessionEndTask(true) , mSelectedVideoTrackID(TRACK_NONE) { @@ -607,12 +604,6 @@ private: MOZ_ASSERT(NS_GetCurrentThread() == mReadThread); LOG(LogLevel::Debug, ("Session.Extract %p", this)); - if (!mIsRegisterProfiler) { - char aLocal; - profiler_register_thread("Media_Encoder", &aLocal); - mIsRegisterProfiler = true; - } - PROFILER_LABEL("MediaRecorder", "Session Extract", js::ProfileEntry::Category::OTHER); @@ -922,8 +913,6 @@ private: bool mStopIssued; // Indicate the session had fire start event. Encoding thread only. bool mIsStartEventFired; - // The register flag for "Media_Encoder" thread to profiler - bool mIsRegisterProfiler; // False if the InitEncoder called successfully, ensure the // ExtractRunnable/DestroyRunnable will end the session. // Main thread only. From 281e42f926df504796c835f0b91a6d0ed903a710 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 23:07:10 +0100 Subject: [PATCH 028/229] Bug 1323100 - Stop double-registering the IPDL Background thread with the profiler. r=froydnj MozReview-Commit-ID: 2BlEhqrxdUz --HG-- extra : rebase_source : c74067a284337374188ff408406232a90171b828 --- ipc/glue/BackgroundImpl.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/ipc/glue/BackgroundImpl.cpp b/ipc/glue/BackgroundImpl.cpp index 2f8e073f8397..86b619f8f2f0 100644 --- a/ipc/glue/BackgroundImpl.cpp +++ b/ipc/glue/BackgroundImpl.cpp @@ -1344,8 +1344,6 @@ ParentImpl::RequestMessageLoopRunnable::Run() AssertIsInMainProcess(); MOZ_ASSERT(mTargetThread); - char stackBaseGuess; - if (NS_IsMainThread()) { MOZ_ASSERT(mMessageLoop); @@ -1375,8 +1373,6 @@ ParentImpl::RequestMessageLoopRunnable::Run() return NS_OK; } - profiler_register_thread("IPDL Background", &stackBaseGuess); - #ifdef DEBUG { bool correctThread; @@ -1414,8 +1410,6 @@ ParentImpl::ShutdownBackgroundThreadRunnable::Run() // sBackgroundPRThread and we should not modify it here. sBackgroundPRThread.compareExchange(PR_GetCurrentThread(), nullptr); - profiler_unregister_thread(); - return NS_OK; } From e9c7fbcf498214fbe318c329cbc7fd08640b0f93 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 23:07:26 +0100 Subject: [PATCH 029/229] Bug 1323100 - Stop double-registering the LazyIdleThread with the profiler. r=froydnj MozReview-Commit-ID: 2vdcgCcdOYJ --HG-- extra : rebase_source : 2a42caebc2a80b4d634eb741bbc196a718379e22 --- xpcom/threads/LazyIdleThread.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/xpcom/threads/LazyIdleThread.cpp b/xpcom/threads/LazyIdleThread.cpp index b6218e959292..be3acfa61fc5 100644 --- a/xpcom/threads/LazyIdleThread.cpp +++ b/xpcom/threads/LazyIdleThread.cpp @@ -180,11 +180,6 @@ LazyIdleThread::EnsureThread() void LazyIdleThread::InitThread() { - char aLocal; - profiler_register_thread(mName.get(), &aLocal); - - PR_SetCurrentThreadName(mName.get()); - // Happens on mThread but mThread may not be set yet... nsCOMPtr thread(do_QueryInterface(NS_GetCurrentThread())); @@ -211,8 +206,6 @@ LazyIdleThread::CleanupThread() MOZ_ASSERT(!mThreadIsShuttingDown, "Shouldn't be true ever!"); mThreadIsShuttingDown = true; } - - profiler_unregister_thread(); } void From 65630c6c3270064e955847e797aa207b31fb6e23 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Fri, 30 Dec 2016 20:27:59 +0100 Subject: [PATCH 030/229] Bug 1323100 - Register most of the remaining threadfunc threads with the profiler. r=froydnj As far as I can tell, this covers all the remaining threads which we start using PR_CreateThread, except the ones that are created inside NSPR or NSS. This adds a AutoProfilerRegister stack class for easy registering and unregistering. There are a few places where we still call profiler_register_thread() and profiler_unregister_thread() manually, either because registration happens conditionally, or because there is a variable that gets put on the stack before the AutoProfilerRegister (e.g. a dynamically generated thread name). AutoProfilerRegister needs to be the first object on the stack because it uses its own `this` pointer as the stack top address. MozReview-Commit-ID: 3vwhS55Yzt --HG-- extra : rebase_source : 9deaace277db2f63c520325be27f6ed97aa65ac9 --- .../webaudio/blink/HRTFDatabaseLoader.cpp | 2 ++ dom/storage/DOMStorageDBThread.cpp | 2 ++ js/xpconnect/src/XPCJSContext.cpp | 1 + netwerk/cache2/CacheIOThread.cpp | 2 ++ netwerk/dns/nsHostResolver.cpp | 6 ++++++ security/manager/ssl/nsKeygenThread.cpp | 2 ++ .../manager/ssl/nsProtectedAuthThread.cpp | 2 ++ security/manager/ssl/nsSmartCardMonitor.cpp | 2 ++ startupcache/StartupCache.cpp | 2 ++ .../components/terminator/nsTerminator.cpp | 2 ++ toolkit/xre/EventTracer.cpp | 1 + tools/profiler/public/GeckoProfiler.h | 8 ++++++++ tools/profiler/public/GeckoProfilerImpl.h | 20 +++++++++++++++++++ xpcom/build/MainThreadIOLogger.cpp | 1 + xpcom/threads/BackgroundHangMonitor.cpp | 2 ++ xpcom/threads/HangMonitor.cpp | 2 ++ xpcom/threads/nsProcessCommon.cpp | 8 ++++++++ 17 files changed, 65 insertions(+) diff --git a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp index 090e1b2172af..41be2c2daa5d 100644 --- a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp +++ b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp @@ -28,6 +28,7 @@ #include "HRTFDatabaseLoader.h" #include "HRTFDatabase.h" +#include "GeckoProfiler.h" using namespace mozilla; @@ -151,6 +152,7 @@ void HRTFDatabaseLoader::MainThreadRelease() // Asynchronously load the database in this thread. static void databaseLoaderEntry(void* threadData) { + AutoProfilerRegister registerThread("HRTFDatabaseLdr"); PR_SetCurrentThreadName("HRTFDatabaseLdr"); HRTFDatabaseLoader* loader = reinterpret_cast(threadData); diff --git a/dom/storage/DOMStorageDBThread.cpp b/dom/storage/DOMStorageDBThread.cpp index d479fbb783f4..7f9039484d82 100644 --- a/dom/storage/DOMStorageDBThread.cpp +++ b/dom/storage/DOMStorageDBThread.cpp @@ -27,6 +27,7 @@ #include "mozilla/IOInterposer.h" #include "mozilla/Services.h" #include "mozilla/Tokenizer.h" +#include "GeckoProfiler.h" // How long we collect write oprerations // before they are flushed to the database @@ -337,6 +338,7 @@ DOMStorageDBThread::SetDefaultPriority() void DOMStorageDBThread::ThreadFunc(void* aArg) { + AutoProfilerRegister registerThread("localStorage DB"); PR_SetCurrentThreadName("localStorage DB"); mozilla::IOInterposer::RegisterCurrentThread(); diff --git a/js/xpconnect/src/XPCJSContext.cpp b/js/xpconnect/src/XPCJSContext.cpp index 5b4d184ea2f8..0393ae9ef498 100644 --- a/js/xpconnect/src/XPCJSContext.cpp +++ b/js/xpconnect/src/XPCJSContext.cpp @@ -1166,6 +1166,7 @@ AutoLockWatchdog::~AutoLockWatchdog() static void WatchdogMain(void* arg) { + mozilla::AutoProfilerRegister registerThread("JS Watchdog"); PR_SetCurrentThreadName("JS Watchdog"); Watchdog* self = static_cast(arg); diff --git a/netwerk/cache2/CacheIOThread.cpp b/netwerk/cache2/CacheIOThread.cpp index 66742679c9ac..be5092a6d09c 100644 --- a/netwerk/cache2/CacheIOThread.cpp +++ b/netwerk/cache2/CacheIOThread.cpp @@ -10,6 +10,7 @@ #include "nsPrintfCString.h" #include "nsThreadUtils.h" #include "mozilla/IOInterposer.h" +#include "GeckoProfiler.h" #ifdef XP_WIN #include @@ -437,6 +438,7 @@ already_AddRefed CacheIOThread::Target() // static void CacheIOThread::ThreadFunc(void* aClosure) { + AutoProfilerRegister registerThread("Cache2 I/O"); PR_SetCurrentThreadName("Cache2 I/O"); mozilla::IOInterposer::RegisterCurrentThread(); CacheIOThread* thread = static_cast(aClosure); diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index 78cdfebf0909..8924ed7e4d10 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -29,6 +29,7 @@ #include "nsURLHelper.h" #include "nsThreadUtils.h" #include "GetAddrInfo.h" +#include "GeckoProfiler.h" #include "mozilla/HashFunctions.h" #include "mozilla/TimeStamp.h" @@ -1435,12 +1436,15 @@ nsHostResolver::SizeOfIncludingThis(MallocSizeOf mallocSizeOf) const void nsHostResolver::ThreadFunc(void *arg) { + char stackTop; + LOG(("DNS lookup thread - starting execution.\n")); static nsThreadPoolNaming naming; nsCString name = naming.GetNextThreadName("DNS Resolver"); PR_SetCurrentThreadName(name.BeginReading()); + profiler_register_thread(name.BeginReading(), &stackTop); #if defined(RES_RETRY_ON_FAILURE) nsResState rs; @@ -1511,6 +1515,8 @@ nsHostResolver::ThreadFunc(void *arg) resolver->mThreadCount--; NS_RELEASE(resolver); LOG(("DNS lookup thread - queue empty, thread finished.\n")); + + profiler_unregister_thread(); } nsresult diff --git a/security/manager/ssl/nsKeygenThread.cpp b/security/manager/ssl/nsKeygenThread.cpp index b295c4f36895..4ff0304e229a 100644 --- a/security/manager/ssl/nsKeygenThread.cpp +++ b/security/manager/ssl/nsKeygenThread.cpp @@ -12,6 +12,7 @@ #include "nsNSSShutDown.h" #include "PSMRunnable.h" #include "mozilla/DebugOnly.h" +#include "GeckoProfiler.h" using namespace mozilla; using namespace mozilla::psm; @@ -114,6 +115,7 @@ nsresult nsKeygenThread::ConsumeResult( static void nsKeygenThreadRunner(void *arg) { + AutoProfilerRegister registerThread("Keygen"); PR_SetCurrentThreadName("Keygen"); nsKeygenThread *self = static_cast(arg); self->Run(); diff --git a/security/manager/ssl/nsProtectedAuthThread.cpp b/security/manager/ssl/nsProtectedAuthThread.cpp index ea511b24a63d..bb930188b874 100644 --- a/security/manager/ssl/nsProtectedAuthThread.cpp +++ b/security/manager/ssl/nsProtectedAuthThread.cpp @@ -11,6 +11,7 @@ #include "nsReadableUtils.h" #include "nsPKCS11Slot.h" #include "nsProtectedAuthThread.h" +#include "GeckoProfiler.h" using namespace mozilla; using namespace mozilla::psm; @@ -19,6 +20,7 @@ NS_IMPL_ISUPPORTS(nsProtectedAuthThread, nsIProtectedAuthThread) static void nsProtectedAuthThreadRunner(void *arg) { + AutoProfilerRegister registerThread("Protected Auth"); PR_SetCurrentThreadName("Protected Auth"); nsProtectedAuthThread *self = static_cast(arg); diff --git a/security/manager/ssl/nsSmartCardMonitor.cpp b/security/manager/ssl/nsSmartCardMonitor.cpp index 3423d4f5f5f1..a5cb8610aef2 100644 --- a/security/manager/ssl/nsSmartCardMonitor.cpp +++ b/security/manager/ssl/nsSmartCardMonitor.cpp @@ -10,6 +10,7 @@ #include "nsIObserverService.h" #include "nsServiceManagerUtils.h" #include "nsThreadUtils.h" +#include "GeckoProfiler.h" #include "nspr.h" #include "pk11func.h" @@ -390,6 +391,7 @@ const SECMODModule* SmartCardMonitoringThread::GetModule() // C-like calling sequence to glue into PR_CreateThread. void SmartCardMonitoringThread::LaunchExecute(void* arg) { + AutoProfilerRegister registerThread("SmartCard"); PR_SetCurrentThreadName("SmartCard"); ((SmartCardMonitoringThread*)arg)->Execute(); diff --git a/startupcache/StartupCache.cpp b/startupcache/StartupCache.cpp index 6d1dd7a3a3ff..f698187170a5 100644 --- a/startupcache/StartupCache.cpp +++ b/startupcache/StartupCache.cpp @@ -36,6 +36,7 @@ #include "nsThreadUtils.h" #include "nsXULAppAPI.h" #include "nsIProtocolHandler.h" +#include "GeckoProfiler.h" #ifdef IS_BIG_ENDIAN #define SC_ENDIAN "big" @@ -503,6 +504,7 @@ StartupCache::WaitOnWriteThread() void StartupCache::ThreadedWrite(void *aClosure) { + AutoProfilerRegister registerThread("StartupCache"); PR_SetCurrentThreadName("StartupCache"); mozilla::IOInterposer::RegisterCurrentThread(); /* diff --git a/toolkit/components/terminator/nsTerminator.cpp b/toolkit/components/terminator/nsTerminator.cpp index e3d958a8807f..4cc156d8f2a3 100644 --- a/toolkit/components/terminator/nsTerminator.cpp +++ b/toolkit/components/terminator/nsTerminator.cpp @@ -32,6 +32,7 @@ #if defined(MOZ_CRASHREPORTER) #include "nsExceptionHandler.h" #endif +#include "GeckoProfiler.h" #if defined(XP_WIN) #include @@ -214,6 +215,7 @@ PRMonitor* gWriteReady = nullptr; void RunWriter(void* arg) { + AutoProfilerRegister registerThread("Shutdown Statistics Writer"); PR_SetCurrentThreadName("Shutdown Statistics Writer"); MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(arg); diff --git a/toolkit/xre/EventTracer.cpp b/toolkit/xre/EventTracer.cpp index cb0d88524db4..622334f43eda 100644 --- a/toolkit/xre/EventTracer.cpp +++ b/toolkit/xre/EventTracer.cpp @@ -122,6 +122,7 @@ class EventLoopLagDispatcher : public Runnable */ void TracerThread(void *arg) { + AutoProfilerRegister registerThread("Event Tracer"); PR_SetCurrentThreadName("Event Tracer"); TracerStartClosure* threadArgs = static_cast(arg); diff --git a/tools/profiler/public/GeckoProfiler.h b/tools/profiler/public/GeckoProfiler.h index bef017d11558..81452dd6563c 100644 --- a/tools/profiler/public/GeckoProfiler.h +++ b/tools/profiler/public/GeckoProfiler.h @@ -248,6 +248,14 @@ static inline bool profiler_in_privacy_mode() { return false; } static inline void profiler_log(const char *str) {} static inline void profiler_log(const char *fmt, va_list args) {} +class AutoProfilerRegister final MOZ_STACK_CLASS +{ + AutoProfilerRegister(const char* aName) {} +private: + AutoProfilerRegister(const AutoProfilerRegister&) = delete; + AutoProfilerRegister& operator=(const AutoProfilerRegister&) = delete; +}; + #else #include "GeckoProfilerImpl.h" diff --git a/tools/profiler/public/GeckoProfilerImpl.h b/tools/profiler/public/GeckoProfilerImpl.h index a32096b94315..2522400fff62 100644 --- a/tools/profiler/public/GeckoProfilerImpl.h +++ b/tools/profiler/public/GeckoProfilerImpl.h @@ -461,6 +461,26 @@ private: void* mHandle; }; +/** + * Convenience class to register and unregister a thread with the profiler. + * Needs to be the first object on the stack of the thread. + */ +class MOZ_STACK_CLASS AutoProfilerRegister final +{ +public: + explicit AutoProfilerRegister(const char* aName) + { + profiler_register_thread(aName, this); + } + ~AutoProfilerRegister() + { + profiler_unregister_thread(); + } +private: + AutoProfilerRegister(const AutoProfilerRegister&) = delete; + AutoProfilerRegister& operator=(const AutoProfilerRegister&) = delete; +}; + } // namespace mozilla inline PseudoStack* mozilla_get_pseudo_stack(void) diff --git a/xpcom/build/MainThreadIOLogger.cpp b/xpcom/build/MainThreadIOLogger.cpp index 0ca942cb9f76..95e469899fbd 100644 --- a/xpcom/build/MainThreadIOLogger.cpp +++ b/xpcom/build/MainThreadIOLogger.cpp @@ -114,6 +114,7 @@ MainThreadIOLoggerImpl::Init() /* static */ void MainThreadIOLoggerImpl::sIOThreadFunc(void* aArg) { + AutoProfilerRegister registerThread("MainThreadIOLogger"); PR_SetCurrentThreadName("MainThreadIOLogger"); MainThreadIOLoggerImpl* obj = static_cast(aArg); obj->IOThreadFunc(); diff --git a/xpcom/threads/BackgroundHangMonitor.cpp b/xpcom/threads/BackgroundHangMonitor.cpp index ac65d9f37162..cc16973752fa 100644 --- a/xpcom/threads/BackgroundHangMonitor.cpp +++ b/xpcom/threads/BackgroundHangMonitor.cpp @@ -22,6 +22,7 @@ #include "nsIObserver.h" #include "mozilla/Services.h" #include "nsXULAppAPI.h" +#include "GeckoProfiler.h" #include @@ -54,6 +55,7 @@ private: // Background hang monitor thread function static void MonitorThread(void* aData) { + AutoProfilerRegister registerThread("BgHangMonitor"); PR_SetCurrentThreadName("BgHangManager"); /* We do not hold a reference to BackgroundHangManager here diff --git a/xpcom/threads/HangMonitor.cpp b/xpcom/threads/HangMonitor.cpp index cde8052f33c4..ab402eb68f58 100644 --- a/xpcom/threads/HangMonitor.cpp +++ b/xpcom/threads/HangMonitor.cpp @@ -21,6 +21,7 @@ #endif #include "nsThreadUtils.h" #include "nsXULAppAPI.h" +#include "GeckoProfiler.h" #ifdef MOZ_CRASHREPORTER #include "nsExceptionHandler.h" @@ -209,6 +210,7 @@ GetChromeHangReport(Telemetry::ProcessedStack& aStack, void ThreadMain(void*) { + AutoProfilerRegister registerThread("Hang Monitor"); PR_SetCurrentThreadName("Hang Monitor"); MonitorAutoLock lock(*gMonitor); diff --git a/xpcom/threads/nsProcessCommon.cpp b/xpcom/threads/nsProcessCommon.cpp index 709865a09d8b..37071b58c95f 100644 --- a/xpcom/threads/nsProcessCommon.cpp +++ b/xpcom/threads/nsProcessCommon.cpp @@ -25,6 +25,7 @@ #include "nsIObserverService.h" #include "nsXULAppAPI.h" #include "mozilla/Services.h" +#include "GeckoProfiler.h" #include @@ -235,10 +236,13 @@ assembleCmdLine(char* const* aArgv, wchar_t** aWideCmdLine, UINT aCodePage) void nsProcess::Monitor(void* aArg) { + char stackBaseGuess; + RefPtr process = dont_AddRef(static_cast(aArg)); if (!process->mBlocking) { PR_SetCurrentThreadName("RunProcess"); + profiler_register_thread("RunProcess", &stackBaseGuess); } #if defined(PROCESSMODEL_WINAPI) @@ -304,6 +308,10 @@ nsProcess::Monitor(void* aArg) } else { NS_DispatchToMainThread(NewRunnableMethod(process, &nsProcess::ProcessComplete)); } + + if (!process->mBlocking) { + profiler_unregister_thread(); + } } void From b40b591cec450128f43d8b6654e4a7961f606d03 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 22 Dec 2016 00:48:55 +0100 Subject: [PATCH 031/229] Bug 1323100 - Use AutoProfilerRegister to register chromium threads with the profiler. r=froydnj MozReview-Commit-ID: 12LS5hqCA2c --HG-- extra : rebase_source : d265e77f82d6805502baa6a786860aa6911b7553 --- ipc/chromium/src/base/thread.cc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ipc/chromium/src/base/thread.cc b/ipc/chromium/src/base/thread.cc index feec3aedf797..05463aecac18 100644 --- a/ipc/chromium/src/base/thread.cc +++ b/ipc/chromium/src/base/thread.cc @@ -153,8 +153,7 @@ void Thread::StopSoon() { } void Thread::ThreadMain() { - char aLocal; - profiler_register_thread(name_.c_str(), &aLocal); + mozilla::AutoProfilerRegister registerThread(name_.c_str()); mozilla::IOInterposer::RegisterCurrentThread(); // The message loop for this thread. @@ -186,7 +185,6 @@ void Thread::ThreadMain() { DCHECK(GetThreadWasQuitProperly()); mozilla::IOInterposer::UnregisterCurrentThread(); - profiler_unregister_thread(); #ifdef MOZ_TASK_TRACER mozilla::tasktracer::FreeTraceInfo(); From b6f1645a45cfcfec24c3ce7fcd0d27a8468f3923 Mon Sep 17 00:00:00 2001 From: Daniel Holbert Date: Fri, 30 Dec 2016 12:03:08 -0800 Subject: [PATCH 032/229] Bug 1326457: Remove redundant check for eCSSKeyword_UNKNOWN at callsites to nsCSSProps::FindKeyword(). r=xidorn nsCSSProps::FindKeyword() has always failed when passed eCSSKeyword_UNKNOWN, but it didn't used to have a fast-path for this sentinel value -- it used to walk the whole array before failing. So it used to make sense to have a dedicated check for it at the callsites, to avoid an unnecessary array traversal. But now, there's an early-return in FindKeyword() (or actually in its helper, FindIndexOfKeyword()) which catches eCSSKeyword_UNKNOWN right away, before it walks the array. So there's no benefit to having a dedicated check at the callsites anymore. MozReview-Commit-ID: FOX48YZMomd --HG-- extra : rebase_source : 2309d5f3f15e3cad2e4ae5ebe14af1c6beb43ebc --- dom/base/nsGlobalWindow.cpp | 3 +- layout/style/nsCSSParser.cpp | 53 +++++++++++++++--------------------- layout/style/nsStyleUtil.cpp | 3 +- 3 files changed, 24 insertions(+), 35 deletions(-) diff --git a/dom/base/nsGlobalWindow.cpp b/dom/base/nsGlobalWindow.cpp index de38308fba18..faa8935c2f97 100644 --- a/dom/base/nsGlobalWindow.cpp +++ b/dom/base/nsGlobalWindow.cpp @@ -13398,8 +13398,7 @@ nsGlobalWindow::SetCursorOuter(const nsAString& aCursor, ErrorResult& aError) cursor = NS_STYLE_CURSOR_AUTO; else { nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(aCursor); - if (eCSSKeyword_UNKNOWN == keyword || - !nsCSSProps::FindKeyword(keyword, nsCSSProps::kCursorKTable, cursor)) { + if (!nsCSSProps::FindKeyword(keyword, nsCSSProps::kCursorKTable, cursor)) { return; } } diff --git a/layout/style/nsCSSParser.cpp b/layout/style/nsCSSParser.cpp index 8167dae58717..8ddfbc9fa062 100644 --- a/layout/style/nsCSSParser.cpp +++ b/layout/style/nsCSSParser.cpp @@ -4226,8 +4226,7 @@ CSSParserImpl::ParseFontFeatureValueSet(nsCSSFontFeatureValuesRule // which font-specific variant of font-variant-alternates int32_t whichVariant; nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(mToken.mIdent); - if (keyword == eCSSKeyword_UNKNOWN || - !nsCSSProps::FindKeyword(keyword, + if (!nsCSSProps::FindKeyword(keyword, nsCSSProps::kFontVariantAlternatesFuncsKTable, whichVariant)) { @@ -6733,12 +6732,10 @@ CSSParserImpl::ParseColor(nsCSSValue& aValue) } else { nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(tk->mIdent); - if (eCSSKeyword_UNKNOWN < keyword) { // known keyword - int32_t value; - if (nsCSSProps::FindKeyword(keyword, nsCSSProps::kColorKTable, value)) { - aValue.SetIntValue(value, eCSSUnit_EnumColor); - return CSSParseResult::Ok; - } + int32_t value; + if (nsCSSProps::FindKeyword(keyword, nsCSSProps::kColorKTable, value)) { + aValue.SetIntValue(value, eCSSUnit_EnumColor); + return CSSParseResult::Ok; } } break; @@ -7556,12 +7553,10 @@ CSSParserImpl::ParseEnum(nsCSSValue& aValue, return false; } nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(*ident); - if (eCSSKeyword_UNKNOWN < keyword) { - int32_t value; - if (nsCSSProps::FindKeyword(keyword, aKeywordTable, value)) { - aValue.SetIntValue(value, eCSSUnit_Enumerated); - return true; - } + int32_t value; + if (nsCSSProps::FindKeyword(keyword, aKeywordTable, value)) { + aValue.SetIntValue(value, eCSSUnit_Enumerated); + return true; } // Put the unknown identifier back and return @@ -7591,16 +7586,14 @@ CSSParserImpl::ParseAlignEnum(nsCSSValue& aValue, } keyword = nsCSSKeywords::LookupKeyword(*ident); } - if (eCSSKeyword_UNKNOWN < keyword) { - int32_t value; - if (nsCSSProps::FindKeyword(keyword, aKeywordTable, value)) { - if (baselinePrefix == eCSSKeyword_last && - keyword == eCSSKeyword_baseline) { - value = NS_STYLE_ALIGN_LAST_BASELINE; - } - aValue.SetIntValue(value, eCSSUnit_Enumerated); - return true; + int32_t value; + if (nsCSSProps::FindKeyword(keyword, aKeywordTable, value)) { + if (baselinePrefix == eCSSKeyword_last && + keyword == eCSSKeyword_baseline) { + value = NS_STYLE_ALIGN_LAST_BASELINE; } + aValue.SetIntValue(value, eCSSUnit_Enumerated); + return true; } // Put the unknown identifier back and return @@ -10659,8 +10652,7 @@ CSSParserImpl::IsLegacyGradientLine(const nsCSSTokenType& aType, // This is only a gradient line if it's a box position keyword. nsCSSKeyword kw = nsCSSKeywords::LookupKeyword(aId); int32_t junk; - if (kw != eCSSKeyword_UNKNOWN && - nsCSSProps::FindKeyword(kw, nsCSSProps::kImageLayerPositionKTable, + if (nsCSSProps::FindKeyword(kw, nsCSSProps::kImageLayerPositionKTable, junk)) { haveGradientLine = true; } @@ -14469,12 +14461,11 @@ CSSParserImpl::ParseSingleAlternate(int32_t& aWhichFeature, // function ==> e.g. swash(flowing) styleset(alt-g, alt-m) nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(mToken.mIdent); - if (!(eCSSKeyword_UNKNOWN < keyword && - nsCSSProps::FindKeyword(keyword, - (isIdent ? - nsCSSProps::kFontVariantAlternatesKTable : - nsCSSProps::kFontVariantAlternatesFuncsKTable), - aWhichFeature))) + if (!nsCSSProps::FindKeyword(keyword, + (isIdent ? + nsCSSProps::kFontVariantAlternatesKTable : + nsCSSProps::kFontVariantAlternatesFuncsKTable), + aWhichFeature)) { // failed, pop token UngetToken(); diff --git a/layout/style/nsStyleUtil.cpp b/layout/style/nsStyleUtil.cpp index 37e423199ff8..60663b4a350f 100644 --- a/layout/style/nsStyleUtil.cpp +++ b/layout/style/nsStyleUtil.cpp @@ -516,8 +516,7 @@ nsStyleUtil::ComputeFunctionalAlternates(const nsCSSValueList* aList, NS_ASSERTION(key != eCSSKeyword_UNKNOWN, "unknown alternate property value"); int32_t alternate; - if (key == eCSSKeyword_UNKNOWN || - !nsCSSProps::FindKeyword(key, + if (!nsCSSProps::FindKeyword(key, nsCSSProps::kFontVariantAlternatesFuncsKTable, alternate)) { NS_NOTREACHED("keyword not a font-variant-alternates value"); From 382cf219da47697408c6c17972bf587acb8257e1 Mon Sep 17 00:00:00 2001 From: Xidorn Quan Date: Fri, 30 Dec 2016 14:17:55 +1100 Subject: [PATCH 033/229] Bug 894245 part 1 - Align windows widget behavior with other widgets to return failure when the specified color is unknown. r=jimm MozReview-Commit-ID: HZ0Fir06QU6 --HG-- extra : rebase_source : 6b6c7fb1a578d2a129e399c534a8b651f32075bd --- widget/windows/nsLookAndFeel.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/widget/windows/nsLookAndFeel.cpp b/widget/windows/nsLookAndFeel.cpp index 7c427ac9feea..3957d8d6e2ce 100644 --- a/widget/windows/nsLookAndFeel.cpp +++ b/widget/windows/nsLookAndFeel.cpp @@ -302,7 +302,9 @@ nsLookAndFeel::NativeGetColor(ColorID aID, nscolor &aColor) idx = COLOR_HOTLIGHT; break; default: + NS_WARNING("Unknown color for nsLookAndFeel"); idx = COLOR_WINDOW; + res = NS_ERROR_FAILURE; break; } From b93e776ac91e67d269c8ad94ad45918ebc65c3ea Mon Sep 17 00:00:00 2001 From: Xidorn Quan Date: Fri, 30 Dec 2016 14:52:10 +1100 Subject: [PATCH 034/229] Bug 894245 part 2 - Reject unknown enum color in CSS parser. r=dholbert MozReview-Commit-ID: 6jfNESnFde5 --HG-- extra : rebase_source : dbe0b7f1eb45a59ef4df67ba5f1d75da1892cb17 --- layout/style/crashtests/894245-1.html | 5 +++ layout/style/crashtests/crashtests.list | 1 + layout/style/nsCSSParser.cpp | 41 ++++++++++++++++++++----- layout/style/nsRuleNode.cpp | 9 +++--- 4 files changed, 44 insertions(+), 12 deletions(-) create mode 100644 layout/style/crashtests/894245-1.html diff --git a/layout/style/crashtests/894245-1.html b/layout/style/crashtests/894245-1.html new file mode 100644 index 000000000000..f2ec419afe46 --- /dev/null +++ b/layout/style/crashtests/894245-1.html @@ -0,0 +1,5 @@ + +
+
+
+
diff --git a/layout/style/crashtests/crashtests.list b/layout/style/crashtests/crashtests.list index c8d0f77da047..9d7c3c9050c8 100644 --- a/layout/style/crashtests/crashtests.list +++ b/layout/style/crashtests/crashtests.list @@ -103,6 +103,7 @@ load 862113.html asserts-if(stylo,5) load 867487.html # bug 1324634 load 873222.html asserts-if(stylo,2) load 880862.html # bug 1324701 +load 894245-1.html load 915440.html load 927734-1.html load 930270-1.html diff --git a/layout/style/nsCSSParser.cpp b/layout/style/nsCSSParser.cpp index 8ddfbc9fa062..18d9db57e46f 100644 --- a/layout/style/nsCSSParser.cpp +++ b/layout/style/nsCSSParser.cpp @@ -8,6 +8,7 @@ #include "mozilla/ArrayUtils.h" #include "mozilla/DebugOnly.h" +#include "mozilla/Maybe.h" #include "mozilla/Move.h" #include "mozilla/MathAlgorithms.h" #include "mozilla/TypedEnumBits.h" @@ -51,6 +52,7 @@ #include "CSSCalc.h" #include "nsMediaFeatures.h" #include "nsLayoutUtils.h" +#include "mozilla/LookAndFeel.h" #include "mozilla/Preferences.h" #include "nsRuleData.h" #include "mozilla/CSSVariableValues.h" @@ -6688,6 +6690,31 @@ CSSParserImpl::ParseDeclarationBlock(uint32_t aFlags, nsCSSContextType aContext) return declaration.forget(); } +static Maybe +GetEnumColorValue(nsCSSKeyword aKeyword, bool aIsChrome) +{ + int32_t value; + if (!nsCSSProps::FindKeyword(aKeyword, nsCSSProps::kColorKTable, value)) { + // Unknown color keyword. + return Nothing(); + } + if (value < 0) { + // Known special color keyword handled by style system, + // e.g. NS_COLOR_CURRENTCOLOR. See nsStyleConsts.h. + return Some(value); + } + nscolor color; + auto colorID = static_cast(value); + if (NS_FAILED(LookAndFeel::GetColor(colorID, !aIsChrome, &color))) { + // Known LookAndFeel::ColorID, but this platform's LookAndFeel impl + // doesn't map it to a color. (This might be a platform-specific + // ColorID, which only makes sense on another platform.) + return Nothing(); + } + // Known color provided by LookAndFeel. + return Some(value); +} + CSSParseResult CSSParserImpl::ParseColor(nsCSSValue& aValue) { @@ -6725,20 +6752,18 @@ CSSParserImpl::ParseColor(nsCSSValue& aValue) } break; - case eCSSToken_Ident: + case eCSSToken_Ident: { if (NS_ColorNameToRGB(tk->mIdent, &rgba)) { aValue.SetStringValue(tk->mIdent, eCSSUnit_Ident); return CSSParseResult::Ok; } - else { - nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(tk->mIdent); - int32_t value; - if (nsCSSProps::FindKeyword(keyword, nsCSSProps::kColorKTable, value)) { - aValue.SetIntValue(value, eCSSUnit_EnumColor); - return CSSParseResult::Ok; - } + nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(tk->mIdent); + if (Maybe value = GetEnumColorValue(keyword, mIsChrome)) { + aValue.SetIntValue(value.value(), eCSSUnit_EnumColor); + return CSSParseResult::Ok; } break; + } case eCSSToken_Function: { bool isRGB; bool isHSL; diff --git a/layout/style/nsRuleNode.cpp b/layout/style/nsRuleNode.cpp index ea27fcee9aab..29added60f39 100644 --- a/layout/style/nsRuleNode.cpp +++ b/layout/style/nsRuleNode.cpp @@ -1044,10 +1044,11 @@ static bool SetColor(const nsCSSValue& aValue, const nscolor aParentColor, LookAndFeel::ColorID colorID = (LookAndFeel::ColorID) intValue; bool useStandinsForNativeColors = aPresContext && !aPresContext->IsChrome(); - if (NS_SUCCEEDED(LookAndFeel::GetColor(colorID, - useStandinsForNativeColors, &aResult))) { - result = true; - } + DebugOnly rv = + LookAndFeel::GetColor(colorID, useStandinsForNativeColors, &aResult); + MOZ_ASSERT(NS_SUCCEEDED(rv), + "Unknown enum colors should have been rejected by parser"); + result = true; } else { aResult = NS_RGB(0, 0, 0); From 65b11f530208d49422c6157b537ccf8f676f1e25 Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Fri, 30 Dec 2016 16:09:03 -0800 Subject: [PATCH 035/229] Backed out 27 changesets (bug 1323100) for leaks in mochitest-e10s-2 a=backout Backed out changeset 069375097856 (bug 1323100) Backed out changeset 3e64cdf12bb6 (bug 1323100) Backed out changeset ba3a6bce2ba5 (bug 1323100) Backed out changeset 4fcf1517da8d (bug 1323100) Backed out changeset 5daf48da151e (bug 1323100) Backed out changeset 4e441df8f70a (bug 1323100) Backed out changeset 8ba2c7c2d262 (bug 1323100) Backed out changeset 7b54195f4383 (bug 1323100) Backed out changeset 8c1328db2d0c (bug 1323100) Backed out changeset cb8d544864b8 (bug 1323100) Backed out changeset 00453dfb7172 (bug 1323100) Backed out changeset 3a5216789011 (bug 1323100) Backed out changeset 3a7ce80e8657 (bug 1323100) Backed out changeset 4baecf3669b0 (bug 1323100) Backed out changeset c5ca13e76e13 (bug 1323100) Backed out changeset 40249b284066 (bug 1323100) Backed out changeset 1fb590677ace (bug 1323100) Backed out changeset 699f7f888ea3 (bug 1323100) Backed out changeset a1c171f8f925 (bug 1323100) Backed out changeset c04743218bc5 (bug 1323100) Backed out changeset 831f4de80f62 (bug 1323100) Backed out changeset 55b1ef1a16cf (bug 1323100) Backed out changeset 6675e4fd50f0 (bug 1323100) Backed out changeset e26f9d68b74c (bug 1323100) Backed out changeset 061f8e2d0000 (bug 1323100) Backed out changeset 6695c396ef15 (bug 1323100) Backed out changeset 5dbb824fd978 (bug 1323100) --- dom/gamepad/cocoa/CocoaGamepad.cpp | 5 +- dom/gamepad/windows/WindowsGamepad.cpp | 2 +- dom/indexedDB/ActorsParent.cpp | 30 +++++-- dom/media/FileBlockCache.cpp | 7 +- dom/media/GraphDriver.cpp | 17 ++++ dom/media/MediaRecorder.cpp | 11 +++ .../android/AndroidMediaResourceServer.cpp | 2 +- dom/media/gtest/TestMP4Reader.cpp | 2 +- .../webaudio/blink/HRTFDatabaseLoader.cpp | 2 - dom/plugins/base/android/ANPAudio.cpp | 4 +- dom/storage/DOMStorageDBThread.cpp | 2 - .../gonk/GonkGPSGeolocationProvider.cpp | 2 +- gfx/layers/LayerScope.cpp | 2 +- hal/gonk/GonkHal.cpp | 2 +- image/DecodePool.cpp | 27 ++++-- image/test/gtest/TestDecodeToSurface.cpp | 3 +- ipc/chromium/src/base/thread.cc | 4 +- ipc/glue/BackgroundImpl.cpp | 6 ++ js/xpconnect/src/XPCJSContext.cpp | 1 - media/mtransport/nr_socket_prsock.cpp | 3 +- netwerk/base/BackgroundFileSaver.cpp | 2 +- netwerk/base/nsPACMan.cpp | 18 +++- netwerk/base/nsPACMan.h | 1 + netwerk/base/nsSocketTransportService2.cpp | 9 ++ netwerk/cache2/CacheIOThread.cpp | 2 - netwerk/dns/nsHostResolver.cpp | 10 +-- netwerk/sctp/datachannel/DataChannel.cpp | 5 +- netwerk/system/win32/nsNotifyAddrListener.cpp | 4 +- netwerk/test/TestFileInput2.cpp | 61 +++++++------ netwerk/wifi/nsWifiMonitor.cpp | 4 +- security/manager/ssl/CryptoTask.cpp | 6 +- security/manager/ssl/nsKeygenThread.cpp | 2 - .../manager/ssl/nsProtectedAuthThread.cpp | 2 - security/manager/ssl/nsSmartCardMonitor.cpp | 2 - startupcache/StartupCache.cpp | 2 - storage/mozStorageConnection.cpp | 7 +- .../test_service_init_background_thread.cpp | 2 +- .../filewatcher/NativeFileWatcherWin.cpp | 6 +- .../components/terminator/nsTerminator.cpp | 2 - .../url-classifier/tests/gtest/Common.cpp | 3 +- toolkit/crashreporter/nsExceptionHandler.cpp | 2 +- toolkit/identity/IdentityCryptoService.cpp | 5 +- toolkit/xre/EventTracer.cpp | 1 - toolkit/xre/nsUpdateDriver.cpp | 3 +- tools/profiler/public/GeckoProfiler.h | 8 -- tools/profiler/public/GeckoProfilerImpl.h | 20 ----- widget/windows/LSPAnnotator.cpp | 2 +- widget/windows/nsSound.cpp | 7 +- xpcom/build/MainThreadIOLogger.cpp | 1 - xpcom/glue/nsThreadUtils.cpp | 85 +++++++++++++++---- xpcom/glue/nsThreadUtils.h | 56 ++++++++---- xpcom/tests/gtest/TestPipes.cpp | 10 +-- .../tests/gtest/TestRacingServiceManager.cpp | 2 +- xpcom/tests/gtest/TestThreads.cpp | 11 +-- xpcom/tests/gtest/TestTimers.cpp | 2 +- xpcom/threads/BackgroundHangMonitor.cpp | 2 - xpcom/threads/HangMonitor.cpp | 2 - xpcom/threads/LazyIdleThread.cpp | 9 +- xpcom/threads/TimerThread.cpp | 3 +- xpcom/threads/nsIThreadManager.idl | 14 --- xpcom/threads/nsProcessCommon.cpp | 8 -- xpcom/threads/nsThread.cpp | 33 +------ xpcom/threads/nsThread.h | 4 +- xpcom/threads/nsThreadManager.cpp | 10 +-- xpcom/threads/nsThreadPool.cpp | 7 +- 65 files changed, 314 insertions(+), 277 deletions(-) diff --git a/dom/gamepad/cocoa/CocoaGamepad.cpp b/dom/gamepad/cocoa/CocoaGamepad.cpp index 0000d616e223..e7c986e22a60 100644 --- a/dom/gamepad/cocoa/CocoaGamepad.cpp +++ b/dom/gamepad/cocoa/CocoaGamepad.cpp @@ -541,9 +541,8 @@ DarwinGamepadService::StartupInternal() void DarwinGamepadService::Startup() { - Unused << NS_NewNamedThread("Gamepad", - getter_AddRefs(mMonitorThread), - new DarwinGamepadServiceStartupRunnable(this)); + Unused << NS_NewThread(getter_AddRefs(mMonitorThread), + new DarwinGamepadServiceStartupRunnable(this)); } void DarwinGamepadService::Shutdown() diff --git a/dom/gamepad/windows/WindowsGamepad.cpp b/dom/gamepad/windows/WindowsGamepad.cpp index 7c2819ed05df..5f60fd0b79d8 100644 --- a/dom/gamepad/windows/WindowsGamepad.cpp +++ b/dom/gamepad/windows/WindowsGamepad.cpp @@ -1065,7 +1065,7 @@ StartGamepadMonitoring() return; } sIsShutdown = false; - NS_NewNamedThread("Gamepad", getter_AddRefs(gMonitorThread)); + NS_NewThread(getter_AddRefs(gMonitorThread)); gMonitorThread->Dispatch(new StartWindowsGamepadServiceRunnable(), NS_DISPATCH_NORMAL); } diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp index 1f84a832a0f0..fc70257c2b81 100644 --- a/dom/indexedDB/ActorsParent.cpp +++ b/dom/indexedDB/ActorsParent.cpp @@ -5720,11 +5720,6 @@ public: return mSerialNumber; } - nsCString GetThreadName() const - { - return nsPrintfCString("IndexedDB #%lu", mSerialNumber); - } - private: ~ThreadRunnable() override; @@ -12576,10 +12571,7 @@ ConnectionPool::ScheduleTransaction(TransactionInfo* aTransactionInfo, RefPtr runnable = new ThreadRunnable(); nsCOMPtr newThread; - nsresult rv = - NS_NewNamedThread(runnable->GetThreadName(), - getter_AddRefs(newThread), runnable); - if (NS_SUCCEEDED(rv)) { + if (NS_SUCCEEDED(NS_NewThread(getter_AddRefs(newThread), runnable))) { MOZ_ASSERT(newThread); IDB_DEBUG_LOG(("ConnectionPool created thread %lu", @@ -13292,6 +13284,10 @@ nsresult ConnectionPool:: ThreadRunnable::Run() { +#ifdef MOZ_ENABLE_PROFILER_SPS + char stackTopGuess; +#endif // MOZ_ENABLE_PROFILER_SPS + MOZ_ASSERT(!IsOnBackgroundThread()); MOZ_ASSERT(mContinueRunning); @@ -13302,6 +13298,18 @@ ThreadRunnable::Run() mFirstRun = false; + { + // Scope for the thread name. Both PR_SetCurrentThreadName() and + // profiler_register_thread() copy the string so we don't need to keep it. + const nsPrintfCString threadName("IndexedDB #%lu", mSerialNumber); + + PR_SetCurrentThreadName(threadName.get()); + +#ifdef MOZ_ENABLE_PROFILER_SPS + profiler_register_thread(threadName.get(), &stackTopGuess); +#endif // MOZ_ENABLE_PROFILER_SPS + } + { // Scope for the profiler label. PROFILER_LABEL("IndexedDB", @@ -13343,6 +13351,10 @@ ThreadRunnable::Run() } } +#ifdef MOZ_ENABLE_PROFILER_SPS + profiler_unregister_thread(); +#endif // MOZ_ENABLE_PROFILER_SPS + return NS_OK; } diff --git a/dom/media/FileBlockCache.cpp b/dom/media/FileBlockCache.cpp index 16a3a0043f39..d85e6cd016de 100644 --- a/dom/media/FileBlockCache.cpp +++ b/dom/media/FileBlockCache.cpp @@ -22,10 +22,9 @@ nsresult FileBlockCache::Open(PRFileDesc* aFD) } { MonitorAutoLock mon(mDataMonitor); - nsresult res = NS_NewNamedThread("FileBlockCache", - getter_AddRefs(mThread), - nullptr, - SharedThreadPool::kStackSize); + nsresult res = NS_NewThread(getter_AddRefs(mThread), + nullptr, + SharedThreadPool::kStackSize); mIsOpen = NS_SUCCEEDED(res); return res; } diff --git a/dom/media/GraphDriver.cpp b/dom/media/GraphDriver.cpp index ecb0acaecd49..33001cd332cc 100644 --- a/dom/media/GraphDriver.cpp +++ b/dom/media/GraphDriver.cpp @@ -39,6 +39,19 @@ namespace mozilla { StaticRefPtr AsyncCubebTask::sThreadPool; +struct AutoProfilerUnregisterThread +{ + // The empty ctor is used to silence a pre-4.8.0 GCC unused variable warning. + AutoProfilerUnregisterThread() + { + } + + ~AutoProfilerUnregisterThread() + { + profiler_unregister_thread(); + } +}; + GraphDriver::GraphDriver(MediaStreamGraphImpl* aGraphImpl) : mIterationStart(0), mIterationEnd(0), @@ -183,7 +196,9 @@ public: } NS_IMETHOD Run() override { + char aLocal; STREAM_LOG(LogLevel::Debug, ("Starting system thread")); + profiler_register_thread("MediaStreamGraph", &aLocal); LIFECYCLE_LOG("Starting a new system driver for graph %p\n", mDriver->mGraphImpl); @@ -301,6 +316,8 @@ SystemClockDriver::IsFallback() void ThreadedDriver::RunThread() { + AutoProfilerUnregisterThread autoUnregister; + bool stillProcessing = true; while (stillProcessing) { mIterationStart = IterationEnd(); diff --git a/dom/media/MediaRecorder.cpp b/dom/media/MediaRecorder.cpp index 4b4070257ccb..2deeb906d86b 100644 --- a/dom/media/MediaRecorder.cpp +++ b/dom/media/MediaRecorder.cpp @@ -283,6 +283,8 @@ class MediaRecorder::Session: public nsIObserver, } else { // Flush out remaining encoded data. mSession->Extract(true); + if (mSession->mIsRegisterProfiler) + profiler_unregister_thread(); if (NS_FAILED(NS_DispatchToMainThread( new DestroyRunnable(mSession)))) { MOZ_ASSERT(false, "NS_DispatchToMainThread DestroyRunnable failed"); @@ -417,6 +419,7 @@ public: , mTimeSlice(aTimeSlice) , mStopIssued(false) , mIsStartEventFired(false) + , mIsRegisterProfiler(false) , mNeedSessionEndTask(true) , mSelectedVideoTrackID(TRACK_NONE) { @@ -604,6 +607,12 @@ private: MOZ_ASSERT(NS_GetCurrentThread() == mReadThread); LOG(LogLevel::Debug, ("Session.Extract %p", this)); + if (!mIsRegisterProfiler) { + char aLocal; + profiler_register_thread("Media_Encoder", &aLocal); + mIsRegisterProfiler = true; + } + PROFILER_LABEL("MediaRecorder", "Session Extract", js::ProfileEntry::Category::OTHER); @@ -913,6 +922,8 @@ private: bool mStopIssued; // Indicate the session had fire start event. Encoding thread only. bool mIsStartEventFired; + // The register flag for "Media_Encoder" thread to profiler + bool mIsRegisterProfiler; // False if the InitEncoder called successfully, ensure the // ExtractRunnable/DestroyRunnable will end the session. // Main thread only. diff --git a/dom/media/android/AndroidMediaResourceServer.cpp b/dom/media/android/AndroidMediaResourceServer.cpp index f6ca13f5aa61..bd76a8c68c49 100644 --- a/dom/media/android/AndroidMediaResourceServer.cpp +++ b/dom/media/android/AndroidMediaResourceServer.cpp @@ -375,7 +375,7 @@ ResourceSocketListener::OnSocketAccepted(nsIServerSocket* aServ, if (NS_FAILED(rv)) return rv; nsCOMPtr thread; - rv = NS_NewNamedThread("ServeResource", getter_AddRefs(thread)); + rv = NS_NewThread(getter_AddRefs(thread)); if (NS_FAILED(rv)) return rv; nsCOMPtr event = new ServeResourceEvent(input.get(), output.get(), mServer); diff --git a/dom/media/gtest/TestMP4Reader.cpp b/dom/media/gtest/TestMP4Reader.cpp index 2cf72681585c..f08f7a40da3c 100644 --- a/dom/media/gtest/TestMP4Reader.cpp +++ b/dom/media/gtest/TestMP4Reader.cpp @@ -44,7 +44,7 @@ public: void Init() { nsCOMPtr thread; nsCOMPtr r = NewRunnableMethod(this, &TestBinding::ReadMetadata); - nsresult rv = NS_NewNamedThread("ReadMetadata", getter_AddRefs(thread), r); + nsresult rv = NS_NewThread(getter_AddRefs(thread), r); EXPECT_EQ(NS_OK, rv); thread->Shutdown(); } diff --git a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp index 41be2c2daa5d..090e1b2172af 100644 --- a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp +++ b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp @@ -28,7 +28,6 @@ #include "HRTFDatabaseLoader.h" #include "HRTFDatabase.h" -#include "GeckoProfiler.h" using namespace mozilla; @@ -152,7 +151,6 @@ void HRTFDatabaseLoader::MainThreadRelease() // Asynchronously load the database in this thread. static void databaseLoaderEntry(void* threadData) { - AutoProfilerRegister registerThread("HRTFDatabaseLdr"); PR_SetCurrentThreadName("HRTFDatabaseLdr"); HRTFDatabaseLoader* loader = reinterpret_cast(threadData); diff --git a/dom/plugins/base/android/ANPAudio.cpp b/dom/plugins/base/android/ANPAudio.cpp index dd4f0b29cdbe..bc47e8999e7a 100644 --- a/dom/plugins/base/android/ANPAudio.cpp +++ b/dom/plugins/base/android/ANPAudio.cpp @@ -122,6 +122,8 @@ public: NS_IMETHODIMP AudioRunnable::Run() { + PR_SetCurrentThreadName("Android Audio"); + JNIEnv* const jenv = mozilla::jni::GetEnvForThread(); mozilla::AutoLocalJNIFrame autoFrame(jenv, 2); @@ -319,7 +321,7 @@ anp_audio_start(ANPAudioTrack* s) RefPtr runnable = new AudioRunnable(s); nsCOMPtr thread; - NS_NewNamedThread("Android Audio", getter_AddRefs(thread), runnable); + NS_NewThread(getter_AddRefs(thread), runnable); } void diff --git a/dom/storage/DOMStorageDBThread.cpp b/dom/storage/DOMStorageDBThread.cpp index 7f9039484d82..d479fbb783f4 100644 --- a/dom/storage/DOMStorageDBThread.cpp +++ b/dom/storage/DOMStorageDBThread.cpp @@ -27,7 +27,6 @@ #include "mozilla/IOInterposer.h" #include "mozilla/Services.h" #include "mozilla/Tokenizer.h" -#include "GeckoProfiler.h" // How long we collect write oprerations // before they are flushed to the database @@ -338,7 +337,6 @@ DOMStorageDBThread::SetDefaultPriority() void DOMStorageDBThread::ThreadFunc(void* aArg) { - AutoProfilerRegister registerThread("localStorage DB"); PR_SetCurrentThreadName("localStorage DB"); mozilla::IOInterposer::RegisterCurrentThread(); diff --git a/dom/system/gonk/GonkGPSGeolocationProvider.cpp b/dom/system/gonk/GonkGPSGeolocationProvider.cpp index b3336f02af12..9ce6ce2e5a30 100644 --- a/dom/system/gonk/GonkGPSGeolocationProvider.cpp +++ b/dom/system/gonk/GonkGPSGeolocationProvider.cpp @@ -556,7 +556,7 @@ GonkGPSGeolocationProvider::Startup() } if (!mInitThread) { - nsresult rv = NS_NewNamedThread("Gonk GPS", getter_AddRefs(mInitThread)); + nsresult rv = NS_NewThread(getter_AddRefs(mInitThread)); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/gfx/layers/LayerScope.cpp b/gfx/layers/LayerScope.cpp index 55f87023d6d7..a3b7778ef40f 100644 --- a/gfx/layers/LayerScope.cpp +++ b/gfx/layers/LayerScope.cpp @@ -1569,7 +1569,7 @@ LayerScopeWebSocketManager::SocketHandler::CloseConnection() LayerScopeWebSocketManager::LayerScopeWebSocketManager() : mHandlerMutex("LayerScopeWebSocketManager::mHandlerMutex") { - NS_NewNamedThread("LayerScope", getter_AddRefs(mDebugSenderThread)); + NS_NewThread(getter_AddRefs(mDebugSenderThread)); mServerSocket = do_CreateInstance(NS_SERVERSOCKET_CONTRACTID); int port = gfxPrefs::LayerScopePort(); diff --git a/hal/gonk/GonkHal.cpp b/hal/gonk/GonkHal.cpp index e2ca40fbbac6..05d9295a225d 100644 --- a/hal/gonk/GonkHal.cpp +++ b/hal/gonk/GonkHal.cpp @@ -395,7 +395,7 @@ EnsureVibratorThreadInitialized() sVibratorRunnable = new VibratorRunnable(); nsCOMPtr thread; - NS_NewNamedThread("Gonk Vibrator", getter_AddRefs(thread), sVibratorRunnable); + NS_NewThread(getter_AddRefs(thread), sVibratorRunnable); } } // namespace diff --git a/image/DecodePool.cpp b/image/DecodePool.cpp index 8053b2f9d19d..9aa3d58229f4 100644 --- a/image/DecodePool.cpp +++ b/image/DecodePool.cpp @@ -60,6 +60,14 @@ public: , mShuttingDown(false) { } + /// Initialize the current thread for use by the decode pool. + void InitCurrentThread() + { + MOZ_ASSERT(!NS_IsMainThread()); + + mThreadNaming.SetThreadPoolName(NS_LITERAL_CSTRING("ImgDecoder")); + } + /// Shut down the provided decode pool thread. static void ShutdownThread(nsIThread* aThisThread) { @@ -127,12 +135,6 @@ public: } while (true); } - nsresult CreateThread(nsIThread** aThread, nsIRunnable* aInitialEvent) - { - return NS_NewNamedThread(mThreadNaming.GetNextThreadName("ImgDecoder"), - aThread, aInitialEvent); - } - private: ~DecodePoolImpl() { } @@ -164,11 +166,22 @@ public: NS_IMETHOD Run() override { +#ifdef MOZ_ENABLE_PROFILER_SPS + char stackBaseGuess; // Need to be the first variable of main loop function. +#endif // MOZ_ENABLE_PROFILER_SPS + MOZ_ASSERT(!NS_IsMainThread()); + mImpl->InitCurrentThread(); + nsCOMPtr thisThread; nsThreadManager::get().GetCurrentThread(getter_AddRefs(thisThread)); +#ifdef MOZ_ENABLE_PROFILER_SPS + // InitCurrentThread() has assigned the thread name. + profiler_register_thread(PR_GetThreadName(PR_GetCurrentThread()), &stackBaseGuess); +#endif // MOZ_ENABLE_PROFILER_SPS + do { Work work = mImpl->PopWork(); switch (work.mType) { @@ -259,7 +272,7 @@ DecodePool::DecodePool() for (uint32_t i = 0 ; i < limit ; ++i) { nsCOMPtr worker = new DecodePoolWorker(mImpl); nsCOMPtr thread; - nsresult rv = mImpl->CreateThread(getter_AddRefs(thread), worker); + nsresult rv = NS_NewThread(getter_AddRefs(thread), worker); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && thread, "Should successfully create image decoding threads"); mThreads.AppendElement(Move(thread)); diff --git a/image/test/gtest/TestDecodeToSurface.cpp b/image/test/gtest/TestDecodeToSurface.cpp index 278cdb1fdc89..bd52e75901c8 100644 --- a/image/test/gtest/TestDecodeToSurface.cpp +++ b/image/test/gtest/TestDecodeToSurface.cpp @@ -69,8 +69,7 @@ RunDecodeToSurface(const ImageTestCase& aTestCase) ASSERT_TRUE(inputStream != nullptr); nsCOMPtr thread; - nsresult rv = - NS_NewNamedThread("DecodeToSurface", getter_AddRefs(thread), nullptr); + nsresult rv = NS_NewThread(getter_AddRefs(thread), nullptr); ASSERT_TRUE(NS_SUCCEEDED(rv)); // We run the DecodeToSurface tests off-main-thread to ensure that diff --git a/ipc/chromium/src/base/thread.cc b/ipc/chromium/src/base/thread.cc index 05463aecac18..feec3aedf797 100644 --- a/ipc/chromium/src/base/thread.cc +++ b/ipc/chromium/src/base/thread.cc @@ -153,7 +153,8 @@ void Thread::StopSoon() { } void Thread::ThreadMain() { - mozilla::AutoProfilerRegister registerThread(name_.c_str()); + char aLocal; + profiler_register_thread(name_.c_str(), &aLocal); mozilla::IOInterposer::RegisterCurrentThread(); // The message loop for this thread. @@ -185,6 +186,7 @@ void Thread::ThreadMain() { DCHECK(GetThreadWasQuitProperly()); mozilla::IOInterposer::UnregisterCurrentThread(); + profiler_unregister_thread(); #ifdef MOZ_TASK_TRACER mozilla::tasktracer::FreeTraceInfo(); diff --git a/ipc/glue/BackgroundImpl.cpp b/ipc/glue/BackgroundImpl.cpp index 86b619f8f2f0..2f8e073f8397 100644 --- a/ipc/glue/BackgroundImpl.cpp +++ b/ipc/glue/BackgroundImpl.cpp @@ -1344,6 +1344,8 @@ ParentImpl::RequestMessageLoopRunnable::Run() AssertIsInMainProcess(); MOZ_ASSERT(mTargetThread); + char stackBaseGuess; + if (NS_IsMainThread()) { MOZ_ASSERT(mMessageLoop); @@ -1373,6 +1375,8 @@ ParentImpl::RequestMessageLoopRunnable::Run() return NS_OK; } + profiler_register_thread("IPDL Background", &stackBaseGuess); + #ifdef DEBUG { bool correctThread; @@ -1410,6 +1414,8 @@ ParentImpl::ShutdownBackgroundThreadRunnable::Run() // sBackgroundPRThread and we should not modify it here. sBackgroundPRThread.compareExchange(PR_GetCurrentThread(), nullptr); + profiler_unregister_thread(); + return NS_OK; } diff --git a/js/xpconnect/src/XPCJSContext.cpp b/js/xpconnect/src/XPCJSContext.cpp index 0393ae9ef498..5b4d184ea2f8 100644 --- a/js/xpconnect/src/XPCJSContext.cpp +++ b/js/xpconnect/src/XPCJSContext.cpp @@ -1166,7 +1166,6 @@ AutoLockWatchdog::~AutoLockWatchdog() static void WatchdogMain(void* arg) { - mozilla::AutoProfilerRegister registerThread("JS Watchdog"); PR_SetCurrentThreadName("JS Watchdog"); Watchdog* self = static_cast(arg); diff --git a/media/mtransport/nr_socket_prsock.cpp b/media/mtransport/nr_socket_prsock.cpp index 1aab40f8b478..f22229df86f5 100644 --- a/media/mtransport/nr_socket_prsock.cpp +++ b/media/mtransport/nr_socket_prsock.cpp @@ -212,9 +212,10 @@ public: nsrefcnt count = ++mUseCount; if (count == 1) { // idle -> in-use - nsresult rv = NS_NewNamedThread(mName, getter_AddRefs(mThread)); + nsresult rv = NS_NewThread(getter_AddRefs(mThread)); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && mThread, "Should successfully create mtransport I/O thread"); + NS_SetThreadName(mThread, mName); r_log(LOG_GENERIC,LOG_DEBUG,"Created wrapped SingletonThread %p", mThread.get()); } diff --git a/netwerk/base/BackgroundFileSaver.cpp b/netwerk/base/BackgroundFileSaver.cpp index ee81113006b3..e4bc05826249 100644 --- a/netwerk/base/BackgroundFileSaver.cpp +++ b/netwerk/base/BackgroundFileSaver.cpp @@ -152,7 +152,7 @@ BackgroundFileSaver::Init() rv = NS_GetCurrentThread(getter_AddRefs(mControlThread)); NS_ENSURE_SUCCESS(rv, rv); - rv = NS_NewNamedThread("BgFileSaver", getter_AddRefs(mWorkerThread)); + rv = NS_NewThread(getter_AddRefs(mWorkerThread)); NS_ENSURE_SUCCESS(rv, rv); sThreadCount++; diff --git a/netwerk/base/nsPACMan.cpp b/netwerk/base/nsPACMan.cpp index 43c569d8b3fd..37d3e8b6bba2 100644 --- a/netwerk/base/nsPACMan.cpp +++ b/netwerk/base/nsPACMan.cpp @@ -742,15 +742,27 @@ nsPACMan::AsyncOnChannelRedirect(nsIChannel *oldChannel, nsIChannel *newChannel, return NS_OK; } +void +nsPACMan::NamePACThread() +{ + MOZ_ASSERT(!NS_IsMainThread(), "wrong thread"); + PR_SetCurrentThreadName("Proxy Resolution"); +} + nsresult nsPACMan::Init(nsISystemProxySettings *systemProxySettings) { mSystemProxySettings = systemProxySettings; - nsresult rv = - NS_NewNamedThread("ProxyResolution", getter_AddRefs(mPACThread)); + nsresult rv = NS_NewThread(getter_AddRefs(mPACThread), nullptr); + if (NS_FAILED(rv)) + return rv; - return rv; + // don't check return value as it is not a big deal for this to fail. + mPACThread->Dispatch(NewRunnableMethod(this, &nsPACMan::NamePACThread), + nsIEventTarget::DISPATCH_NORMAL); + + return NS_OK; } } // namespace net diff --git a/netwerk/base/nsPACMan.h b/netwerk/base/nsPACMan.h index df952ff9ee25..def0843cb80a 100644 --- a/netwerk/base/nsPACMan.h +++ b/netwerk/base/nsPACMan.h @@ -214,6 +214,7 @@ private: void PostProcessPendingQ(); void PostCancelPendingQ(nsresult); bool ProcessPending(); + void NamePACThread(); private: ProxyAutoConfig mPAC; diff --git a/netwerk/base/nsSocketTransportService2.cpp b/netwerk/base/nsSocketTransportService2.cpp index b47eee88e6c4..4705a6055d94 100644 --- a/netwerk/base/nsSocketTransportService2.cpp +++ b/netwerk/base/nsSocketTransportService2.cpp @@ -833,6 +833,11 @@ nsSocketTransportService::MarkTheLastElementOfPendingQueue() NS_IMETHODIMP nsSocketTransportService::Run() { +#ifdef MOZ_ENABLE_PROFILER_SPS + char stackBaseGuess; // Need to be the first variable of main loop function. + profiler_register_thread(PR_GetThreadName(PR_GetCurrentThread()), &stackBaseGuess); +#endif // MOZ_ENABLE_PROFILER_SPS + SOCKET_LOG(("STS thread init %d sockets\n", gMaxCount)); psm::InitializeSSLServerCertVerificationThreads(); @@ -1014,6 +1019,10 @@ nsSocketTransportService::Run() SOCKET_LOG(("STS thread exit\n")); +#ifdef MOZ_ENABLE_PROFILER_SPS + profiler_unregister_thread(); +#endif // MOZ_ENABLE_PROFILER_SPS + return NS_OK; } diff --git a/netwerk/cache2/CacheIOThread.cpp b/netwerk/cache2/CacheIOThread.cpp index be5092a6d09c..66742679c9ac 100644 --- a/netwerk/cache2/CacheIOThread.cpp +++ b/netwerk/cache2/CacheIOThread.cpp @@ -10,7 +10,6 @@ #include "nsPrintfCString.h" #include "nsThreadUtils.h" #include "mozilla/IOInterposer.h" -#include "GeckoProfiler.h" #ifdef XP_WIN #include @@ -438,7 +437,6 @@ already_AddRefed CacheIOThread::Target() // static void CacheIOThread::ThreadFunc(void* aClosure) { - AutoProfilerRegister registerThread("Cache2 I/O"); PR_SetCurrentThreadName("Cache2 I/O"); mozilla::IOInterposer::RegisterCurrentThread(); CacheIOThread* thread = static_cast(aClosure); diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index 8924ed7e4d10..f2e26cadd4eb 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -29,7 +29,6 @@ #include "nsURLHelper.h" #include "nsThreadUtils.h" #include "GetAddrInfo.h" -#include "GeckoProfiler.h" #include "mozilla/HashFunctions.h" #include "mozilla/TimeStamp.h" @@ -1436,15 +1435,10 @@ nsHostResolver::SizeOfIncludingThis(MallocSizeOf mallocSizeOf) const void nsHostResolver::ThreadFunc(void *arg) { - char stackTop; - LOG(("DNS lookup thread - starting execution.\n")); static nsThreadPoolNaming naming; - nsCString name = naming.GetNextThreadName("DNS Resolver"); - - PR_SetCurrentThreadName(name.BeginReading()); - profiler_register_thread(name.BeginReading(), &stackTop); + naming.SetThreadPoolName(NS_LITERAL_CSTRING("DNS Resolver")); #if defined(RES_RETRY_ON_FAILURE) nsResState rs; @@ -1515,8 +1509,6 @@ nsHostResolver::ThreadFunc(void *arg) resolver->mThreadCount--; NS_RELEASE(resolver); LOG(("DNS lookup thread - queue empty, thread finished.\n")); - - profiler_unregister_thread(); } nsresult diff --git a/netwerk/sctp/datachannel/DataChannel.cpp b/netwerk/sctp/datachannel/DataChannel.cpp index b5adef05ab66..98810061bb24 100644 --- a/netwerk/sctp/datachannel/DataChannel.cpp +++ b/netwerk/sctp/datachannel/DataChannel.cpp @@ -2326,9 +2326,8 @@ DataChannelConnection::SendBlob(uint16_t stream, nsIInputStream *aBlob) NS_ENSURE_TRUE(channel, 0); // Spawn a thread to send the data if (!mInternalIOThread) { - nsresult rv = NS_NewNamedThread("DataChannel IO", - getter_AddRefs(mInternalIOThread)); - if (NS_FAILED(rv)) { + nsresult res = NS_NewThread(getter_AddRefs(mInternalIOThread)); + if (NS_FAILED(res)) { return -1; } } diff --git a/netwerk/system/win32/nsNotifyAddrListener.cpp b/netwerk/system/win32/nsNotifyAddrListener.cpp index bebbf4d0efc9..5d1ec3a61fe1 100644 --- a/netwerk/system/win32/nsNotifyAddrListener.cpp +++ b/netwerk/system/win32/nsNotifyAddrListener.cpp @@ -323,6 +323,8 @@ nsNotifyAddrListener::nextCoalesceWaitTime() NS_IMETHODIMP nsNotifyAddrListener::Run() { + PR_SetCurrentThreadName("Link Monitor"); + mStartTime = TimeStamp::Now(); calculateNetworkId(); @@ -419,7 +421,7 @@ nsNotifyAddrListener::Init(void) mCheckEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); NS_ENSURE_TRUE(mCheckEvent, NS_ERROR_OUT_OF_MEMORY); - rv = NS_NewNamedThread("Link Monitor", getter_AddRefs(mThread), this); + rv = NS_NewThread(getter_AddRefs(mThread), this); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; diff --git a/netwerk/test/TestFileInput2.cpp b/netwerk/test/TestFileInput2.cpp index a23437891b9d..f51988010e20 100644 --- a/netwerk/test/TestFileInput2.cpp +++ b/netwerk/test/TestFileInput2.cpp @@ -315,7 +315,7 @@ NS_IMPL_ISUPPORTS(FileChannelWorker, nsIRunnable) //////////////////////////////////////////////////////////////////////////////// void -Test(CreateFun create, const char* name, uint32_t count, +Test(CreateFun create, uint32_t count, nsIFile* inDirSpec, nsIFile* outDirSpec, uint32_t bufSize) { nsresult rv; @@ -375,8 +375,7 @@ Test(CreateFun create, const char* name, uint32_t count, bufSize); if (NS_FAILED(rv)) goto done; - rv = NS_NewNamedThread(name, getter_AddRefs(thread), - worker, 0, PR_JOINABLE_THREAD); + rv = NS_NewThread(getter_AddRefs(thread), worker, 0, PR_JOINABLE_THREAD); if (NS_FAILED(rv)) goto done; bool inserted = threads.InsertObjectAt(thread, i); @@ -434,44 +433,42 @@ main(int argc, char* argv[]) if (NS_FAILED(rv)) return rv; CreateFun create = FileChannelWorker::Create; - const char* name = "FileChannelWorker"; Test(create, 1, inDirFile, outDirFile, 16 * 1024); #if 1 printf("FileChannelWorker *****************************\n"); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); #endif create = FileSpecWorker::Create; - name = "FileSpecWorker"; printf("FileSpecWorker ********************************\n"); #if 1 - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); #endif #if 1 - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); #endif } // this scopes the nsCOMPtrs // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM diff --git a/netwerk/wifi/nsWifiMonitor.cpp b/netwerk/wifi/nsWifiMonitor.cpp index 2c1885f2be78..4613a107dc61 100644 --- a/netwerk/wifi/nsWifiMonitor.cpp +++ b/netwerk/wifi/nsWifiMonitor.cpp @@ -84,7 +84,7 @@ NS_IMETHODIMP nsWifiMonitor::StartWatching(nsIWifiListener *aListener) } if (!mThread) { - rv = NS_NewNamedThread("Wifi Monitor", getter_AddRefs(mThread), this); + rv = NS_NewThread(getter_AddRefs(mThread), this); if (NS_FAILED(rv)) return rv; } @@ -155,6 +155,8 @@ NS_IMETHODIMP nsWifiMonitor::Run() { LOG(("@@@@@ wifi monitor run called\n")); + PR_SetCurrentThreadName("Wifi Monitor"); + nsresult rv = DoScan(); LOG(("@@@@@ wifi monitor run::doscan complete %x\n", rv)); diff --git a/security/manager/ssl/CryptoTask.cpp b/security/manager/ssl/CryptoTask.cpp index 2ffc1d93159a..71b8ac88d5b3 100644 --- a/security/manager/ssl/CryptoTask.cpp +++ b/security/manager/ssl/CryptoTask.cpp @@ -31,13 +31,13 @@ CryptoTask::Dispatch(const nsACString& taskThreadName) } // Can't add 'this' as the event to run, since mThread may not be set yet - nsresult rv = NS_NewNamedThread(taskThreadName, getter_AddRefs(mThread), - nullptr, - nsIThreadManager::DEFAULT_STACK_SIZE); + nsresult rv = NS_NewThread(getter_AddRefs(mThread), nullptr, + nsIThreadManager::DEFAULT_STACK_SIZE); if (NS_FAILED(rv)) { return rv; } + NS_SetThreadName(mThread, taskThreadName); // Note: event must not null out mThread! return mThread->Dispatch(this, NS_DISPATCH_NORMAL); } diff --git a/security/manager/ssl/nsKeygenThread.cpp b/security/manager/ssl/nsKeygenThread.cpp index 4ff0304e229a..b295c4f36895 100644 --- a/security/manager/ssl/nsKeygenThread.cpp +++ b/security/manager/ssl/nsKeygenThread.cpp @@ -12,7 +12,6 @@ #include "nsNSSShutDown.h" #include "PSMRunnable.h" #include "mozilla/DebugOnly.h" -#include "GeckoProfiler.h" using namespace mozilla; using namespace mozilla::psm; @@ -115,7 +114,6 @@ nsresult nsKeygenThread::ConsumeResult( static void nsKeygenThreadRunner(void *arg) { - AutoProfilerRegister registerThread("Keygen"); PR_SetCurrentThreadName("Keygen"); nsKeygenThread *self = static_cast(arg); self->Run(); diff --git a/security/manager/ssl/nsProtectedAuthThread.cpp b/security/manager/ssl/nsProtectedAuthThread.cpp index bb930188b874..ea511b24a63d 100644 --- a/security/manager/ssl/nsProtectedAuthThread.cpp +++ b/security/manager/ssl/nsProtectedAuthThread.cpp @@ -11,7 +11,6 @@ #include "nsReadableUtils.h" #include "nsPKCS11Slot.h" #include "nsProtectedAuthThread.h" -#include "GeckoProfiler.h" using namespace mozilla; using namespace mozilla::psm; @@ -20,7 +19,6 @@ NS_IMPL_ISUPPORTS(nsProtectedAuthThread, nsIProtectedAuthThread) static void nsProtectedAuthThreadRunner(void *arg) { - AutoProfilerRegister registerThread("Protected Auth"); PR_SetCurrentThreadName("Protected Auth"); nsProtectedAuthThread *self = static_cast(arg); diff --git a/security/manager/ssl/nsSmartCardMonitor.cpp b/security/manager/ssl/nsSmartCardMonitor.cpp index a5cb8610aef2..3423d4f5f5f1 100644 --- a/security/manager/ssl/nsSmartCardMonitor.cpp +++ b/security/manager/ssl/nsSmartCardMonitor.cpp @@ -10,7 +10,6 @@ #include "nsIObserverService.h" #include "nsServiceManagerUtils.h" #include "nsThreadUtils.h" -#include "GeckoProfiler.h" #include "nspr.h" #include "pk11func.h" @@ -391,7 +390,6 @@ const SECMODModule* SmartCardMonitoringThread::GetModule() // C-like calling sequence to glue into PR_CreateThread. void SmartCardMonitoringThread::LaunchExecute(void* arg) { - AutoProfilerRegister registerThread("SmartCard"); PR_SetCurrentThreadName("SmartCard"); ((SmartCardMonitoringThread*)arg)->Execute(); diff --git a/startupcache/StartupCache.cpp b/startupcache/StartupCache.cpp index f698187170a5..6d1dd7a3a3ff 100644 --- a/startupcache/StartupCache.cpp +++ b/startupcache/StartupCache.cpp @@ -36,7 +36,6 @@ #include "nsThreadUtils.h" #include "nsXULAppAPI.h" #include "nsIProtocolHandler.h" -#include "GeckoProfiler.h" #ifdef IS_BIG_ENDIAN #define SC_ENDIAN "big" @@ -504,7 +503,6 @@ StartupCache::WaitOnWriteThread() void StartupCache::ThreadedWrite(void *aClosure) { - AutoProfilerRegister registerThread("StartupCache"); PR_SetCurrentThreadName("StartupCache"); mozilla::IOInterposer::RegisterCurrentThread(); /* diff --git a/storage/mozStorageConnection.cpp b/storage/mozStorageConnection.cpp index 6129ac4442a1..2ad50fb51d21 100644 --- a/storage/mozStorageConnection.cpp +++ b/storage/mozStorageConnection.cpp @@ -589,13 +589,14 @@ Connection::getAsyncExecutionTarget() return nullptr; if (!mAsyncExecutionThread) { - static nsThreadPoolNaming naming; - nsresult rv = NS_NewNamedThread(naming.GetNextThreadName("mozStorage"), - getter_AddRefs(mAsyncExecutionThread)); + nsresult rv = ::NS_NewThread(getter_AddRefs(mAsyncExecutionThread)); if (NS_FAILED(rv)) { NS_WARNING("Failed to create async thread."); return nullptr; } + static nsThreadPoolNaming naming; + naming.SetThreadPoolName(NS_LITERAL_CSTRING("mozStorage"), + mAsyncExecutionThread); } #ifdef DEBUG diff --git a/storage/test/gtest/test_service_init_background_thread.cpp b/storage/test/gtest/test_service_init_background_thread.cpp index e811e249702b..022026cbaefd 100644 --- a/storage/test/gtest/test_service_init_background_thread.cpp +++ b/storage/test/gtest/test_service_init_background_thread.cpp @@ -46,7 +46,7 @@ TEST(storage_service_init_background_thread_DeathTest, Test) do_check_true(event); nsCOMPtr thread; - do_check_success(NS_NewNamedThread("StorageService", getter_AddRefs(thread))); + do_check_success(NS_NewThread(getter_AddRefs(thread))); do_check_success(thread->Dispatch(event, NS_DISPATCH_NORMAL)); diff --git a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp index 8e2ed8a7278e..8bb40bfd4d89 100644 --- a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp +++ b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp @@ -1253,8 +1253,7 @@ NativeFileWatcherService::Init() // Start the IO worker thread. mWorkerIORunnable = new NativeFileWatcherIOTask(completionPort); - nsresult rv = NS_NewNamedThread("FileWatcher IO", getter_AddRefs(mIOThread), - mWorkerIORunnable); + nsresult rv = NS_NewThread(getter_AddRefs(mIOThread), mWorkerIORunnable); if (NS_FAILED(rv)) { FILEWATCHERLOG( "NativeFileWatcherIOTask::Init - Unable to create and dispatch the worker thread (%x).", @@ -1262,6 +1261,9 @@ NativeFileWatcherService::Init() return rv; } + // Set the name for the worker thread. + NS_SetThreadName(mIOThread, "FileWatcher IO"); + mIOCompletionPort = completionPort.forget(); return NS_OK; diff --git a/toolkit/components/terminator/nsTerminator.cpp b/toolkit/components/terminator/nsTerminator.cpp index 4cc156d8f2a3..e3d958a8807f 100644 --- a/toolkit/components/terminator/nsTerminator.cpp +++ b/toolkit/components/terminator/nsTerminator.cpp @@ -32,7 +32,6 @@ #if defined(MOZ_CRASHREPORTER) #include "nsExceptionHandler.h" #endif -#include "GeckoProfiler.h" #if defined(XP_WIN) #include @@ -215,7 +214,6 @@ PRMonitor* gWriteReady = nullptr; void RunWriter(void* arg) { - AutoProfilerRegister registerThread("Shutdown Statistics Writer"); PR_SetCurrentThreadName("Shutdown Statistics Writer"); MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(arg); diff --git a/toolkit/components/url-classifier/tests/gtest/Common.cpp b/toolkit/components/url-classifier/tests/gtest/Common.cpp index b2c9bad8bc41..b5f024b38e41 100644 --- a/toolkit/components/url-classifier/tests/gtest/Common.cpp +++ b/toolkit/components/url-classifier/tests/gtest/Common.cpp @@ -14,8 +14,7 @@ template void RunTestInNewThread(Function&& aFunction) { nsCOMPtr r = NS_NewRunnableFunction(mozilla::Forward(aFunction)); nsCOMPtr testingThread; - nsresult rv = - NS_NewNamedThread("Testing Thread", getter_AddRefs(testingThread), r); + nsresult rv = NS_NewThread(getter_AddRefs(testingThread), r); ASSERT_EQ(rv, NS_OK); testingThread->Shutdown(); } diff --git a/toolkit/crashreporter/nsExceptionHandler.cpp b/toolkit/crashreporter/nsExceptionHandler.cpp index 5922b9b80c2d..9fd69f504830 100644 --- a/toolkit/crashreporter/nsExceptionHandler.cpp +++ b/toolkit/crashreporter/nsExceptionHandler.cpp @@ -3609,7 +3609,7 @@ InjectCrashReporterIntoProcess(DWORD processID, InjectorCrashCallback* cb) OOPInit(); if (!sInjectorThread) { - if (NS_FAILED(NS_NewNamedThread("CrashRep Inject", &sInjectorThread))) + if (NS_FAILED(NS_NewThread(&sInjectorThread))) return; } diff --git a/toolkit/identity/IdentityCryptoService.cpp b/toolkit/identity/IdentityCryptoService.cpp index 5ad3fd19c9d4..0aeaed2f3f94 100644 --- a/toolkit/identity/IdentityCryptoService.cpp +++ b/toolkit/identity/IdentityCryptoService.cpp @@ -205,8 +205,7 @@ IdentityCryptoService::GenerateKeyPair( nsCOMPtr r = new KeyGenRunnable(keyType, callback); nsCOMPtr thread; - nsresult rv = NS_NewNamedThread("GenerateKeyPair", getter_AddRefs(thread), - r); + nsresult rv = NS_NewThread(getter_AddRefs(thread), r); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -310,7 +309,7 @@ KeyPair::Sign(const nsACString & textToSign, callback); nsCOMPtr thread; - nsresult rv = NS_NewNamedThread("KeyPair Sign", getter_AddRefs(thread), r); + nsresult rv = NS_NewThread(getter_AddRefs(thread), r); return rv; } diff --git a/toolkit/xre/EventTracer.cpp b/toolkit/xre/EventTracer.cpp index 622334f43eda..cb0d88524db4 100644 --- a/toolkit/xre/EventTracer.cpp +++ b/toolkit/xre/EventTracer.cpp @@ -122,7 +122,6 @@ class EventLoopLagDispatcher : public Runnable */ void TracerThread(void *arg) { - AutoProfilerRegister registerThread("Event Tracer"); PR_SetCurrentThreadName("Event Tracer"); TracerStartClosure* threadArgs = static_cast(arg); diff --git a/toolkit/xre/nsUpdateDriver.cpp b/toolkit/xre/nsUpdateDriver.cpp index 8c1bb9bca843..ce60c652187a 100644 --- a/toolkit/xre/nsUpdateDriver.cpp +++ b/toolkit/xre/nsUpdateDriver.cpp @@ -1246,8 +1246,7 @@ nsUpdateProcessor::ProcessUpdate(nsIUpdate* aUpdate) MOZ_ASSERT(NS_IsMainThread(), "not main thread"); nsCOMPtr r = NewRunnableMethod(this, &nsUpdateProcessor::StartStagedUpdate); - return NS_NewNamedThread("Update Watcher", getter_AddRefs(mProcessWatcher), - r); + return NS_NewThread(getter_AddRefs(mProcessWatcher), r); } diff --git a/tools/profiler/public/GeckoProfiler.h b/tools/profiler/public/GeckoProfiler.h index 81452dd6563c..bef017d11558 100644 --- a/tools/profiler/public/GeckoProfiler.h +++ b/tools/profiler/public/GeckoProfiler.h @@ -248,14 +248,6 @@ static inline bool profiler_in_privacy_mode() { return false; } static inline void profiler_log(const char *str) {} static inline void profiler_log(const char *fmt, va_list args) {} -class AutoProfilerRegister final MOZ_STACK_CLASS -{ - AutoProfilerRegister(const char* aName) {} -private: - AutoProfilerRegister(const AutoProfilerRegister&) = delete; - AutoProfilerRegister& operator=(const AutoProfilerRegister&) = delete; -}; - #else #include "GeckoProfilerImpl.h" diff --git a/tools/profiler/public/GeckoProfilerImpl.h b/tools/profiler/public/GeckoProfilerImpl.h index 2522400fff62..a32096b94315 100644 --- a/tools/profiler/public/GeckoProfilerImpl.h +++ b/tools/profiler/public/GeckoProfilerImpl.h @@ -461,26 +461,6 @@ private: void* mHandle; }; -/** - * Convenience class to register and unregister a thread with the profiler. - * Needs to be the first object on the stack of the thread. - */ -class MOZ_STACK_CLASS AutoProfilerRegister final -{ -public: - explicit AutoProfilerRegister(const char* aName) - { - profiler_register_thread(aName, this); - } - ~AutoProfilerRegister() - { - profiler_unregister_thread(); - } -private: - AutoProfilerRegister(const AutoProfilerRegister&) = delete; - AutoProfilerRegister& operator=(const AutoProfilerRegister&) = delete; -}; - } // namespace mozilla inline PseudoStack* mozilla_get_pseudo_stack(void) diff --git a/widget/windows/LSPAnnotator.cpp b/widget/windows/LSPAnnotator.cpp index 5e8f465116e1..5b0c1d14b484 100644 --- a/widget/windows/LSPAnnotator.cpp +++ b/widget/windows/LSPAnnotator.cpp @@ -151,7 +151,7 @@ void LSPAnnotate() nsCOMPtr thread; nsCOMPtr runnable = do_QueryObject(new LSPAnnotationGatherer()); - NS_NewNamedThread("LSP Annotate", getter_AddRefs(thread), runnable); + NS_NewThread(getter_AddRefs(thread), runnable); } } // namespace crashreporter diff --git a/widget/windows/nsSound.cpp b/widget/windows/nsSound.cpp index a22e048df3ef..5635f8356b9d 100644 --- a/widget/windows/nsSound.cpp +++ b/widget/windows/nsSound.cpp @@ -241,9 +241,7 @@ NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias) return NS_OK; nsCOMPtr player = new nsSoundPlayer(this, aSoundAlias); NS_ENSURE_TRUE(player, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = - NS_NewNamedThread("PlaySystemSound", getter_AddRefs(mPlayerThread), - player); + nsresult rv = NS_NewThread(getter_AddRefs(mPlayerThread), player); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } @@ -301,8 +299,7 @@ NS_IMETHODIMP nsSound::PlayEventSound(uint32_t aEventId) nsCOMPtr player = new nsSoundPlayer(this, sound); NS_ENSURE_TRUE(player, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = - NS_NewNamedThread("PlayEventSound", getter_AddRefs(mPlayerThread), player); + nsresult rv = NS_NewThread(getter_AddRefs(mPlayerThread), player); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } diff --git a/xpcom/build/MainThreadIOLogger.cpp b/xpcom/build/MainThreadIOLogger.cpp index 95e469899fbd..0ca942cb9f76 100644 --- a/xpcom/build/MainThreadIOLogger.cpp +++ b/xpcom/build/MainThreadIOLogger.cpp @@ -114,7 +114,6 @@ MainThreadIOLoggerImpl::Init() /* static */ void MainThreadIOLoggerImpl::sIOThreadFunc(void* aArg) { - AutoProfilerRegister registerThread("MainThreadIOLogger"); PR_SetCurrentThreadName("MainThreadIOLogger"); MainThreadIOLoggerImpl* obj = static_cast(aArg); obj->IOThreadFunc(); diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index d2f5c88bcb6f..994f71de7d25 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -95,16 +95,13 @@ IncrementalRunnable::SetDeadline(TimeStamp aDeadline) //----------------------------------------------------------------------------- nsresult -NS_NewNamedThread(const nsACString& aName, - nsIThread** aResult, - nsIRunnable* aEvent, - uint32_t aStackSize) +NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) { nsCOMPtr thread; #ifdef MOZILLA_INTERNAL_API nsresult rv = - nsThreadManager::get().nsThreadManager::NewNamedThread(aName, aStackSize, - getter_AddRefs(thread)); + nsThreadManager::get().nsThreadManager::NewThread(0, aStackSize, + getter_AddRefs(thread)); #else nsresult rv; nsCOMPtr mgr = @@ -113,7 +110,7 @@ NS_NewNamedThread(const nsACString& aName, return rv; } - rv = mgr->NewNamedThread(aName, aStackSize, getter_AddRefs(thread)); + rv = mgr->NewThread(0, aStackSize, getter_AddRefs(thread)); #endif if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -131,12 +128,6 @@ NS_NewNamedThread(const nsACString& aName, return NS_OK; } -nsresult -NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) -{ - return NS_NewNamedThread(NS_LITERAL_CSTRING(""), aResult, aEvent, aStackSize); -} - nsresult NS_GetCurrentThread(nsIThread** aResult) { @@ -390,6 +381,56 @@ NS_ProcessNextEvent(nsIThread* aThread, bool aMayWait) return NS_SUCCEEDED(aThread->ProcessNextEvent(aMayWait, &val)) && val; } +#ifndef XPCOM_GLUE_AVOID_NSPR + +namespace { + +class nsNameThreadRunnable final : public nsIRunnable +{ + ~nsNameThreadRunnable() {} + +public: + explicit nsNameThreadRunnable(const nsACString& aName) : mName(aName) {} + + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSIRUNNABLE + +protected: + const nsCString mName; +}; + +NS_IMPL_ISUPPORTS(nsNameThreadRunnable, nsIRunnable) + +NS_IMETHODIMP +nsNameThreadRunnable::Run() +{ + PR_SetCurrentThreadName(mName.BeginReading()); + return NS_OK; +} + +} // namespace + +void +NS_SetThreadName(nsIThread* aThread, const nsACString& aName) +{ + if (!aThread) { + return; + } + + aThread->Dispatch(new nsNameThreadRunnable(aName), + nsIEventTarget::DISPATCH_NORMAL); +} + +#else // !XPCOM_GLUE_AVOID_NSPR + +void +NS_SetThreadName(nsIThread* aThread, const nsACString& aName) +{ + // No NSPR, no love. +} + +#endif + #ifdef MOZILLA_INTERNAL_API nsIThread* NS_GetCurrentThread() @@ -399,13 +440,23 @@ NS_GetCurrentThread() #endif // nsThreadPoolNaming -nsCString -nsThreadPoolNaming::GetNextThreadName(const nsACString& aPoolName) +void +nsThreadPoolNaming::SetThreadPoolName(const nsACString& aPoolName, + nsIThread* aThread) { nsCString name(aPoolName); name.AppendLiteral(" #"); - name.AppendInt(++mCounter, 10); // The counter is declared as atomic - return name; + name.AppendInt(++mCounter, 10); // The counter is declared as volatile + + if (aThread) { + // Set on the target thread + NS_SetThreadName(aThread, name); + } else { + // Set on the current thread +#ifndef XPCOM_GLUE_AVOID_NSPR + PR_SetCurrentThreadName(name.BeginReading()); +#endif + } } // nsAutoLowPriorityIO diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index 82ed1294cdfc..309729a1e99a 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -32,6 +32,24 @@ // These methods are alternatives to the methods on nsIThreadManager, provided // for convenience. +/** + * Set name of the target thread. This operation is asynchronous. + */ +extern void NS_SetThreadName(nsIThread* aThread, const nsACString& aName); + +/** + * Static length version of the above function checking length of the + * name at compile time. + */ +template +inline void +NS_SetThreadName(nsIThread* aThread, const char (&aName)[LEN]) +{ + static_assert(LEN <= 16, + "Thread name must be no more than 16 characters"); + NS_SetThreadName(aThread, nsDependentCString(aName)); +} + /** * Create a new thread, and optionally provide an initial event for the thread. * @@ -53,12 +71,6 @@ NS_NewThread(nsIThread** aResult, /** * Creates a named thread, otherwise the same as NS_NewThread */ -extern nsresult -NS_NewNamedThread(const nsACString& aName, - nsIThread** aResult, - nsIRunnable* aInitialEvent = nullptr, - uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE); - template inline nsresult NS_NewNamedThread(const char (&aName)[LEN], @@ -66,10 +78,21 @@ NS_NewNamedThread(const char (&aName)[LEN], nsIRunnable* aInitialEvent = nullptr, uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) { - static_assert(LEN <= 16, - "Thread name must be no more than 16 characters"); - return NS_NewNamedThread(nsDependentCString(aName, LEN - 1), - aResult, aInitialEvent, aStackSize); + // Hold a ref while dispatching the initial event to match NS_NewThread() + nsCOMPtr thread; + nsresult rv = NS_NewThread(getter_AddRefs(thread), nullptr, aStackSize); + if (NS_WARN_IF(NS_FAILED(rv))) { + return rv; + } + NS_SetThreadName(thread, aName); + if (aInitialEvent) { + rv = thread->Dispatch(aInitialEvent, NS_DISPATCH_NORMAL); + NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Initial event dispatch failed"); + } + + *aResult = nullptr; + thread.swap(*aResult); + return rv; } /** @@ -1003,15 +1026,12 @@ public: nsThreadPoolNaming() : mCounter(0) {} /** - * Returns a thread name as " #" and increments the counter. + * Creates and sets next thread name as " #" + * on the specified thread. If no thread is specified (aThread + * is null) then the name is synchronously set on the current thread. */ - nsCString GetNextThreadName(const nsACString& aPoolName); - - template - nsCString GetNextThreadName(const char (&aPoolName)[LEN]) - { - return GetNextThreadName(nsDependentCString(aPoolName, LEN - 1)); - } + void SetThreadPoolName(const nsACString& aPoolName, + nsIThread* aThread = nullptr); private: mozilla::Atomic mCounter; diff --git a/xpcom/tests/gtest/TestPipes.cpp b/xpcom/tests/gtest/TestPipes.cpp index 5bf31c94197e..87b923008258 100644 --- a/xpcom/tests/gtest/TestPipes.cpp +++ b/xpcom/tests/gtest/TestPipes.cpp @@ -107,7 +107,7 @@ TestPipe(nsIInputStream* in, nsIOutputStream* out) nsresult rv; nsCOMPtr thread; - rv = NS_NewNamedThread("TestPipe", getter_AddRefs(thread), receiver); + rv = NS_NewThread(getter_AddRefs(thread), receiver); if (NS_FAILED(rv)) return rv; uint32_t total = 0; @@ -225,8 +225,7 @@ TestShortWrites(nsIInputStream* in, nsIOutputStream* out) nsresult rv; nsCOMPtr thread; - rv = NS_NewNamedThread("TestShortWrites", getter_AddRefs(thread), - receiver); + rv = NS_NewThread(getter_AddRefs(thread), receiver); if (NS_FAILED(rv)) return rv; uint32_t total = 0; @@ -331,15 +330,14 @@ TEST(Pipes, ChainedPipes) if (pump == nullptr) return; nsCOMPtr thread; - rv = NS_NewNamedThread("ChainedPipePump", getter_AddRefs(thread), pump); + rv = NS_NewThread(getter_AddRefs(thread), pump); if (NS_FAILED(rv)) return; RefPtr receiver = new nsReceiver(in2); if (receiver == nullptr) return; nsCOMPtr receiverThread; - rv = NS_NewNamedThread("ChainedPipeRecv", getter_AddRefs(receiverThread), - receiver); + rv = NS_NewThread(getter_AddRefs(receiverThread), receiver); if (NS_FAILED(rv)) return; uint32_t total = 0; diff --git a/xpcom/tests/gtest/TestRacingServiceManager.cpp b/xpcom/tests/gtest/TestRacingServiceManager.cpp index 1309083ed853..b0638db02f48 100644 --- a/xpcom/tests/gtest/TestRacingServiceManager.cpp +++ b/xpcom/tests/gtest/TestRacingServiceManager.cpp @@ -255,7 +255,7 @@ TEST(RacingServiceManager, Test) // Run the classID test nsCOMPtr newThread; - rv = NS_NewNamedThread("RacingServMan", getter_AddRefs(newThread), runnable); + rv = NS_NewThread(getter_AddRefs(newThread), runnable); ASSERT_TRUE(NS_SUCCEEDED(rv)); { diff --git a/xpcom/tests/gtest/TestThreads.cpp b/xpcom/tests/gtest/TestThreads.cpp index 4d47f2649415..4f6055dce9b9 100644 --- a/xpcom/tests/gtest/TestThreads.cpp +++ b/xpcom/tests/gtest/TestThreads.cpp @@ -49,7 +49,7 @@ TEST(Threads, Main) EXPECT_TRUE(event); nsCOMPtr runner; - rv = NS_NewNamedThread("TestThreadsMain", getter_AddRefs(runner), event); + rv = NS_NewThread(getter_AddRefs(runner), event); EXPECT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr thread; @@ -112,8 +112,7 @@ TEST(Threads, Stress) for (k = 0; k < threads; k++) { nsCOMPtr t; - nsresult rv = NS_NewNamedThread("StressRunner", getter_AddRefs(t), - new nsStressRunner(k)); + nsresult rv = NS_NewThread(getter_AddRefs(t), new nsStressRunner(k)); EXPECT_TRUE(NS_SUCCEEDED(rv)); NS_ADDREF(array[k] = t); } @@ -170,8 +169,7 @@ public: { mozilla::MonitorAutoLock lock(*gBeginAsyncShutdownMonitor); - rv = NS_NewNamedThread("AsyncShutdownPr", getter_AddRefs(t), - new AsyncShutdownPreparer()); + rv = NS_NewThread(getter_AddRefs(t), new AsyncShutdownPreparer()); EXPECT_TRUE(NS_SUCCEEDED(rv)); lock.Wait(); @@ -223,8 +221,7 @@ TEST(Threads, AsyncShutdown) { mozilla::MonitorAutoLock lock(*gAsyncShutdownReadyMonitor); - rv = NS_NewNamedThread("AsyncShutdownWt", getter_AddRefs(t), - new AsyncShutdownWaiter()); + rv = NS_NewThread(getter_AddRefs(t), new AsyncShutdownWaiter()); EXPECT_TRUE(NS_SUCCEEDED(rv)); lock.Wait(); diff --git a/xpcom/tests/gtest/TestTimers.cpp b/xpcom/tests/gtest/TestTimers.cpp index 524e1e8b3f7b..fe7520ab1018 100644 --- a/xpcom/tests/gtest/TestTimers.cpp +++ b/xpcom/tests/gtest/TestTimers.cpp @@ -31,7 +31,7 @@ class AutoTestThread public: AutoTestThread() { nsCOMPtr newThread; - nsresult rv = NS_NewNamedThread("AutoTestThread", getter_AddRefs(newThread)); + nsresult rv = NS_NewThread(getter_AddRefs(newThread)); if (NS_FAILED(rv)) return; diff --git a/xpcom/threads/BackgroundHangMonitor.cpp b/xpcom/threads/BackgroundHangMonitor.cpp index cc16973752fa..ac65d9f37162 100644 --- a/xpcom/threads/BackgroundHangMonitor.cpp +++ b/xpcom/threads/BackgroundHangMonitor.cpp @@ -22,7 +22,6 @@ #include "nsIObserver.h" #include "mozilla/Services.h" #include "nsXULAppAPI.h" -#include "GeckoProfiler.h" #include @@ -55,7 +54,6 @@ private: // Background hang monitor thread function static void MonitorThread(void* aData) { - AutoProfilerRegister registerThread("BgHangMonitor"); PR_SetCurrentThreadName("BgHangManager"); /* We do not hold a reference to BackgroundHangManager here diff --git a/xpcom/threads/HangMonitor.cpp b/xpcom/threads/HangMonitor.cpp index ab402eb68f58..cde8052f33c4 100644 --- a/xpcom/threads/HangMonitor.cpp +++ b/xpcom/threads/HangMonitor.cpp @@ -21,7 +21,6 @@ #endif #include "nsThreadUtils.h" #include "nsXULAppAPI.h" -#include "GeckoProfiler.h" #ifdef MOZ_CRASHREPORTER #include "nsExceptionHandler.h" @@ -210,7 +209,6 @@ GetChromeHangReport(Telemetry::ProcessedStack& aStack, void ThreadMain(void*) { - AutoProfilerRegister registerThread("Hang Monitor"); PR_SetCurrentThreadName("Hang Monitor"); MonitorAutoLock lock(*gMonitor); diff --git a/xpcom/threads/LazyIdleThread.cpp b/xpcom/threads/LazyIdleThread.cpp index be3acfa61fc5..527cc681962f 100644 --- a/xpcom/threads/LazyIdleThread.cpp +++ b/xpcom/threads/LazyIdleThread.cpp @@ -169,7 +169,7 @@ LazyIdleThread::EnsureThread() return NS_ERROR_UNEXPECTED; } - rv = NS_NewNamedThread("Lazy Idle", getter_AddRefs(mThread), runnable); + rv = NS_NewThread(getter_AddRefs(mThread), runnable); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -180,6 +180,11 @@ LazyIdleThread::EnsureThread() void LazyIdleThread::InitThread() { + char aLocal; + profiler_register_thread(mName.get(), &aLocal); + + PR_SetCurrentThreadName(mName.get()); + // Happens on mThread but mThread may not be set yet... nsCOMPtr thread(do_QueryInterface(NS_GetCurrentThread())); @@ -206,6 +211,8 @@ LazyIdleThread::CleanupThread() MOZ_ASSERT(!mThreadIsShuttingDown, "Shouldn't be true ever!"); mThreadIsShuttingDown = true; } + + profiler_unregister_thread(); } void diff --git a/xpcom/threads/TimerThread.cpp b/xpcom/threads/TimerThread.cpp index da4bc6edba26..8536f0395ab7 100644 --- a/xpcom/threads/TimerThread.cpp +++ b/xpcom/threads/TimerThread.cpp @@ -323,8 +323,7 @@ TimerThread::Init() if (mInitInProgress.exchange(true) == false) { // We hold on to mThread to keep the thread alive. - nsresult rv = - NS_NewNamedThread("Timer Thread", getter_AddRefs(mThread), this); + nsresult rv = NS_NewThread(getter_AddRefs(mThread), this); if (NS_FAILED(rv)) { mThread = nullptr; } else { diff --git a/xpcom/threads/nsIThreadManager.idl b/xpcom/threads/nsIThreadManager.idl index fa0f037c2712..9b4fc126f9b3 100644 --- a/xpcom/threads/nsIThreadManager.idl +++ b/xpcom/threads/nsIThreadManager.idl @@ -35,20 +35,6 @@ interface nsIThreadManager : nsISupports */ nsIThread newThread(in unsigned long creationFlags, [optional] in unsigned long stackSize); - /** - * Create a new thread (a global, user PRThread) with the specified name. - * - * @param name - * The name of the thread. Passing an empty name is equivalent to - * calling newThread(0, stackSize), i.e. the thread will not be named. - * @param stackSize - * Number of bytes to reserve for the thread's stack. - * - * @returns - * The newly created nsIThread object. - */ - [noscript] nsIThread newNamedThread(in ACString name, [optional] in unsigned long stackSize); - /** * Get the nsIThread object (if any) corresponding to the given PRThread. * This method returns null if there is no corresponding nsIThread. diff --git a/xpcom/threads/nsProcessCommon.cpp b/xpcom/threads/nsProcessCommon.cpp index 37071b58c95f..709865a09d8b 100644 --- a/xpcom/threads/nsProcessCommon.cpp +++ b/xpcom/threads/nsProcessCommon.cpp @@ -25,7 +25,6 @@ #include "nsIObserverService.h" #include "nsXULAppAPI.h" #include "mozilla/Services.h" -#include "GeckoProfiler.h" #include @@ -236,13 +235,10 @@ assembleCmdLine(char* const* aArgv, wchar_t** aWideCmdLine, UINT aCodePage) void nsProcess::Monitor(void* aArg) { - char stackBaseGuess; - RefPtr process = dont_AddRef(static_cast(aArg)); if (!process->mBlocking) { PR_SetCurrentThreadName("RunProcess"); - profiler_register_thread("RunProcess", &stackBaseGuess); } #if defined(PROCESSMODEL_WINAPI) @@ -308,10 +304,6 @@ nsProcess::Monitor(void* aArg) } else { NS_DispatchToMainThread(NewRunnableMethod(process, &nsProcess::ProcessComplete)); } - - if (!process->mBlocking) { - profiler_unregister_thread(); - } } void diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp index 119e0c788471..6c0f898240ae 100644 --- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -38,7 +38,6 @@ #include "nsIIncrementalRunnable.h" #include "nsThreadSyncDispatch.h" #include "LeakRefPtr.h" -#include "GeckoProfiler.h" #ifdef MOZ_CRASHREPORTER #include "nsServiceManagerUtils.h" @@ -433,34 +432,15 @@ SetupCurrentThreadForChaosMode() } } -namespace { - -struct ThreadInitData { - nsThread* thread; - const nsACString& name; -}; - -} - /*static*/ void nsThread::ThreadFunc(void* aArg) { using mozilla::ipc::BackgroundChild; - char stackTop; - - ThreadInitData* initData = static_cast(aArg); - nsThread* self = initData->thread; // strong reference - + nsThread* self = static_cast(aArg); // strong reference self->mThread = PR_GetCurrentThread(); SetupCurrentThreadForChaosMode(); - if (initData->name.Length() > 0) { - PR_SetCurrentThreadName(initData->name.BeginReading()); - - profiler_register_thread(initData->name.BeginReading(), &stackTop); - } - // Inform the ThreadManager nsThreadManager::get().RegisterCurrentThread(*self); @@ -475,9 +455,6 @@ nsThread::ThreadFunc(void* aArg) return; } } - - initData = nullptr; // clear before unblocking nsThread::Init - event->Run(); // unblocks nsThread::Init event = nullptr; @@ -524,8 +501,6 @@ nsThread::ThreadFunc(void* aArg) // Inform the threadmanager that this thread is going away nsThreadManager::get().UnregisterCurrentThread(*self); - profiler_unregister_thread(); - // Dispatch shutdown ACK NotNull context = WrapNotNull(self->mShutdownContext); @@ -653,7 +628,7 @@ nsThread::~nsThread() } nsresult -nsThread::Init(const nsACString& aName) +nsThread::Init() { // spawn thread and wait until it is fully setup RefPtr startup = new nsThreadStartupEvent(); @@ -664,10 +639,8 @@ nsThread::Init(const nsACString& aName) mShutdownRequired = true; - ThreadInitData initData = { this, aName }; - // ThreadFunc is responsible for setting mThread - if (!PR_CreateThread(PR_USER_THREAD, ThreadFunc, &initData, + if (!PR_CreateThread(PR_USER_THREAD, ThreadFunc, this, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, mStackSize)) { NS_RELEASE_THIS(); diff --git a/xpcom/threads/nsThread.h b/xpcom/threads/nsThread.h index fd8209b0b5c4..836123747aad 100644 --- a/xpcom/threads/nsThread.h +++ b/xpcom/threads/nsThread.h @@ -48,8 +48,8 @@ public: nsThread(MainThreadFlag aMainThread, uint32_t aStackSize); - // Initialize this as a wrapper for a new PRThread, and optionally give it a name. - nsresult Init(const nsACString& aName = NS_LITERAL_CSTRING("")); + // Initialize this as a wrapper for a new PRThread. + nsresult Init(); // Initialize this as a wrapper for the current PRThread. nsresult InitCurrentThread(); diff --git a/xpcom/threads/nsThreadManager.cpp b/xpcom/threads/nsThreadManager.cpp index 217e557a8274..d1eb84b8f84c 100644 --- a/xpcom/threads/nsThreadManager.cpp +++ b/xpcom/threads/nsThreadManager.cpp @@ -248,14 +248,6 @@ NS_IMETHODIMP nsThreadManager::NewThread(uint32_t aCreationFlags, uint32_t aStackSize, nsIThread** aResult) -{ - return NewNamedThread(NS_LITERAL_CSTRING(""), aStackSize, aResult); -} - -NS_IMETHODIMP -nsThreadManager::NewNamedThread(const nsACString& aName, - uint32_t aStackSize, - nsIThread** aResult) { // Note: can be called from arbitrary threads @@ -265,7 +257,7 @@ nsThreadManager::NewNamedThread(const nsACString& aName, } RefPtr thr = new nsThread(nsThread::NOT_MAIN_THREAD, aStackSize); - nsresult rv = thr->Init(aName); // Note: blocks until the new thread has been set up + nsresult rv = thr->Init(); // Note: blocks until the new thread has been set up if (NS_FAILED(rv)) { return rv; } diff --git a/xpcom/threads/nsThreadPool.cpp b/xpcom/threads/nsThreadPool.cpp index f1d849ed1a85..241fad39dcc2 100644 --- a/xpcom/threads/nsThreadPool.cpp +++ b/xpcom/threads/nsThreadPool.cpp @@ -104,9 +104,8 @@ nsThreadPool::PutEvent(already_AddRefed aEvent, uint32_t aFlags) } nsCOMPtr thread; - nsresult rv = NS_NewNamedThread(mThreadNaming.GetNextThreadName(mName), - getter_AddRefs(thread), nullptr, stackSize); - if (NS_WARN_IF(NS_FAILED(rv))) { + nsThreadManager::get().NewThread(0, stackSize, getter_AddRefs(thread)); + if (NS_WARN_IF(!thread)) { return NS_ERROR_UNEXPECTED; } @@ -153,6 +152,8 @@ nsThreadPool::ShutdownThread(nsIThread* aThread) NS_IMETHODIMP nsThreadPool::Run() { + mThreadNaming.SetThreadPoolName(mName); + LOG(("THRD-P(%p) enter %s\n", this, mName.BeginReading())); nsCOMPtr current; From 0f9ff65fceba1a42a3a3359e5d7fc6f23c027ad4 Mon Sep 17 00:00:00 2001 From: Xidorn Quan Date: Fri, 30 Dec 2016 18:23:26 +1100 Subject: [PATCH 036/229] Bug 1322843 part 1 - Add Reverse method to nsTArray. r=froydnj MozReview-Commit-ID: 8VNEFzHn4dC --HG-- extra : rebase_source : 4f1ef1bca974045168d6e33e2f079ae1f7b44be9 --- xpcom/glue/nsTArray.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/xpcom/glue/nsTArray.h b/xpcom/glue/nsTArray.h index 572b4e50fc9a..ba9a254e9942 100644 --- a/xpcom/glue/nsTArray.h +++ b/xpcom/glue/nsTArray.h @@ -2017,6 +2017,16 @@ public: // 'operator<' is defined for elem_type. void Sort() { Sort(nsDefaultComparator()); } + // This method reverses the array in place. + void Reverse() + { + elem_type* elements = Elements(); + const size_type len = Length(); + for (index_type i = 0, iend = len / 2; i < iend; ++i) { + mozilla::Swap(elements[i], elements[len - i - 1]); + } + } + protected: using base_type::Hdr; using base_type::ShrinkCapacity; From 0fe4f86e06899264ac00334a44f7f87d8ad49c11 Mon Sep 17 00:00:00 2001 From: Xidorn Quan Date: Thu, 22 Dec 2016 18:30:38 +1100 Subject: [PATCH 037/229] Bug 1322843 part 2 - Conditionally keep some floats in InlinePrefISizeData::ForceBreak. r=dbaron This patch makes ForceBreak() partially clear floats according to the break type of the coming block. MozReview-Commit-ID: 71Gl9lBoTJ5 --HG-- extra : rebase_source : 5ca01565f607241df0c63a7cd64c35ac7ff7648f --- layout/generic/nsBlockFrame.cpp | 7 ++++- layout/generic/nsFrame.cpp | 56 ++++++++++++++++++++++++++++++--- layout/generic/nsIFrame.h | 20 +++++++++++- 3 files changed, 76 insertions(+), 7 deletions(-) diff --git a/layout/generic/nsBlockFrame.cpp b/layout/generic/nsBlockFrame.cpp index 78809fe8b65f..fd23f8b7f517 100644 --- a/layout/generic/nsBlockFrame.cpp +++ b/layout/generic/nsBlockFrame.cpp @@ -838,9 +838,14 @@ nsBlockFrame::GetPrefISize(nsRenderingContext *aRenderingContext) AutoNoisyIndenter lineindent(gNoisyIntrinsic); #endif if (line->IsBlock()) { + StyleClear breakType; if (!data.mLineIsEmpty || BlockCanIntersectFloats(line->mFirstChild)) { - data.ForceBreak(); + breakType = StyleClear::Both; + } else { + breakType = line->mFirstChild-> + StyleDisplay()->PhysicalBreakType(data.mLineContainerWM); } + data.ForceBreak(breakType); data.mCurrentLine = nsLayoutUtils::IntrinsicForContainer(aRenderingContext, line->mFirstChild, nsLayoutUtils::PREF_ISIZE); data.ForceBreak(); diff --git a/layout/generic/nsFrame.cpp b/layout/generic/nsFrame.cpp index f78511d66aff..78ac40a6108b 100644 --- a/layout/generic/nsFrame.cpp +++ b/layout/generic/nsFrame.cpp @@ -4512,9 +4512,17 @@ nsIFrame::InlineMinISizeData::OptionallyBreak(nscoord aHyphenWidth) } void -nsIFrame::InlinePrefISizeData::ForceBreak() +nsIFrame::InlinePrefISizeData::ForceBreak(StyleClear aBreakType) { - if (mFloats.Length() != 0) { + MOZ_ASSERT(aBreakType == StyleClear::None || + aBreakType == StyleClear::Both || + aBreakType == StyleClear::Left || + aBreakType == StyleClear::Right, + "Must be a physical break type"); + + // If this force break is not clearing any float, we can leave all the + // floats to the next force break. + if (mFloats.Length() != 0 && aBreakType != StyleClear::None) { // preferred widths accumulated for floats that have already // been cleared past nscoord floats_done = 0, @@ -4522,11 +4530,12 @@ nsIFrame::InlinePrefISizeData::ForceBreak() // been cleared past floats_cur_left = 0, floats_cur_right = 0; + const WritingMode wm = mLineContainerWM; for (uint32_t i = 0, i_end = mFloats.Length(); i != i_end; ++i) { const FloatInfo& floatInfo = mFloats[i]; const nsStyleDisplay* floatDisp = floatInfo.Frame()->StyleDisplay(); - StyleClear breakType = floatDisp->PhysicalBreakType(mLineContainerWM); + StyleClear breakType = floatDisp->PhysicalBreakType(wm); if (breakType == StyleClear::Left || breakType == StyleClear::Right || breakType == StyleClear::Both) { @@ -4543,7 +4552,7 @@ nsIFrame::InlinePrefISizeData::ForceBreak() } } - StyleFloat floatStyle = floatDisp->PhysicalFloats(mLineContainerWM); + StyleFloat floatStyle = floatDisp->PhysicalFloats(wm); nscoord& floats_cur = floatStyle == StyleFloat::Left ? floats_cur_left : floats_cur_right; nscoord floatWidth = floatInfo.Width(); @@ -4560,7 +4569,44 @@ nsIFrame::InlinePrefISizeData::ForceBreak() mCurrentLine = NSCoordSaturatingAdd(mCurrentLine, floats_done); - mFloats.Clear(); + if (aBreakType == StyleClear::Both) { + mFloats.Clear(); + } else { + // If the break type does not clear all floats, it means there may + // be some floats whose isize should contribute to the intrinsic + // isize of the next line. The code here scans the current mFloats + // and keeps floats which are not cleared by this break. Note that + // floats may be cleared directly or indirectly. See below. + nsTArray newFloats; + MOZ_ASSERT(aBreakType == StyleClear::Left || + aBreakType == StyleClear::Right, + "Other values should have been handled in other branches"); + StyleFloat clearFloatType = + aBreakType == StyleClear::Left ? StyleFloat::Left : StyleFloat::Right; + // Iterate the array in reverse so that we can stop when there are + // no longer any floats we need to keep. See below. + for (FloatInfo& floatInfo : Reversed(mFloats)) { + const nsStyleDisplay* floatDisp = floatInfo.Frame()->StyleDisplay(); + if (floatDisp->PhysicalFloats(wm) != clearFloatType) { + newFloats.AppendElement(floatInfo); + } else { + // This is a float on the side that this break directly clears + // which means we're not keeping it in mFloats. However, if + // this float clears floats on the opposite side (via a value + // of either 'both' or one of 'left'/'right'), any remaining + // (earlier) floats on that side would be indirectly cleared + // as well. Thus, we should break out of this loop and stop + // considering earlier floats to be kept in mFloats. + StyleClear floatBreakType = floatDisp->PhysicalBreakType(wm); + if (floatBreakType != aBreakType && + floatBreakType != StyleClear::None) { + break; + } + } + } + newFloats.Reverse(); + mFloats = Move(newFloats); + } } mCurrentLine = diff --git a/layout/generic/nsIFrame.h b/layout/generic/nsIFrame.h index 383e684f42bc..7d1efbaae12c 100644 --- a/layout/generic/nsIFrame.h +++ b/layout/generic/nsIFrame.h @@ -2020,11 +2020,29 @@ public: }; struct InlinePrefISizeData : public InlineIntrinsicISizeData { + typedef mozilla::StyleClear StyleClear; + InlinePrefISizeData() : mLineIsEmpty(true) {} - void ForceBreak(); + /** + * Finish the current line and start a new line. + * + * @param aBreakType controls whether isize of floats are considered + * and what floats are kept for the next line: + * * |None| skips handling floats, which means no floats are + * removed, and isizes of floats are not considered either. + * * |Both| takes floats into consideration when computing isize + * of the current line, and removes all floats after that. + * * |Left| and |Right| do the same as |Both| except that they only + * remove floats on the given side, and any floats on the other + * side that are prior to a float on the given side that has a + * 'clear' property that clears them. + * All other values of StyleClear must be converted to the four + * physical values above for this function. + */ + void ForceBreak(StyleClear aBreakType = StyleClear::Both); // The default implementation for nsIFrame::AddInlinePrefISize. void DefaultAddInlinePrefISize(nscoord aISize); From c7690fb4ef3d485e0a88634afeddcb675cf0ad4f Mon Sep 17 00:00:00 2001 From: Xidorn Quan Date: Thu, 22 Dec 2016 18:32:08 +1100 Subject: [PATCH 038/229] Bug 1322843 part 3 - Add reftests for this bug. r=dbaron Test 1322843-1[a-d] fail before part 2, while the other two tests fail before patch for bug 1260031. MozReview-Commit-ID: 9QfBvtwQOvP --HG-- extra : rebase_source : d42b2ace21fb2a9e896f89f97b01c2e0584c7313 --- layout/reftests/floats/1322843-1-ref.html | 10 ++++++ layout/reftests/floats/1322843-1a.html | 33 ++++++++++++++++++ layout/reftests/floats/1322843-1b.html | 26 ++++++++++++++ layout/reftests/floats/1322843-1c.html | 26 ++++++++++++++ layout/reftests/floats/1322843-1d.html | 41 +++++++++++++++++++++++ layout/reftests/floats/1322843-1e.html | 26 ++++++++++++++ layout/reftests/floats/1322843-1f.html | 34 +++++++++++++++++++ layout/reftests/floats/reftest.list | 6 ++++ 8 files changed, 202 insertions(+) create mode 100644 layout/reftests/floats/1322843-1-ref.html create mode 100644 layout/reftests/floats/1322843-1a.html create mode 100644 layout/reftests/floats/1322843-1b.html create mode 100644 layout/reftests/floats/1322843-1c.html create mode 100644 layout/reftests/floats/1322843-1d.html create mode 100644 layout/reftests/floats/1322843-1e.html create mode 100644 layout/reftests/floats/1322843-1f.html diff --git a/layout/reftests/floats/1322843-1-ref.html b/layout/reftests/floats/1322843-1-ref.html new file mode 100644 index 000000000000..f3b15eb9e024 --- /dev/null +++ b/layout/reftests/floats/1322843-1-ref.html @@ -0,0 +1,10 @@ + +Bug 1322843 - Intrinsic width with float + +
diff --git a/layout/reftests/floats/1322843-1a.html b/layout/reftests/floats/1322843-1a.html new file mode 100644 index 000000000000..c2f7ba285787 --- /dev/null +++ b/layout/reftests/floats/1322843-1a.html @@ -0,0 +1,33 @@ + +Bug 1322843 - Intrinsic width with float + +
+
+
+
+
diff --git a/layout/reftests/floats/1322843-1b.html b/layout/reftests/floats/1322843-1b.html new file mode 100644 index 000000000000..6ab8e1b42a22 --- /dev/null +++ b/layout/reftests/floats/1322843-1b.html @@ -0,0 +1,26 @@ + +Bug 1322843 - Intrinsic width with float + +
+
+
+
diff --git a/layout/reftests/floats/1322843-1c.html b/layout/reftests/floats/1322843-1c.html new file mode 100644 index 000000000000..2625f847df65 --- /dev/null +++ b/layout/reftests/floats/1322843-1c.html @@ -0,0 +1,26 @@ + +Bug 1322843 - Intrinsic width with float + +
+
+
+
diff --git a/layout/reftests/floats/1322843-1d.html b/layout/reftests/floats/1322843-1d.html new file mode 100644 index 000000000000..e8fb14ce46b3 --- /dev/null +++ b/layout/reftests/floats/1322843-1d.html @@ -0,0 +1,41 @@ + +Bug 1322843 - Intrinsic width with float + +
+
+
+
+
+
diff --git a/layout/reftests/floats/1322843-1e.html b/layout/reftests/floats/1322843-1e.html new file mode 100644 index 000000000000..493ed173496a --- /dev/null +++ b/layout/reftests/floats/1322843-1e.html @@ -0,0 +1,26 @@ + +Bug 1322843 - Intrinsic width with float + +
+
+
+
diff --git a/layout/reftests/floats/1322843-1f.html b/layout/reftests/floats/1322843-1f.html new file mode 100644 index 000000000000..49e9189b01a1 --- /dev/null +++ b/layout/reftests/floats/1322843-1f.html @@ -0,0 +1,34 @@ + +Bug 1322843 - Intrinsic width with float + +
+
+
+
+
diff --git a/layout/reftests/floats/reftest.list b/layout/reftests/floats/reftest.list index 948fea3142b9..3ffe35c6857f 100644 --- a/layout/reftests/floats/reftest.list +++ b/layout/reftests/floats/reftest.list @@ -26,6 +26,12 @@ fails == 345369-2.html 345369-2-ref.html == 1260031-1.html?overflow:hidden 1260031-1-ref.html == 1291110-1.html 1291110-1-ref.html == 1291110-2.html 1291110-2-ref.html +== 1322843-1a.html 1322843-1-ref.html +== 1322843-1b.html 1322843-1-ref.html +== 1322843-1c.html 1322843-1-ref.html +== 1322843-1d.html 1322843-1-ref.html +== 1322843-1e.html 1322843-1-ref.html +== 1322843-1f.html 1322843-1-ref.html == float-in-rtl-1a.html float-in-rtl-1-ref.html fuzzy-if(skiaContent,1,27000) == float-in-rtl-1b.html float-in-rtl-1-ref.html fuzzy-if(skiaContent,1,27000) == float-in-rtl-1c.html float-in-rtl-1-ref.html From 2ca25c39f64e2dd326f08fe459b2dc69071a7a0e Mon Sep 17 00:00:00 2001 From: "Nils Ohlmeier [:drno]" Date: Thu, 17 Nov 2016 23:16:33 -0800 Subject: [PATCH 039/229] Bug 1318180: turn network offline events into ice disconnected event. r=bwc,jib MozReview-Commit-ID: Kqbicl2goL2 --HG-- extra : rebase_source : 4ed7d1364af8bd1575e2ced1bd8512405e0dd669 --- dom/media/PeerConnection.js | 56 +++++------- media/mtransport/nricectx.cpp | 10 +++ media/mtransport/nricectx.h | 3 + media/mtransport/test/ice_unittest.cpp | 63 +++++++++++++ .../third_party/nICEr/src/ice/ice_component.c | 37 +++++--- .../third_party/nICEr/src/ice/ice_component.h | 3 + .../nICEr/src/ice/ice_media_stream.c | 89 +++++++++++++++++-- .../nICEr/src/ice/ice_media_stream.h | 11 ++- .../third_party/nICEr/src/ice/ice_peer_ctx.c | 36 +++++++- .../third_party/nICEr/src/ice/ice_peer_ctx.h | 2 + .../src/peerconnection/PeerConnectionCtx.cpp | 58 +++++++++--- .../src/peerconnection/PeerConnectionCtx.h | 6 +- .../src/peerconnection/PeerConnectionImpl.cpp | 11 ++- .../src/peerconnection/PeerConnectionImpl.h | 2 + .../peerconnection/PeerConnectionMedia.cpp | 16 ++++ .../src/peerconnection/PeerConnectionMedia.h | 4 + 16 files changed, 337 insertions(+), 70 deletions(-) diff --git a/dom/media/PeerConnection.js b/dom/media/PeerConnection.js index 52a242b5d4a0..9f4bee8fc7ef 100644 --- a/dom/media/PeerConnection.js +++ b/dom/media/PeerConnection.js @@ -182,19 +182,11 @@ GlobalPCList.prototype = { } } else if (topic == "profile-change-net-teardown" || topic == "network:offline-about-to-go-offline") { - // Delete all peerconnections on shutdown - mostly synchronously (we - // need them to be done deleting transports and streams before we - // return)! All socket operations must be queued to STS thread - // before we return to here. - // Also kill them if "Work Offline" is selected - more can be created - // while offline, but attempts to connect them should fail. - for (let winId in this._list) { - cleanupWinId(this._list, winId); - } + // As Necko doesn't prevent us from accessing the network we still need to + // monitor the network offline/online state here. See bug 1326483 this._networkdown = true; } else if (topic == "network:offline-status-changed") { if (data == "offline") { - // this._list shold be empty here this._networkdown = true; } else if (data == "online") { this._networkdown = false; @@ -1211,9 +1203,11 @@ RTCPeerConnection.prototype = { }, changeIceConnectionState: function(state) { - this._iceConnectionState = state; - _globalPCList.notifyLifecycleObservers(this, "iceconnectionstatechange"); - this.dispatchEvent(new this._win.Event("iceconnectionstatechange")); + if (state != this._iceConnectionState) { + this._iceConnectionState = state; + _globalPCList.notifyLifecycleObservers(this, "iceconnectionstatechange"); + this.dispatchEvent(new this._win.Event("iceconnectionstatechange")); + } }, getStats: function(selector, onSucc, onErr) { @@ -1370,35 +1364,25 @@ PeerConnectionObserver.prototype = { // // iceConnectionState: // ------------------- - // new The ICE Agent is gathering addresses and/or waiting for - // remote candidates to be supplied. + // new Any of the RTCIceTransports are in the new state and none + // of them are in the checking, failed or disconnected state. // - // checking The ICE Agent has received remote candidates on at least - // one component, and is checking candidate pairs but has not - // yet found a connection. In addition to checking, it may - // also still be gathering. + // checking Any of the RTCIceTransports are in the checking state and + // none of them are in the failed or disconnected state. // - // connected The ICE Agent has found a usable connection for all - // components but is still checking other candidate pairs to - // see if there is a better connection. It may also still be - // gathering. - // - // completed The ICE Agent has finished gathering and checking and found - // a connection for all components. Open issue: it is not - // clear how the non controlling ICE side knows it is in the + // connected All RTCIceTransports are in the connected, completed or + // closed state and at least one of them is in the connected // state. // - // failed The ICE Agent is finished checking all candidate pairs and - // failed to find a connection for at least one component. - // Connections may have been found for some components. + // completed All RTCIceTransports are in the completed or closed state + // and at least one of them is in the completed state. // - // disconnected Liveness checks have failed for one or more components. - // This is more aggressive than failed, and may trigger - // intermittently (and resolve itself without action) on a - // flaky network. + // failed Any of the RTCIceTransports are in the failed state. // - // closed The ICE Agent has shut down and is no longer responding to - // STUN requests. + // disconnected Any of the RTCIceTransports are in the disconnected state + // and none of them are in the failed state. + // + // closed All of the RTCIceTransports are in the closed state. handleIceConnectionStateChange: function(iceConnectionState) { let pc = this._dompc; diff --git a/media/mtransport/nricectx.cpp b/media/mtransport/nricectx.cpp index 60147fea1807..adc712414416 100644 --- a/media/mtransport/nricectx.cpp +++ b/media/mtransport/nricectx.cpp @@ -971,6 +971,16 @@ nsresult NrIceCtx::Finalize() { return NS_OK; } +void NrIceCtx::UpdateNetworkState(bool online) { + MOZ_MTLOG(ML_INFO, "NrIceCtx(" << name_ << "): updating network state to " << + (online ? "online" : "offline")); + if (online) { + nr_ice_peer_ctx_refresh_consent_all_streams(peer_); + } else { + nr_ice_peer_ctx_disconnect_all_streams(peer_); + } +} + void NrIceCtx::SetConnectionState(ConnectionState state) { if (state == connection_state_) return; diff --git a/media/mtransport/nricectx.h b/media/mtransport/nricectx.h index e6a8a34b567e..a25ff62ba7eb 100644 --- a/media/mtransport/nricectx.h +++ b/media/mtransport/nricectx.h @@ -314,6 +314,9 @@ class NrIceCtx { // Start checking nsresult StartChecks(); + // Notify that the network has gone online/offline + void UpdateNetworkState(bool online); + // Finalize the ICE negotiation. I.e., there will be no // more forking. nsresult Finalize(); diff --git a/media/mtransport/test/ice_unittest.cpp b/media/mtransport/test/ice_unittest.cpp index 0b3216353094..cdcec82ec2c6 100644 --- a/media/mtransport/test/ice_unittest.cpp +++ b/media/mtransport/test/ice_unittest.cpp @@ -1366,6 +1366,26 @@ class IceTestPeer : public sigslot::has_slots<> { NS_DISPATCH_SYNC); } + void ChangeNetworkState_s(bool online) { + ice_ctx_->ctx()->UpdateNetworkState(online); + } + + void ChangeNetworkStateToOffline() { + test_utils_->sts_target()->Dispatch( + WrapRunnable(this, + &IceTestPeer::ChangeNetworkState_s, + false), + NS_DISPATCH_SYNC); + } + + void ChangeNetworkStateToOnline() { + test_utils_->sts_target()->Dispatch( + WrapRunnable(this, + &IceTestPeer::ChangeNetworkState_s, + true), + NS_DISPATCH_SYNC); + } + int trickled() { return trickled_; } void SetControlling(NrIceCtx::Controlling controlling) { @@ -3350,6 +3370,49 @@ TEST_F(WebRtcIceConnectTest, TestConsentDelayed) { SendReceive(); } +TEST_F(WebRtcIceConnectTest, TestNetworkForcedOfflineAndRecovery) { + AddStream(1); + SetupAndCheckConsent(); + p1_->ChangeNetworkStateToOffline(); + ASSERT_TRUE_WAIT(p1_->ice_connected() == 0, kDefaultTimeout); + // Next round of consent check should switch it back to online + ASSERT_TRUE_WAIT(p1_->ice_connected(), kDefaultTimeout); +} + +TEST_F(WebRtcIceConnectTest, TestNetworkForcedOfflineTwice) { + AddStream(1); + SetupAndCheckConsent(); + p2_->ChangeNetworkStateToOffline(); + ASSERT_TRUE_WAIT(p2_->ice_connected() == 0, kDefaultTimeout); + p2_->ChangeNetworkStateToOffline(); + ASSERT_TRUE_WAIT(p2_->ice_connected() == 0, kDefaultTimeout); +} + +TEST_F(WebRtcIceConnectTest, TestNetworkOnlineDoesntChangeState) { + AddStream(1); + SetupAndCheckConsent(); + p2_->ChangeNetworkStateToOnline(); + ASSERT_TRUE(p2_->ice_connected()); + PR_Sleep(1500); + p2_->ChangeNetworkStateToOnline(); + ASSERT_TRUE(p2_->ice_connected()); +} + +TEST_F(WebRtcIceConnectTest, TestNetworkOnlineTriggersConsent) { + // Let's emulate audio + video w/o rtcp-mux + AddStream(2); + AddStream(2); + SetupAndCheckConsent(); + p1_->ChangeNetworkStateToOffline(); + p1_->SetBlockStun(true); + ASSERT_TRUE_WAIT(p1_->ice_connected() == 0, kDefaultTimeout); + PR_Sleep(1500); + ASSERT_TRUE(p1_->ice_connected() == 0); + p1_->SetBlockStun(false); + p1_->ChangeNetworkStateToOnline(); + ASSERT_TRUE_WAIT(p1_->ice_connected(), 500); +} + TEST_F(WebRtcIceConnectTest, TestConnectTurn) { if (turn_server_.empty()) return; diff --git a/media/mtransport/third_party/nICEr/src/ice/ice_component.c b/media/mtransport/third_party/nICEr/src/ice/ice_component.c index 2be25efca370..fc67183687af 100644 --- a/media/mtransport/third_party/nICEr/src/ice/ice_component.c +++ b/media/mtransport/third_party/nICEr/src/ice/ice_component.c @@ -1242,13 +1242,22 @@ static void nr_ice_component_consent_timeout_cb(NR_SOCKET s, int how, void *cb_a } -static void nr_ice_component_consent_request_timed_out(nr_ice_component *comp) +void nr_ice_component_disconnected(nr_ice_component *comp) { if (!comp->can_send) { return; } - nr_ice_peer_ctx_disconnected(comp->stream->pctx); + if (comp->disconnected) { + return; + } + + r_log(LOG_ICE,LOG_WARNING,"ICE(%s)/STREAM(%s)/COMP(%d): component disconnected", + comp->ctx->label, comp->stream->label, comp->component_id); + comp->disconnected = 1; + + /* a single disconnected component disconnects the stream */ + nr_ice_media_stream_set_disconnected(comp->stream, NR_ICE_MEDIA_STREAM_DISCONNECTED); } static void nr_ice_component_consent_refreshed(nr_ice_component *comp) @@ -1264,7 +1273,9 @@ static void nr_ice_component_consent_refreshed(nr_ice_component *comp) comp->ctx->label, comp->stream->label, comp->component_id, comp->consent_last_seen.tv_sec); - nr_ice_peer_ctx_connected(comp->stream->pctx); + comp->disconnected = 0; + + nr_ice_media_stream_check_if_connected(comp->stream); if (comp->consent_timeout) NR_async_timer_cancel(comp->consent_timeout); @@ -1297,7 +1308,7 @@ static void nr_ice_component_refresh_consent_cb(NR_SOCKET s, int how, void *cb_a case NR_STUN_CLIENT_STATE_TIMED_OUT: r_log(LOG_ICE, LOG_INFO, "ICE(%s)/STREAM(%s)/COMP(%d): A single consent refresh request timed out", comp->ctx->label, comp->stream->label, comp->component_id); - nr_ice_component_consent_request_timed_out(comp); + nr_ice_component_disconnected(comp); break; default: break; @@ -1340,6 +1351,9 @@ static void nr_ice_component_consent_timer_cb(NR_SOCKET s, int how, void *cb_arg nr_ice_component *comp=cb_arg; int r; + if (comp->consent_timer) { + NR_async_timer_cancel(comp->consent_timer); + } comp->consent_timer = 0; comp->consent_ctx->params.ice_binding_request.username = @@ -1361,12 +1375,6 @@ static void nr_ice_component_consent_timer_cb(NR_SOCKET s, int how, void *cb_arg comp)) { r_log(LOG_ICE,LOG_ERR,"ICE(%s)/STREAM(%s)/COMP(%d): Refresh consent failed with %d", comp->ctx->label, comp->stream->label, comp->component_id, r); - /* In case our attempt to send the refresh binding request reports an - * error we don't have to wait for timeouts, but declare this connection - * dead right away. */ - if (r != R_WOULDBLOCK) { - nr_ice_component_consent_failed(comp); - } } nr_ice_component_consent_schedule_consent_timer(comp); @@ -1384,6 +1392,11 @@ void nr_ice_component_consent_schedule_consent_timer(nr_ice_component *comp) &comp->consent_timer); } +void nr_ice_component_refresh_consent_now(nr_ice_component *comp) + { + nr_ice_component_consent_timer_cb(0, 0, comp); + } + void nr_ice_component_consent_destroy(nr_ice_component *comp) { if (comp->consent_timer) { @@ -1401,6 +1414,7 @@ void nr_ice_component_consent_destroy(nr_ice_component *comp) } if (comp->consent_ctx) { nr_stun_client_ctx_destroy(&comp->consent_ctx); + comp->consent_ctx = 0; } } @@ -1411,6 +1425,8 @@ int nr_ice_component_setup_consent(nr_ice_component *comp) r_log(LOG_ICE,LOG_DEBUG,"ICE(%s)/STREAM(%s)/COMP(%d): Setting up refresh consent", comp->ctx->label, comp->stream->label, comp->component_id); + nr_ice_component_consent_destroy(comp); + if (r=nr_stun_client_ctx_create("consent", comp->active->local->osock, &comp->active->remote->addr, 0, &comp->consent_ctx)) @@ -1423,6 +1439,7 @@ int nr_ice_component_setup_consent(nr_ice_component *comp) ABORT(r); comp->can_send = 1; + comp->disconnected = 0; nr_ice_component_consent_refreshed(comp); nr_ice_component_consent_calc_consent_timer(comp); diff --git a/media/mtransport/third_party/nICEr/src/ice/ice_component.h b/media/mtransport/third_party/nICEr/src/ice/ice_component.h index 5bb0ea1e7a68..014119e13c3d 100644 --- a/media/mtransport/third_party/nICEr/src/ice/ice_component.h +++ b/media/mtransport/third_party/nICEr/src/ice/ice_component.h @@ -75,6 +75,7 @@ struct nr_ice_component_ { void *consent_timeout; void *consent_handle; int can_send; + int disconnected; struct timeval consent_last_seen; STAILQ_ENTRY(nr_ice_component_)entry; @@ -97,6 +98,8 @@ int nr_ice_component_set_failed(nr_ice_component *comp); int nr_ice_component_finalize(nr_ice_component *lcomp, nr_ice_component *rcomp); int nr_ice_component_insert_pair(nr_ice_component *pcomp, nr_ice_cand_pair *pair); int nr_ice_component_get_default_candidate(nr_ice_component *comp, nr_ice_candidate **candp, int ip_version); +void nr_ice_component_refresh_consent_now(nr_ice_component *comp); +void nr_ice_component_disconnected(nr_ice_component *comp); #ifdef __cplusplus } diff --git a/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.c b/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.c index b93e45aeb0fa..aaaafde581d5 100644 --- a/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.c +++ b/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.c @@ -43,7 +43,7 @@ static char *RCSSTRING __UNUSED__="$Id: ice_media_stream.c,v 1.2 2008/04/28 17:5 #include "ice_ctx.h" static char *nr_ice_media_stream_states[]={"INVALID", - "UNPAIRED","FROZEN","ACTIVE","COMPLETED","FAILED" + "UNPAIRED","FROZEN","ACTIVE","CONNECTED","FAILED" }; int nr_ice_media_stream_set_state(nr_ice_media_stream *str, int state); @@ -74,6 +74,7 @@ int nr_ice_media_stream_create(nr_ice_ctx *ctx,char *label,int components, nr_ic TAILQ_INIT(&stream->check_list); TAILQ_INIT(&stream->trigger_check_queue); + stream->disconnected = 0; stream->component_ct=components; stream->ice_state = NR_ICE_MEDIA_STREAM_UNPAIRED; *streamp=stream; @@ -339,7 +340,7 @@ static void nr_ice_media_stream_check_timer_cb(NR_SOCKET s, int h, void *cb_arg) pair=TAILQ_NEXT(pair,triggered_check_queue_entry); } - if (stream->ice_state != NR_ICE_MEDIA_STREAM_CHECKS_COMPLETED) { + if (stream->ice_state != NR_ICE_MEDIA_STREAM_CHECKS_CONNECTED) { if(!pair){ /* Find the highest priority WAITING check and move it to RUNNING */ pair=TAILQ_FIRST(&stream->check_list); @@ -392,7 +393,7 @@ int nr_ice_media_stream_start_checks(nr_ice_peer_ctx *pctx, nr_ice_media_stream /* Even if the stream is completed already remote can still create a new * triggered check request which needs to fire, but not change our stream * state. */ - if (stream->ice_state != NR_ICE_MEDIA_STREAM_CHECKS_COMPLETED) { + if (stream->ice_state != NR_ICE_MEDIA_STREAM_CHECKS_CONNECTED) { if(r=nr_ice_media_stream_set_state(stream,NR_ICE_MEDIA_STREAM_CHECKS_ACTIVE)) { ABORT(r); } @@ -584,6 +585,80 @@ int nr_ice_media_stream_set_state(nr_ice_media_stream *str, int state) return(0); } + +void nr_ice_media_stream_refresh_consent_all(nr_ice_media_stream *stream) + { + nr_ice_component *comp; + + comp=STAILQ_FIRST(&stream->components); + while(comp){ + if((comp->state != NR_ICE_COMPONENT_DISABLED) && + (comp->local_component->state != NR_ICE_COMPONENT_DISABLED) && + comp->disconnected) { + nr_ice_component_refresh_consent_now(comp); + } + + comp=STAILQ_NEXT(comp,entry); + } + } + +void nr_ice_media_stream_disconnect_all_components(nr_ice_media_stream *stream) + { + nr_ice_component *comp; + + comp=STAILQ_FIRST(&stream->components); + while(comp){ + if((comp->state != NR_ICE_COMPONENT_DISABLED) && + (comp->local_component->state != NR_ICE_COMPONENT_DISABLED)) { + comp->disconnected = 1; + } + + comp=STAILQ_NEXT(comp,entry); + } + } + +void nr_ice_media_stream_set_disconnected(nr_ice_media_stream *stream, int disconnected) + { + if (stream->disconnected == disconnected) { + return; + } + + if (stream->ice_state != NR_ICE_MEDIA_STREAM_CHECKS_CONNECTED) { + return; + } + stream->disconnected = disconnected; + + if (disconnected == NR_ICE_MEDIA_STREAM_DISCONNECTED) { + nr_ice_peer_ctx_disconnected(stream->pctx); + } else { + nr_ice_peer_ctx_check_if_connected(stream->pctx); + } + } + +int nr_ice_media_stream_check_if_connected(nr_ice_media_stream *stream) + { + nr_ice_component *comp; + + comp=STAILQ_FIRST(&stream->components); + while(comp){ + if((comp->state != NR_ICE_COMPONENT_DISABLED) && + (comp->local_component->state != NR_ICE_COMPONENT_DISABLED) && + comp->disconnected) + break; + + comp=STAILQ_NEXT(comp,entry); + } + + /* At least one disconnected component */ + if(comp) + goto done; + + nr_ice_media_stream_set_disconnected(stream, NR_ICE_MEDIA_STREAM_CONNECTED); + + done: + return(0); + } + /* S OK, this component has a nominated. If every component has a nominated, the stream is ready */ int nr_ice_media_stream_component_nominated(nr_ice_media_stream *stream,nr_ice_component *component) @@ -607,7 +682,7 @@ int nr_ice_media_stream_component_nominated(nr_ice_media_stream *stream,nr_ice_c /* All done... */ r_log(LOG_ICE,LOG_INFO,"ICE-PEER(%s)/ICE-STREAM(%s): all active components have nominated candidate pairs",stream->pctx->label,stream->label); - nr_ice_media_stream_set_state(stream,NR_ICE_MEDIA_STREAM_CHECKS_COMPLETED); + nr_ice_media_stream_set_state(stream,NR_ICE_MEDIA_STREAM_CHECKS_CONNECTED); /* Cancel our timer */ if(stream->timer){ @@ -747,8 +822,12 @@ int nr_ice_media_stream_send(nr_ice_peer_ctx *pctx, nr_ice_media_stream *str, in 2. Use the address on the remote side */ if(r=nr_socket_sendto(comp->active->local->osock,data,len,0, - &comp->active->remote->addr)) + &comp->active->remote->addr)) { + if ((r==R_IO_ERROR) || (r==R_EOD)) { + nr_ice_component_disconnected(comp); + } ABORT(r); + } _status=0; abort: diff --git a/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.h b/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.h index 3d818d5300ec..0730ed34444b 100644 --- a/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.h +++ b/media/mtransport/third_party/nICEr/src/ice/ice_media_stream.h @@ -59,9 +59,14 @@ struct nr_ice_media_stream_ { #define NR_ICE_MEDIA_STREAM_UNPAIRED 1 #define NR_ICE_MEDIA_STREAM_CHECKS_FROZEN 2 #define NR_ICE_MEDIA_STREAM_CHECKS_ACTIVE 3 -#define NR_ICE_MEDIA_STREAM_CHECKS_COMPLETED 4 +#define NR_ICE_MEDIA_STREAM_CHECKS_CONNECTED 4 #define NR_ICE_MEDIA_STREAM_CHECKS_FAILED 5 + int disconnected; + +#define NR_ICE_MEDIA_STREAM_CONNECTED 0 +#define NR_ICE_MEDIA_STREAM_DISCONNECTED 1 + nr_ice_cand_pair_head check_list; nr_ice_cand_pair_head trigger_check_queue; void *timer; /* Check list periodic timer */ @@ -87,6 +92,10 @@ int nr_ice_media_stream_unfreeze_pairs_foundation(nr_ice_media_stream *stream, c int nr_ice_media_stream_dump_state(nr_ice_peer_ctx *pctx, nr_ice_media_stream *stream,FILE *out); int nr_ice_media_stream_component_nominated(nr_ice_media_stream *stream,nr_ice_component *component); int nr_ice_media_stream_component_failed(nr_ice_media_stream *stream,nr_ice_component *component); +void nr_ice_media_stream_refresh_consent_all(nr_ice_media_stream *stream); +void nr_ice_media_stream_disconnect_all_components(nr_ice_media_stream *stream); +void nr_ice_media_stream_set_disconnected(nr_ice_media_stream *stream, int disconnected); +int nr_ice_media_stream_check_if_connected(nr_ice_media_stream *stream); int nr_ice_media_stream_set_state(nr_ice_media_stream *str, int state); int nr_ice_media_stream_get_best_candidate(nr_ice_media_stream *str, int component, nr_ice_candidate **candp); int nr_ice_media_stream_send(nr_ice_peer_ctx *pctx, nr_ice_media_stream *str, int component, UCHAR *data, int len); diff --git a/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.c b/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.c index d494e45de606..fb92d4a0278d 100644 --- a/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.c +++ b/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.c @@ -648,12 +648,45 @@ int nr_ice_peer_ctx_dump_state(nr_ice_peer_ctx *pctx,FILE *out) } #endif +void nr_ice_peer_ctx_refresh_consent_all_streams(nr_ice_peer_ctx *pctx) + { + nr_ice_media_stream *str; + + r_log(LOG_ICE,LOG_INFO,"ICE-PEER(%s): refreshing consent on all streams",pctx->label); + + str=STAILQ_FIRST(&pctx->peer_streams); + while(str) { + nr_ice_media_stream_refresh_consent_all(str); + str=STAILQ_NEXT(str,entry); + } + } + void nr_ice_peer_ctx_disconnected(nr_ice_peer_ctx *pctx) { if (pctx->reported_connected && pctx->handler && pctx->handler->vtbl->ice_disconnected) { pctx->handler->vtbl->ice_disconnected(pctx->handler->obj, pctx); + + pctx->reported_connected = 0; + } + } + +void nr_ice_peer_ctx_disconnect_all_streams(nr_ice_peer_ctx *pctx) + { + nr_ice_media_stream *str; + + r_log(LOG_ICE,LOG_INFO,"ICE-PEER(%s): disconnecting all streams",pctx->label); + + str=STAILQ_FIRST(&pctx->peer_streams); + while(str) { + nr_ice_media_stream_disconnect_all_components(str); + + /* The first stream to be disconnected will cause the peer ctx to signal + the disconnect up. */ + nr_ice_media_stream_set_disconnected(str, NR_ICE_MEDIA_STREAM_DISCONNECTED); + + str=STAILQ_NEXT(str,entry); } } @@ -687,7 +720,7 @@ int nr_ice_peer_ctx_check_if_connected(nr_ice_peer_ctx *pctx) str=STAILQ_FIRST(&pctx->peer_streams); while(str){ - if(str->ice_state==NR_ICE_MEDIA_STREAM_CHECKS_COMPLETED){ + if(str->ice_state==NR_ICE_MEDIA_STREAM_CHECKS_CONNECTED){ succeeded++; } else if(str->ice_state==NR_ICE_MEDIA_STREAM_CHECKS_FAILED){ @@ -716,7 +749,6 @@ int nr_ice_peer_ctx_check_if_connected(nr_ice_peer_ctx *pctx) done: _status=0; -// abort: return(_status); } diff --git a/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.h b/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.h index 47e3be70408a..0f6de9d0eb79 100644 --- a/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.h +++ b/media/mtransport/third_party/nICEr/src/ice/ice_peer_ctx.h @@ -83,6 +83,8 @@ int nr_ice_peer_ctx_parse_global_attributes(nr_ice_peer_ctx *pctx, char **attrs, int nr_ice_peer_ctx_start_checks(nr_ice_peer_ctx *pctx); int nr_ice_peer_ctx_start_checks2(nr_ice_peer_ctx *pctx, int allow_non_first); void nr_ice_peer_ctx_stream_started_checks(nr_ice_peer_ctx *pctx, nr_ice_media_stream *stream); +void nr_ice_peer_ctx_refresh_consent_all_streams(nr_ice_peer_ctx *pctx); +void nr_ice_peer_ctx_disconnect_all_streams(nr_ice_peer_ctx *pctx); void nr_ice_peer_ctx_disconnected(nr_ice_peer_ctx *pctx); void nr_ice_peer_ctx_connected(nr_ice_peer_ctx *pctx); int nr_ice_peer_ctx_dump_state(nr_ice_peer_ctx *pctx,FILE *out); diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp b/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp index 515258efba91..84134171f9a0 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp @@ -22,9 +22,12 @@ #include "nsServiceManagerUtils.h" // do_GetService #include "nsIObserverService.h" #include "nsIObserver.h" +#include "nsIIOService.h" // NS_IOSERVICE_* #include "mozilla/Services.h" #include "mozilla/StaticPtr.h" +#include "nsCRTGlue.h" + #include "gmp-video-decode.h" // GMP_API_VIDEO_DECODER #include "gmp-video-encode.h" // GMP_API_VIDEO_ENCODER @@ -34,12 +37,12 @@ namespace mozilla { using namespace dom; -class PeerConnectionCtxShutdown : public nsIObserver +class PeerConnectionCtxObserver : public nsIObserver { public: NS_DECL_ISUPPORTS - PeerConnectionCtxShutdown() {} + PeerConnectionCtxObserver() {} void Init() { @@ -55,6 +58,10 @@ public: NS_XPCOM_SHUTDOWN_OBSERVER_ID, false); MOZ_ALWAYS_SUCCEEDS(rv); + rv = observerService->AddObserver(this, + NS_IOSERVICE_OFFLINE_STATUS_TOPIC, + false); + MOZ_ALWAYS_SUCCEEDS(rv); #endif (void) rv; } @@ -71,34 +78,52 @@ public: return NS_ERROR_FAILURE; nsresult rv = observerService->RemoveObserver(this, - NS_XPCOM_SHUTDOWN_OBSERVER_ID); + NS_IOSERVICE_OFFLINE_STATUS_TOPIC); + MOZ_ALWAYS_SUCCEEDS(rv); + rv = observerService->RemoveObserver(this, + NS_XPCOM_SHUTDOWN_OBSERVER_ID); MOZ_ALWAYS_SUCCEEDS(rv); // Make sure we're not deleted while still inside ::Observe() - RefPtr kungFuDeathGrip(this); - PeerConnectionCtx::gPeerConnectionCtxShutdown = nullptr; + RefPtr kungFuDeathGrip(this); + PeerConnectionCtx::gPeerConnectionCtxObserver = nullptr; + } + if (strcmp(aTopic, NS_IOSERVICE_OFFLINE_STATUS_TOPIC) == 0) { + const nsLiteralString onlineString(u"" NS_IOSERVICE_ONLINE); + const nsLiteralString offlineString(u"" NS_IOSERVICE_OFFLINE); + if (NS_strcmp(aData, offlineString.get()) == 0) { + CSFLogDebug(logTag, "Updating network state to offline"); + PeerConnectionCtx::UpdateNetworkState(false); + } else if(NS_strcmp(aData, onlineString.get()) == 0) { + CSFLogDebug(logTag, "Updating network state to online"); + PeerConnectionCtx::UpdateNetworkState(true); + } else { + CSFLogDebug(logTag, "Received unsupported network state event"); + MOZ_CRASH(); + } } return NS_OK; } private: - virtual ~PeerConnectionCtxShutdown() + virtual ~PeerConnectionCtxObserver() { nsCOMPtr observerService = services::GetObserverService(); if (observerService) + observerService->RemoveObserver(this, NS_IOSERVICE_OFFLINE_STATUS_TOPIC); observerService->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID); } }; -NS_IMPL_ISUPPORTS(PeerConnectionCtxShutdown, nsIObserver); +NS_IMPL_ISUPPORTS(PeerConnectionCtxObserver, nsIObserver); } namespace mozilla { PeerConnectionCtx* PeerConnectionCtx::gInstance; nsIThread* PeerConnectionCtx::gMainThread; -StaticRefPtr PeerConnectionCtx::gPeerConnectionCtxShutdown; +StaticRefPtr PeerConnectionCtx::gPeerConnectionCtxObserver; const std::map& PeerConnectionCtx::mGetPeerConnections() @@ -129,9 +154,9 @@ nsresult PeerConnectionCtx::InitializeGlobal(nsIThread *mainThread, gInstance = ctx; - if (!PeerConnectionCtx::gPeerConnectionCtxShutdown) { - PeerConnectionCtx::gPeerConnectionCtxShutdown = new PeerConnectionCtxShutdown(); - PeerConnectionCtx::gPeerConnectionCtxShutdown->Init(); + if (!PeerConnectionCtx::gPeerConnectionCtxObserver) { + PeerConnectionCtx::gPeerConnectionCtxObserver = new PeerConnectionCtxObserver(); + PeerConnectionCtx::gPeerConnectionCtxObserver->Init(); } } @@ -334,6 +359,17 @@ PeerConnectionCtx::EverySecondTelemetryCallback_m(nsITimer* timer, void *closure } #endif +void +PeerConnectionCtx::UpdateNetworkState(bool online) { + auto ctx = GetInstance(); + if (ctx->mPeerConnections.empty()) { + return; + } + for (auto pc : ctx->mPeerConnections) { + pc.second->UpdateNetworkState(online); + } +} + nsresult PeerConnectionCtx::Initialize() { initGMP(); diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.h b/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.h index 3f7d6250b05d..c150e2a06fbc 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.h +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.h @@ -18,7 +18,7 @@ #include "nsIRunnable.h" namespace mozilla { -class PeerConnectionCtxShutdown; +class PeerConnectionCtxObserver; namespace dom { class WebrtcGlobalInformation; @@ -48,6 +48,8 @@ class PeerConnectionCtx { bool gmpHasH264(); + static void UpdateNetworkState(bool online); + // Make these classes friend so that they can access mPeerconnections. friend class PeerConnectionImpl; friend class PeerConnectionWrapper; @@ -101,7 +103,7 @@ private: static PeerConnectionCtx *gInstance; public: static nsIThread *gMainThread; - static mozilla::StaticRefPtr gPeerConnectionCtxShutdown; + static mozilla::StaticRefPtr gPeerConnectionCtxObserver; }; } // namespace mozilla diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp index 7720982c5379..437149ccb81c 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp @@ -2297,10 +2297,17 @@ PeerConnectionImpl::AddIceCandidate(const char* aCandidate, const char* aMid, un pco->OnAddIceCandidateError(error, ObString(errorString.c_str()), rv); } - UpdateSignalingState(); return NS_OK; } +void +PeerConnectionImpl::UpdateNetworkState(bool online) { + if (!mMedia) { + return; + } + mMedia->UpdateNetworkState(online); +} + NS_IMETHODIMP PeerConnectionImpl::CloseStreams() { PC_AUTO_ENTER_API_CALL(false); @@ -3364,8 +3371,6 @@ PeerConnectionImpl::CandidateReady(const std::string& candidate, CSFLogDebug(logTag, "Passing local candidate to content: %s", candidate.c_str()); SendLocalIceCandidateToContent(level, mid, candidate); - - UpdateSignalingState(); } static void diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h index 49a453e6c40a..b79481eda9fd 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h @@ -414,6 +414,8 @@ public: NS_ConvertUTF16toUTF8(aMid).get(), aLevel); } + void UpdateNetworkState(bool online); + NS_IMETHODIMP CloseStreams(); void CloseStreams(ErrorResult &rv) diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp index e1c66ff4a465..4ff6f8353b5c 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp @@ -858,6 +858,7 @@ PeerConnectionMedia::AddIceCandidate(const std::string& candidate, aMLine), NS_DISPATCH_NORMAL); } + void PeerConnectionMedia::AddIceCandidate_s(const std::string& aCandidate, const std::string& aMid, @@ -877,6 +878,21 @@ PeerConnectionMedia::AddIceCandidate_s(const std::string& aCandidate, } } +void +PeerConnectionMedia::UpdateNetworkState(bool online) { + RUN_ON_THREAD(GetSTSThread(), + WrapRunnable( + RefPtr(this), + &PeerConnectionMedia::UpdateNetworkState_s, + online), + NS_DISPATCH_NORMAL); +} + +void +PeerConnectionMedia::UpdateNetworkState_s(bool online) { + mIceCtxHdlr->ctx()->UpdateNetworkState(online); +} + void PeerConnectionMedia::FlushIceCtxOperationQueueIfReady() { diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h index 3ecddf8ca3d4..da1546235f3d 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h @@ -292,6 +292,9 @@ class PeerConnectionMedia : public sigslot::has_slots<> { void AddIceCandidate(const std::string& candidate, const std::string& mid, uint32_t aMLine); + // Handle notifications of network online/offline events. + void UpdateNetworkState(bool online); + // Handle complete media pipelines. nsresult UpdateMediaPipelines(const JsepSession& session); @@ -491,6 +494,7 @@ class PeerConnectionMedia : public sigslot::has_slots<> { void AddIceCandidate_s(const std::string& aCandidate, const std::string& aMid, uint32_t aMLine); + void UpdateNetworkState_s(bool online); // ICE events void IceGatheringStateChange_s(NrIceCtx* ctx, From 0fde5f380831498cfafcd0f8c4bd8c0cc8721d87 Mon Sep 17 00:00:00 2001 From: Masatoshi Kimura Date: Fri, 30 Dec 2016 20:32:29 +0900 Subject: [PATCH 040/229] Bug 1321705 - Remove "network.standard-url.(escape|encode)-utf8". r=valentin.gosu MozReview-Commit-ID: D6fRD9ElrBd --HG-- extra : rebase_source : 55fd4c55a4822076bde8a616dd4ddbde26c8e398 --- modules/libpref/init/all.js | 8 -------- netwerk/base/nsStandardURL.cpp | 28 +++------------------------- netwerk/base/nsStandardURL.h | 3 --- 3 files changed, 3 insertions(+), 36 deletions(-) diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js index 210787ce86f7..713563e04552 100644 --- a/modules/libpref/init/all.js +++ b/modules/libpref/init/all.js @@ -1851,14 +1851,6 @@ pref("network.dns.localDomains", ""); // Contols whether or not "localhost" should resolve when offline pref("network.dns.offline-localhost", true); -// This preference controls whether or not URLs with UTF-8 characters are -// escaped. Set this preference to TRUE for strict RFC2396 conformance. -pref("network.standard-url.escape-utf8", true); - -// This preference controls whether or not URLs are always encoded and sent as -// UTF-8. -pref("network.standard-url.encode-utf8", true); - // The maximum allowed length for a URL - 1MB default pref("network.standard-url.max-length", 1048576); diff --git a/netwerk/base/nsStandardURL.cpp b/netwerk/base/nsStandardURL.cpp index 77e17478b997..fccc2c7ef585 100644 --- a/netwerk/base/nsStandardURL.cpp +++ b/netwerk/base/nsStandardURL.cpp @@ -140,8 +140,6 @@ static NS_DEFINE_CID(kStandardURLCID, NS_STANDARDURL_CID); nsIIDNService *nsStandardURL::gIDN = nullptr; bool nsStandardURL::gInitialized = false; -bool nsStandardURL::gEscapeUTF8 = true; -bool nsStandardURL::gAlwaysEncodeInUTF8 = true; char nsStandardURL::gHostLimitDigits[] = { '/', '\\', '?', '#', 0 }; //---------------------------------------------------------------------------- @@ -158,8 +156,6 @@ char nsStandardURL::gHostLimitDigits[] = { '/', '\\', '?', '#', 0 }; // nsStandardURL::nsPrefObserver //---------------------------------------------------------------------------- -#define NS_NET_PREF_ESCAPEUTF8 "network.standard-url.escape-utf8" -#define NS_NET_PREF_ALWAYSENCODEINUTF8 "network.standard-url.encode-utf8" #define NS_NET_PREF_ENABLE_RUST "network.standard-url.enable-rust" NS_IMPL_ISUPPORTS(nsStandardURL::nsPrefObserver, nsIObserver) @@ -225,13 +221,10 @@ nsSegmentEncoder::EncodeSegmentCount(const char *str, } } - // escape per RFC2396 unless UTF-8 and allowed by preferences - int16_t escapeFlags = (gEscapeUTF8 || mEncoder) ? 0 : esc_OnlyASCII; - uint32_t initLen = result.Length(); // now perform any required escaping - if (NS_EscapeURL(str + pos, len, mask | escapeFlags, result)) { + if (NS_EscapeURL(str + pos, len, mask, result)) { len = result.Length() - initLen; appended = true; } @@ -280,7 +273,7 @@ nsSegmentEncoder::InitUnicodeEncoder() nsSegmentEncoder name(useUTF8 ? nullptr : mOriginCharset.get()) #define GET_SEGMENT_ENCODER(name) \ - GET_SEGMENT_ENCODER_INTERNAL(name, gAlwaysEncodeInUTF8) + GET_SEGMENT_ENCODER_INTERNAL(name, true) #define GET_QUERY_ENCODER(name) \ GET_SEGMENT_ENCODER_INTERNAL(name, false) @@ -372,8 +365,6 @@ nsStandardURL::InitGlobalObjects() nsCOMPtr prefBranch( do_GetService(NS_PREFSERVICE_CONTRACTID) ); if (prefBranch) { nsCOMPtr obs( new nsPrefObserver() ); - prefBranch->AddObserver(NS_NET_PREF_ESCAPEUTF8, obs.get(), false); - prefBranch->AddObserver(NS_NET_PREF_ALWAYSENCODEINUTF8, obs.get(), false); #ifdef MOZ_RUST_URLPARSE prefBranch->AddObserver(NS_NET_PREF_ENABLE_RUST, obs.get(), false); #endif @@ -1178,26 +1169,13 @@ nsStandardURL::WriteSegment(nsIBinaryOutputStream *stream, const URLSegment &seg /* static */ void nsStandardURL::PrefsChanged(nsIPrefBranch *prefs, const char *pref) { - bool val; - LOG(("nsStandardURL::PrefsChanged [pref=%s]\n", pref)); #define PREF_CHANGED(p) ((pref == nullptr) || !strcmp(pref, p)) #define GOT_PREF(p, b) (NS_SUCCEEDED(prefs->GetBoolPref(p, &b))) - if (PREF_CHANGED(NS_NET_PREF_ESCAPEUTF8)) { - if (GOT_PREF(NS_NET_PREF_ESCAPEUTF8, val)) - gEscapeUTF8 = val; - LOG(("escape UTF-8 %s\n", gEscapeUTF8 ? "enabled" : "disabled")); - } - - if (PREF_CHANGED(NS_NET_PREF_ALWAYSENCODEINUTF8)) { - if (GOT_PREF(NS_NET_PREF_ALWAYSENCODEINUTF8, val)) - gAlwaysEncodeInUTF8 = val; - LOG(("encode in UTF-8 %s\n", gAlwaysEncodeInUTF8 ? "enabled" : "disabled")); - } - #ifdef MOZ_RUST_URLPARSE + bool val; if (PREF_CHANGED(NS_NET_PREF_ENABLE_RUST)) { if (GOT_PREF(NS_NET_PREF_ENABLE_RUST, val)) { gRustEnabled = val; diff --git a/netwerk/base/nsStandardURL.h b/netwerk/base/nsStandardURL.h index 613db691b601..3c06e0cc0137 100644 --- a/netwerk/base/nsStandardURL.h +++ b/netwerk/base/nsStandardURL.h @@ -301,9 +301,6 @@ private: static nsIIDNService *gIDN; static char gHostLimitDigits[]; static bool gInitialized; - static bool gEscapeUTF8; - static bool gAlwaysEncodeInUTF8; - static bool gEncodeQueryInUTF8; public: #ifdef DEBUG_DUMP_URLS_AT_SHUTDOWN From 5c9dc72fccf31dc8c396028bb28dbb6f457bd011 Mon Sep 17 00:00:00 2001 From: bechen Date: Wed, 28 Dec 2016 15:51:37 +0800 Subject: [PATCH 041/229] Bug 1310162 - mTrack in SimpleTextTrackEvent might be null. r=jwwang MozReview-Commit-ID: ESqYqBem7kQ --HG-- extra : rebase_source : b8ad44e919992a7eaa3e8e1db9b0c5258c66d617 --- dom/html/TextTrackManager.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/dom/html/TextTrackManager.cpp b/dom/html/TextTrackManager.cpp index f138e686c224..1c5782c4cf71 100644 --- a/dom/html/TextTrackManager.cpp +++ b/dom/html/TextTrackManager.cpp @@ -491,11 +491,13 @@ class CompareSimpleTextTrackEvents { private: int32_t TrackChildPosition(SimpleTextTrackEvent* aEvent) const { - HTMLTrackElement* trackElement = aEvent->mTrack->GetTrackElement();; - if (!trackElement) { - return -1; + if (aEvent->mTrack) { + HTMLTrackElement* trackElement = aEvent->mTrack->GetTrackElement(); + if (trackElement) { + return mMediaElement->IndexOf(trackElement); + } } - return mMediaElement->IndexOf(trackElement); + return -1; } HTMLMediaElement* mMediaElement; public: From d62604fd8b53bbfaa59ca70e5692aa371e08bc44 Mon Sep 17 00:00:00 2001 From: Tim Nguyen Date: Fri, 30 Dec 2016 15:01:42 +0100 Subject: [PATCH 042/229] Bug 1325213 - Fix lots of eslint errors in devtools/shared/. r=jryans MozReview-Commit-ID: 2XxhfV8ih0S --HG-- extra : rebase_source : 48cda848a23c57d3301db5e563ad8f5f20064862 --- .eslintignore | 11 - devtools/shared/client/connection-manager.js | 22 +- devtools/shared/client/main.js | 1310 +++++++++-------- devtools/shared/discovery/discovery.js | 22 +- .../shared/discovery/tests/unit/.eslintrc.js | 6 + .../discovery/tests/unit/test_discovery.js | 1 - .../shared/performance/recording-common.js | 86 +- .../shared/performance/recording-utils.js | 7 +- devtools/shared/performance/test/.eslintrc.js | 6 + devtools/shared/performance/test/head.js | 5 +- .../test_perf-utils-allocations-to-samples.js | 14 +- devtools/shared/qrcode/index.js | 1 - .../shared/qrcode/tests/unit/.eslintrc.js | 6 + devtools/shared/security/auth.js | 10 +- devtools/shared/security/cert.js | 1 - devtools/shared/security/socket.js | 10 +- .../shared/security/tests/chrome/.eslintrc.js | 6 + .../chrome/test_websocket-transport.html | 8 +- .../shared/security/tests/unit/head_dbg.js | 56 +- .../security/tests/unit/test_oob_cert_auth.js | 12 +- .../shared/security/tests/unit/testactors.js | 34 +- devtools/shared/shims/event-emitter.js | 9 +- .../tests/browser/browser_async_storage.js | 2 +- devtools/shared/tests/unit/exposeLoader.js | 2 + devtools/shared/tests/unit/head_devtools.js | 36 +- devtools/shared/tests/unit/test_assert.js | 5 +- .../shared/tests/unit/test_async-utils.js | 16 +- .../tests/unit/test_console_filtering.js | 20 +- .../unit/test_defineLazyPrototypeGetter.js | 4 +- .../shared/tests/unit/test_executeSoon.js | 1 - devtools/shared/tests/unit/test_flatten.js | 2 + .../tests/unit/test_independent_loaders.js | 2 + devtools/shared/tests/unit/test_isSet.js | 2 + devtools/shared/tests/unit/test_require.js | 2 + .../shared/tests/unit/test_require_lazy.js | 6 +- .../shared/tests/unit/test_require_raw.js | 2 + .../shared/tests/unit/test_safeErrorString.js | 2 + devtools/shared/tests/unit/test_stack.js | 2 + devtools/shared/touch/simulator-content.js | 2 +- devtools/shared/touch/simulator-core.js | 18 +- 40 files changed, 969 insertions(+), 800 deletions(-) create mode 100644 devtools/shared/discovery/tests/unit/.eslintrc.js create mode 100644 devtools/shared/performance/test/.eslintrc.js create mode 100644 devtools/shared/qrcode/tests/unit/.eslintrc.js create mode 100644 devtools/shared/security/tests/chrome/.eslintrc.js diff --git a/.eslintignore b/.eslintignore index a676a160e1c7..3c8a9c3b2323 100644 --- a/.eslintignore +++ b/.eslintignore @@ -117,20 +117,9 @@ devtools/server/tests/browser/** devtools/server/tests/mochitest/** devtools/server/tests/unit/** devtools/shared/apps/** -devtools/shared/client/** -devtools/shared/discovery/** devtools/shared/gcli/** !devtools/shared/gcli/templater.js devtools/shared/heapsnapshot/** -devtools/shared/layout/** -devtools/shared/performance/** -!devtools/shared/platform/** -devtools/shared/qrcode/** -devtools/shared/security/** -devtools/shared/shims/** -devtools/shared/tests/** -!devtools/shared/tests/unit/test_csslexer.js -devtools/shared/touch/** devtools/shared/transport/** !devtools/shared/transport/transport.js !devtools/shared/transport/websocket-transport.js diff --git a/devtools/shared/client/connection-manager.js b/devtools/shared/client/connection-manager.js index ef242db85302..6b6a1e5e85c9 100644 --- a/devtools/shared/client/connection-manager.js +++ b/devtools/shared/client/connection-manager.js @@ -6,9 +6,8 @@ "use strict"; -const {Cc, Ci, Cu, Cr} = require("chrome"); +const {Cc, Ci, Cr} = require("chrome"); const EventEmitter = require("devtools/shared/event-emitter"); -const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/main"); const Services = require("Services"); @@ -70,8 +69,10 @@ const REMOTE_TIMEOUT = "devtools.debugger.remote-timeout"; * . Connection.Events.CONNECTING Trying to connect to host:port * . Connection.Events.CONNECTED Connection is successful * . Connection.Events.DISCONNECTING Trying to disconnect from server - * . Connection.Events.DISCONNECTED Disconnected (at client request, or because of a timeout or connection error) - * . Connection.Events.STATUS_CHANGED The connection status (connection.status) has changed + * . Connection.Events.DISCONNECTED Disconnected (at client request, + * or because of a timeout or connection error) + * . Connection.Events.STATUS_CHANGED The connection status (connection.status) + * has changed * . Connection.Events.TIMEOUT Connection timeout * . Connection.Events.HOST_CHANGED Host has changed * . Connection.Events.PORT_CHANGED Port has changed @@ -168,8 +169,9 @@ Connection.prototype = { }, set host(value) { - if (this._host && this._host == value) + if (this._host && this._host == value) { return; + } this._host = value; this.emit(Connection.Events.HOST_CHANGED); }, @@ -179,8 +181,9 @@ Connection.prototype = { }, set port(value) { - if (this._port && this._port == value) + if (this._port && this._port == value) { return; + } this._port = value; this.emit(Connection.Events.PORT_CHANGED); }, @@ -334,8 +337,9 @@ Connection.prototype = { }, _setStatus: function (value) { - if (this._status && this._status == value) + if (this._status && this._status == value) { return; + } this._status = value; this.emit(value); this.emit(Connection.Events.STATUS_CHANGED, value); @@ -357,7 +361,9 @@ Connection.prototype = { this.log("disconnected (unexpected)"); break; case Connection.Status.CONNECTING: - this.log("connection error. Possible causes: USB port not connected, port not forwarded (adb forward), wrong host or port, remote debugging not enabled on the device."); + this.log("connection error. Possible causes: USB port not connected, port not " + + "forwarded (adb forward), wrong host or port, remote debugging not " + + "enabled on the device."); break; default: this.log("disconnected"); diff --git a/devtools/shared/client/main.js b/devtools/shared/client/main.js index 408c0b277edc..b1e3295aff64 100644 --- a/devtools/shared/client/main.js +++ b/devtools/shared/client/main.js @@ -7,7 +7,6 @@ "use strict"; const { Ci, Cu } = require("chrome"); -const Services = require("Services"); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const { getStack, callFunctionWithAsyncStack } = require("devtools/shared/platform/stack"); @@ -28,22 +27,22 @@ const noop = () => {}; * augmented with the necessary facilities by passing its prototype to this * function. * - * @param aProto object + * @param proto object * The prototype object that will be modified. */ -function eventSource(aProto) { +function eventSource(proto) { /** * Add a listener to the event source for a given event. * - * @param aName string + * @param name string * The event to listen for. - * @param aListener function + * @param listener function * Called when the event is fired. If the same listener * is added more than once, it will be called once per * addListener call. */ - aProto.addListener = function (aName, aListener) { - if (typeof aListener != "function") { + proto.addListener = function (name, listener) { + if (typeof listener != "function") { throw TypeError("Listeners must be functions."); } @@ -51,47 +50,46 @@ function eventSource(aProto) { this._listeners = {}; } - this._getListeners(aName).push(aListener); + this._getListeners(name).push(listener); }; /** * Add a listener to the event source for a given event. The * listener will be removed after it is called for the first time. * - * @param aName string + * @param name string * The event to listen for. - * @param aListener function + * @param listener function * Called when the event is fired. */ - aProto.addOneTimeListener = function (aName, aListener) { + proto.addOneTimeListener = function (name, listener) { let l = (...args) => { - this.removeListener(aName, l); - aListener.apply(null, args); + this.removeListener(name, l); + listener.apply(null, args); }; - this.addListener(aName, l); + this.addListener(name, l); }; /** * Remove a listener from the event source previously added with * addListener(). * - * @param aName string + * @param name string * The event name used during addListener to add the listener. - * @param aListener function + * @param listener function * The callback to remove. If addListener was called multiple * times, all instances will be removed. */ - aProto.removeListener = function (aName, aListener) { - if (!this._listeners || (aListener && !this._listeners[aName])) { + proto.removeListener = function (name, listener) { + if (!this._listeners || (listener && !this._listeners[name])) { return; } - if (!aListener) { - this._listeners[aName] = []; - } - else { - this._listeners[aName] = - this._listeners[aName].filter(function (l) { return l != aListener; }); + if (!listener) { + this._listeners[name] = []; + } else { + this._listeners[name] = + this._listeners[name].filter(l => l != listener); } }; @@ -99,27 +97,27 @@ function eventSource(aProto) { * Returns the listeners for the specified event name. If none are defined it * initializes an empty list and returns that. * - * @param aName string + * @param name string * The event name. */ - aProto._getListeners = function (aName) { - if (aName in this._listeners) { - return this._listeners[aName]; + proto._getListeners = function (name) { + if (name in this._listeners) { + return this._listeners[name]; } - this._listeners[aName] = []; - return this._listeners[aName]; + this._listeners[name] = []; + return this._listeners[name]; }; /** * Notify listeners of an event. * - * @param aName string + * @param name string * The event to fire. * @param arguments * All arguments will be passed along to the listeners, * including the name argument. */ - aProto.emit = function () { + proto.emit = function () { if (!this._listeners) { return; } @@ -202,9 +200,8 @@ const UnsolicitedPauses = { * provides the means to communicate with the server and exchange the messages * required by the protocol in a traditional JavaScript API. */ -const DebuggerClient = exports.DebuggerClient = function (aTransport) -{ - this._transport = aTransport; +const DebuggerClient = exports.DebuggerClient = function (transport) { + this._transport = transport; this._transport.hooks = this; // Map actor ID to client instance for each actor type. @@ -224,18 +221,18 @@ const DebuggerClient = exports.DebuggerClient = function (aTransport) * the connection's root actor. */ this.mainRoot = null; - this.expectReply("root", (aPacket) => { - this.mainRoot = new RootClient(this, aPacket); - this.emit("connected", aPacket.applicationType, aPacket.traits); + this.expectReply("root", (packet) => { + this.mainRoot = new RootClient(this, packet); + this.emit("connected", packet.applicationType, packet.traits); }); }; /** * A declarative helper for defining methods that send requests to the server. * - * @param aPacketSkeleton + * @param packetSkeleton * The form of the packet to send. Can specify fields to be filled from - * the parameters by using the |args| function. + * the parameters by using the |arg| function. * @param before * The function to call before sending the packet. Is passed the packet, * and the return value is used as the new packet. The |this| context is @@ -249,21 +246,21 @@ const DebuggerClient = exports.DebuggerClient = function (aTransport) * The `Request` object that is a Promise object and resolves once * we receive the response. (See request method for more details) */ -DebuggerClient.requester = function (aPacketSkeleton, config = {}) { +DebuggerClient.requester = function (packetSkeleton, config = {}) { let { before, after } = config; return DevToolsUtils.makeInfallible(function (...args) { let outgoingPacket = { - to: aPacketSkeleton.to || this.actor + to: packetSkeleton.to || this.actor }; let maxPosition = -1; - for (let k of Object.keys(aPacketSkeleton)) { - if (aPacketSkeleton[k] instanceof DebuggerClient.Argument) { - let { position } = aPacketSkeleton[k]; - outgoingPacket[k] = aPacketSkeleton[k].getArgument(args); + for (let k of Object.keys(packetSkeleton)) { + if (packetSkeleton[k] instanceof DebuggerClient.Argument) { + let { position } = packetSkeleton[k]; + outgoingPacket[k] = packetSkeleton[k].getArgument(args); maxPosition = Math.max(position, maxPosition); } else { - outgoingPacket[k] = aPacketSkeleton[k]; + outgoingPacket[k] = packetSkeleton[k]; } } @@ -271,37 +268,37 @@ DebuggerClient.requester = function (aPacketSkeleton, config = {}) { outgoingPacket = before.call(this, outgoingPacket); } - return this.request(outgoingPacket, DevToolsUtils.makeInfallible((aResponse) => { + return this.request(outgoingPacket, DevToolsUtils.makeInfallible((response) => { if (after) { - let { from } = aResponse; - aResponse = after.call(this, aResponse); - if (!aResponse.from) { - aResponse.from = from; + let { from } = response; + response = after.call(this, response); + if (!response.from) { + response.from = from; } } // The callback is always the last parameter. let thisCallback = args[maxPosition + 1]; if (thisCallback) { - thisCallback(aResponse); + thisCallback(response); } }, "DebuggerClient.requester request callback")); }, "DebuggerClient.requester"); }; -function args(aPos) { - return new DebuggerClient.Argument(aPos); +function arg(pos) { + return new DebuggerClient.Argument(pos); } -DebuggerClient.Argument = function (aPosition) { - this.position = aPosition; +DebuggerClient.Argument = function (position) { + this.position = position; }; -DebuggerClient.Argument.prototype.getArgument = function (aParams) { - if (!(this.position in aParams)) { +DebuggerClient.Argument.prototype.getArgument = function (params) { + if (!(this.position in params)) { throw new Error("Bad index into params: " + this.position); } - return aParams[this.position]; + return params[this.position]; }; // Expose these to save callers the trouble of importing DebuggerSocket @@ -320,7 +317,7 @@ DebuggerClient.prototype = { /** * Connect to the server and start exchanging protocol messages. * - * @param aOnConnected function + * @param onConnected function * If specified, will be called when the greeting packet is * received from the debugging server. * @@ -330,7 +327,7 @@ DebuggerClient.prototype = { * element is the traits object (help figure out the features * and behaviors of the server we connect to. See RootActor). */ - connect: function (aOnConnected) { + connect: function (onConnected) { let deferred = promise.defer(); this.emit("connect"); @@ -338,12 +335,12 @@ DebuggerClient.prototype = { // so it's possible to track all instances. events.emit(DebuggerClient, "connect", this); - this.addOneTimeListener("connected", (aName, aApplicationType, aTraits) => { - this.traits = aTraits; - if (aOnConnected) { - aOnConnected(aApplicationType, aTraits); + this.addOneTimeListener("connected", (name, applicationType, traits) => { + this.traits = traits; + if (onConnected) { + onConnected(applicationType, traits); } - deferred.resolve([aApplicationType, aTraits]); + deferred.resolve([applicationType, traits]); }); this._transport.ready(); @@ -353,17 +350,17 @@ DebuggerClient.prototype = { /** * Shut down communication with the debugging server. * - * @param aOnClosed function + * @param onClosed function * If specified, will be called when the debugging connection * has been closed. This parameter is deprecated - please use * the returned Promise. * @return Promise * Resolves after the underlying transport is closed. */ - close: function (aOnClosed) { + close: function (onClosed) { let deferred = promise.defer(); - if (aOnClosed) { - deferred.promise.then(aOnClosed); + if (onClosed) { + deferred.promise.then(onClosed); } // Disable detach event notifications, because event handlers will be in a @@ -413,198 +410,206 @@ DebuggerClient.prototype = { * This function exists only to preserve DebuggerClient's interface; * new code should say 'client.mainRoot.listTabs()'. */ - listTabs: function (aOnResponse) { return this.mainRoot.listTabs(aOnResponse); }, + listTabs: function (onResponse) { + return this.mainRoot.listTabs(onResponse); + }, /* * This function exists only to preserve DebuggerClient's interface; * new code should say 'client.mainRoot.listAddons()'. */ - listAddons: function (aOnResponse) { return this.mainRoot.listAddons(aOnResponse); }, + listAddons: function (onResponse) { + return this.mainRoot.listAddons(onResponse); + }, - getTab: function (aFilter) { return this.mainRoot.getTab(aFilter); }, + getTab: function (filter) { + return this.mainRoot.getTab(filter); + }, /** * Attach to a tab actor. * - * @param string aTabActor + * @param string tabActor * The actor ID for the tab to attach. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a TabClient * (which will be undefined on error). */ - attachTab: function (aTabActor, aOnResponse = noop) { - if (this._clients.has(aTabActor)) { - let cachedTab = this._clients.get(aTabActor); + attachTab: function (tabActor, onResponse = noop) { + if (this._clients.has(tabActor)) { + let cachedTab = this._clients.get(tabActor); let cachedResponse = { cacheDisabled: cachedTab.cacheDisabled, javascriptEnabled: cachedTab.javascriptEnabled, traits: cachedTab.traits, }; - DevToolsUtils.executeSoon(() => aOnResponse(cachedResponse, cachedTab)); + DevToolsUtils.executeSoon(() => onResponse(cachedResponse, cachedTab)); return promise.resolve([cachedResponse, cachedTab]); } let packet = { - to: aTabActor, + to: tabActor, type: "attach" }; - return this.request(packet).then(aResponse => { + return this.request(packet).then(response => { let tabClient; - if (!aResponse.error) { - tabClient = new TabClient(this, aResponse); + if (!response.error) { + tabClient = new TabClient(this, response); this.registerClient(tabClient); } - aOnResponse(aResponse, tabClient); - return [aResponse, tabClient]; + onResponse(response, tabClient); + return [response, tabClient]; }); }, - attachWorker: function DC_attachWorker(aWorkerActor, aOnResponse = noop) { - let workerClient = this._clients.get(aWorkerActor); + attachWorker: function (workerActor, onResponse = noop) { + let workerClient = this._clients.get(workerActor); if (workerClient !== undefined) { let response = { from: workerClient.actor, type: "attached", url: workerClient.url }; - DevToolsUtils.executeSoon(() => aOnResponse(response, workerClient)); + DevToolsUtils.executeSoon(() => onResponse(response, workerClient)); return promise.resolve([response, workerClient]); } - return this.request({ to: aWorkerActor, type: "attach" }).then(aResponse => { - if (aResponse.error) { - aOnResponse(aResponse, null); - return [aResponse, null]; + return this.request({ to: workerActor, type: "attach" }).then(response => { + if (response.error) { + onResponse(response, null); + return [response, null]; } - let workerClient = new WorkerClient(this, aResponse); + workerClient = new WorkerClient(this, response); this.registerClient(workerClient); - aOnResponse(aResponse, workerClient); - return [aResponse, workerClient]; + onResponse(response, workerClient); + return [response, workerClient]; }); }, /** * Attach to an addon actor. * - * @param string aAddonActor + * @param string addonActor * The actor ID for the addon to attach. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a AddonClient * (which will be undefined on error). */ - attachAddon: function DC_attachAddon(aAddonActor, aOnResponse = noop) { + attachAddon: function (addonActor, onResponse = noop) { let packet = { - to: aAddonActor, + to: addonActor, type: "attach" }; - return this.request(packet).then(aResponse => { + return this.request(packet).then(response => { let addonClient; - if (!aResponse.error) { - addonClient = new AddonClient(this, aAddonActor); + if (!response.error) { + addonClient = new AddonClient(this, addonActor); this.registerClient(addonClient); this.activeAddon = addonClient; } - aOnResponse(aResponse, addonClient); - return [aResponse, addonClient]; + onResponse(response, addonClient); + return [response, addonClient]; }); }, /** * Attach to a Web Console actor. * - * @param string aConsoleActor + * @param string consoleActor * The ID for the console actor to attach to. - * @param array aListeners + * @param array listeners * The console listeners you want to start. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a WebConsoleClient * instance (which will be undefined on error). */ attachConsole: - function (aConsoleActor, aListeners, aOnResponse = noop) { + function (consoleActor, listeners, onResponse = noop) { let packet = { - to: aConsoleActor, + to: consoleActor, type: "startListeners", - listeners: aListeners, + listeners: listeners, }; - return this.request(packet).then(aResponse => { + return this.request(packet).then(response => { let consoleClient; - if (!aResponse.error) { - if (this._clients.has(aConsoleActor)) { - consoleClient = this._clients.get(aConsoleActor); + if (!response.error) { + if (this._clients.has(consoleActor)) { + consoleClient = this._clients.get(consoleActor); } else { - consoleClient = new WebConsoleClient(this, aResponse); + consoleClient = new WebConsoleClient(this, response); this.registerClient(consoleClient); } } - aOnResponse(aResponse, consoleClient); - return [aResponse, consoleClient]; + onResponse(response, consoleClient); + return [response, consoleClient]; }); }, /** * Attach to a global-scoped thread actor for chrome debugging. * - * @param string aThreadActor + * @param string threadActor * The actor ID for the thread to attach. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a ThreadClient * (which will be undefined on error). - * @param object aOptions + * @param object options * Configuration options. * - useSourceMaps: whether to use source maps or not. */ - attachThread: function (aThreadActor, aOnResponse = noop, aOptions = {}) { - if (this._clients.has(aThreadActor)) { - let client = this._clients.get(aThreadActor); - DevToolsUtils.executeSoon(() => aOnResponse({}, client)); + attachThread: function (threadActor, onResponse = noop, options = {}) { + if (this._clients.has(threadActor)) { + let client = this._clients.get(threadActor); + DevToolsUtils.executeSoon(() => onResponse({}, client)); return promise.resolve([{}, client]); } let packet = { - to: aThreadActor, + to: threadActor, type: "attach", - options: aOptions + options, }; - return this.request(packet).then(aResponse => { - if (!aResponse.error) { - var threadClient = new ThreadClient(this, aThreadActor); + return this.request(packet).then(response => { + let threadClient; + if (!response.error) { + threadClient = new ThreadClient(this, threadActor); this.registerClient(threadClient); } - aOnResponse(aResponse, threadClient); - return [aResponse, threadClient]; + onResponse(response, threadClient); + return [response, threadClient]; }); }, /** * Attach to a trace actor. * - * @param string aTraceActor + * @param string traceActor * The actor ID for the tracer to attach. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a TraceClient * (which will be undefined on error). */ - attachTracer: function (aTraceActor, aOnResponse = noop) { - if (this._clients.has(aTraceActor)) { - let client = this._clients.get(aTraceActor); - DevToolsUtils.executeSoon(() => aOnResponse({}, client)); + attachTracer: function (traceActor, onResponse = noop) { + if (this._clients.has(traceActor)) { + let client = this._clients.get(traceActor); + DevToolsUtils.executeSoon(() => onResponse({}, client)); return promise.resolve([{}, client]); } let packet = { - to: aTraceActor, + to: traceActor, type: "attach" }; - return this.request(packet).then(aResponse => { - if (!aResponse.error) { - var traceClient = new TraceClient(this, aTraceActor); + return this.request(packet).then(response => { + let traceClient; + if (!response.error) { + traceClient = new TraceClient(this, traceActor); this.registerClient(traceClient); } - aOnResponse(aResponse, traceClient); - return [aResponse, traceClient]; + onResponse(response, traceClient); + return [response, traceClient]; }); }, @@ -612,17 +617,17 @@ DebuggerClient.prototype = { * Fetch the ChromeActor for the main process or ChildProcessActor for a * a given child process ID. * - * @param number aId + * @param number id * The ID for the process to attach (returned by `listProcesses`). * Connected to the main process if omitted, or is 0. */ - getProcess: function (aId) { + getProcess: function (id) { let packet = { to: "root", type: "getProcess" }; - if (typeof (aId) == "number") { - packet.id = aId; + if (typeof (id) == "number") { + packet.id = id; } return this.request(packet); }, @@ -630,23 +635,23 @@ DebuggerClient.prototype = { /** * Release an object actor. * - * @param string aActor + * @param string actor * The actor ID to send the request to. - * @param aOnResponse function + * @param onResponse function * If specified, will be called with the response packet when * debugging server responds. */ release: DebuggerClient.requester({ - to: args(0), + to: arg(0), type: "release" }), /** * Send a request to the debugging server. * - * @param aRequest object + * @param packet object * A JSON packet to send to the debugging server. - * @param aOnResponse function + * @param onResponse function * If specified, will be called with the JSON response packet when * debugging server responds. * @return Request @@ -656,7 +661,7 @@ DebuggerClient.prototype = { * whenever a JSON or a Bulk response is received; and is rejected * if the response is an error. * Note: This return value can be ignored if you are using JSON alone, - * because the callback provided in |aOnResponse| will be bound to the + * because the callback provided in |onResponse| will be bound to the * "json-reply" event automatically. * * Events emitted: @@ -688,30 +693,30 @@ DebuggerClient.prototype = { * This object also emits "progress" events for each chunk * that is copied. See stream-utils.js. */ - request: function (aRequest, aOnResponse) { + request: function (packet, onResponse) { if (!this.mainRoot) { throw Error("Have not yet received a hello packet from the server."); } - let type = aRequest.type || ""; - if (!aRequest.to) { + let type = packet.type || ""; + if (!packet.to) { throw Error("'" + type + "' request packet has no destination."); } if (this._closed) { let msg = "'" + type + "' request packet to " + - "'" + aRequest.to + "' " + + "'" + packet.to + "' " + "can't be sent as the connection is closed."; let resp = { error: "connectionClosed", message: msg }; - if (aOnResponse) { - aOnResponse(resp); + if (onResponse) { + onResponse(resp); } return promise.reject(resp); } - let request = new Request(aRequest); + let request = new Request(packet); request.format = "json"; request.stack = getStack(); - if (aOnResponse) { - request.on("json-reply", aOnResponse); + if (onResponse) { + request.on("json-reply", onResponse); } this._sendOrQueueRequest(request); @@ -861,7 +866,7 @@ DebuggerClient.prototype = { if (request.format === "json") { this._transport.send(request.request); - return false; + return; } this._transport.startBulkSend(request.request).then((...args) => { @@ -899,28 +904,28 @@ DebuggerClient.prototype = { }, /** - * Arrange to hand the next reply from |aActor| to the handler bound to - * |aRequest|. + * Arrange to hand the next reply from |actor| to the handler bound to + * |request|. * * DebuggerClient.prototype.request / startBulkRequest usually takes care of * establishing the handler for a given request, but in rare cases (well, * greetings from new root actors, is the only case at the moment) we must be * prepared for a "reply" that doesn't correspond to any request we sent. */ - expectReply: function (aActor, aRequest) { - if (this._activeRequests.has(aActor)) { - throw Error("clashing handlers for next reply from " + uneval(aActor)); + expectReply: function (actor, request) { + if (this._activeRequests.has(actor)) { + throw Error("clashing handlers for next reply from " + actor); } // If a handler is passed directly (as it is with the handler for the root // actor greeting), create a dummy request to bind this to. - if (typeof aRequest === "function") { - let handler = aRequest; - aRequest = new Request(); - aRequest.on("json-reply", handler); + if (typeof request === "function") { + let handler = request; + request = new Request(); + request.on("json-reply", handler); } - this._activeRequests.set(aActor, aRequest); + this._activeRequests.set(actor, request); }, // Transport hooks. @@ -928,23 +933,23 @@ DebuggerClient.prototype = { /** * Called by DebuggerTransport to dispatch incoming packets as appropriate. * - * @param aPacket object + * @param packet object * The incoming packet. */ - onPacket: function (aPacket) { - if (!aPacket.from) { + onPacket: function (packet) { + if (!packet.from) { DevToolsUtils.reportException( "onPacket", new Error("Server did not specify an actor, dropping packet: " + - JSON.stringify(aPacket))); + JSON.stringify(packet))); return; } // If we have a registered Front for this actor, let it handle the packet // and skip all the rest of this unpleasantness. - let front = this.getActor(aPacket.from); + let front = this.getActor(packet.from); if (front) { - front.onPacket(aPacket); + front.onPacket(packet); return; } @@ -952,17 +957,17 @@ DebuggerClient.prototype = { // This is necessary because we might receive this event while the client is closing, // and the clients have already been removed by that point. if (this.mainRoot && - aPacket.from == this.mainRoot.actor && - aPacket.type == "forwardingCancelled") { - this.purgeRequests(aPacket.prefix); + packet.from == this.mainRoot.actor && + packet.type == "forwardingCancelled") { + this.purgeRequests(packet.prefix); return; } - if (this._clients.has(aPacket.from) && aPacket.type) { - let client = this._clients.get(aPacket.from); - let type = aPacket.type; + if (this._clients.has(packet.from) && packet.type) { + let client = this._clients.get(packet.from); + let type = packet.type; if (client.events.indexOf(type) != -1) { - client.emit(type, aPacket); + client.emit(type, packet); // we ignore the rest, as the client is expected to handle this packet. return; } @@ -972,24 +977,24 @@ DebuggerClient.prototype = { // See if we have a handler function waiting for a reply from this // actor. (Don't count unsolicited notifications or pauses as // replies.) - if (this._activeRequests.has(aPacket.from) && - !(aPacket.type in UnsolicitedNotifications) && - !(aPacket.type == ThreadStateTypes.paused && - aPacket.why.type in UnsolicitedPauses)) { - activeRequest = this._activeRequests.get(aPacket.from); - this._activeRequests.delete(aPacket.from); + if (this._activeRequests.has(packet.from) && + !(packet.type in UnsolicitedNotifications) && + !(packet.type == ThreadStateTypes.paused && + packet.why.type in UnsolicitedPauses)) { + activeRequest = this._activeRequests.get(packet.from); + this._activeRequests.delete(packet.from); } // If there is a subsequent request for the same actor, hand it off to the // transport. Delivery of packets on the other end is always async, even // in the local transport case. - this._attemptNextRequest(aPacket.from); + this._attemptNextRequest(packet.from); // Packets that indicate thread state changes get special treatment. - if (aPacket.type in ThreadStateTypes && - this._clients.has(aPacket.from) && - typeof this._clients.get(aPacket.from)._onThreadState == "function") { - this._clients.get(aPacket.from)._onThreadState(aPacket); + if (packet.type in ThreadStateTypes && + this._clients.has(packet.from) && + typeof this._clients.get(packet.from)._onThreadState == "function") { + this._clients.get(packet.from)._onThreadState(packet); } // TODO: Bug 1151156 - Remove once Gecko 40 is on b2g-stable. @@ -997,10 +1002,10 @@ DebuggerClient.prototype = { // On navigation the server resumes, so the client must resume as well. // We achieve that by generating a fake resumption packet that triggers // the client's thread state change listeners. - if (aPacket.type == UnsolicitedNotifications.tabNavigated && - this._clients.has(aPacket.from) && - this._clients.get(aPacket.from).thread) { - let thread = this._clients.get(aPacket.from).thread; + if (packet.type == UnsolicitedNotifications.tabNavigated && + this._clients.has(packet.from) && + this._clients.get(packet.from).thread) { + let thread = this._clients.get(packet.from).thread; let resumption = { from: thread._actor, type: "resumed" }; thread._onThreadState(resumption); } @@ -1008,12 +1013,12 @@ DebuggerClient.prototype = { // Only try to notify listeners on events, not responses to requests // that lack a packet type. - if (aPacket.type) { - this.emit(aPacket.type, aPacket); + if (packet.type) { + this.emit(packet.type, packet); } if (activeRequest) { - let emitReply = () => activeRequest.emit("json-reply", aPacket); + let emitReply = () => activeRequest.emit("json-reply", packet); if (activeRequest.stack) { callFunctionWithAsyncStack(emitReply, activeRequest.stack, "DevTools RDP"); @@ -1054,7 +1059,7 @@ DebuggerClient.prototype = { * that is copied. See stream-utils.js. */ onBulkPacket: function (packet) { - let { actor, type, length } = packet; + let { actor } = packet; if (!actor) { DevToolsUtils.reportException( @@ -1084,7 +1089,7 @@ DebuggerClient.prototype = { /** * Called by DebuggerTransport when the underlying stream is closed. * - * @param aStatus nsresult + * @param status nsresult * The status code that corresponds to the reason for closing * the stream. */ @@ -1280,7 +1285,9 @@ DebuggerClient.prototype = { poolFor: function (actorID) { for (let pool of this._pools) { - if (pool.has(actorID)) return pool; + if (pool.has(actorID)) { + return pool; + } } return null; }, @@ -1315,7 +1322,9 @@ Request.prototype = { events.emit(this, type, ...args); }, - get actor() { return this.request.to || this.request.actor; } + get actor() { + return this.request.to || this.request.actor; + } }; @@ -1324,76 +1333,80 @@ Request.prototype = { * is a front to the tab actor created in the server side, hiding the protocol * details in a traditional JavaScript API. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aForm object + * @param form object * The protocol form for this tab. */ -function TabClient(aClient, aForm) { - this.client = aClient; - this._actor = aForm.from; - this._threadActor = aForm.threadActor; - this.javascriptEnabled = aForm.javascriptEnabled; - this.cacheDisabled = aForm.cacheDisabled; +function TabClient(client, form) { + this.client = client; + this._actor = form.from; + this._threadActor = form.threadActor; + this.javascriptEnabled = form.javascriptEnabled; + this.cacheDisabled = form.cacheDisabled; this.thread = null; this.request = this.client.request; - this.traits = aForm.traits || {}; + this.traits = form.traits || {}; this.events = ["workerListChanged"]; } TabClient.prototype = { - get actor() { return this._actor; }, - get _transport() { return this.client._transport; }, + get actor() { + return this._actor; + }, + get _transport() { + return this.client._transport; + }, /** * Attach to a thread actor. * - * @param object aOptions + * @param object options * Configuration options. * - useSourceMaps: whether to use source maps or not. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a ThreadClient * (which will be undefined on error). */ - attachThread: function (aOptions = {}, aOnResponse = noop) { + attachThread: function (options = {}, onResponse = noop) { if (this.thread) { - DevToolsUtils.executeSoon(() => aOnResponse({}, this.thread)); + DevToolsUtils.executeSoon(() => onResponse({}, this.thread)); return promise.resolve([{}, this.thread]); } let packet = { to: this._threadActor, type: "attach", - options: aOptions + options, }; - return this.request(packet).then(aResponse => { - if (!aResponse.error) { + return this.request(packet).then(response => { + if (!response.error) { this.thread = new ThreadClient(this, this._threadActor); this.client.registerClient(this.thread); } - aOnResponse(aResponse, this.thread); - return [aResponse, this.thread]; + onResponse(response, this.thread); + return [response, this.thread]; }); }, /** * Detach the client from the tab actor. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - before: function (aPacket) { + before: function (packet) { if (this.thread) { this.thread.detach(); } - return aPacket; + return packet; }, - after: function (aResponse) { + after: function (response) { this.client.unregisterClient(this); - return aResponse; + return response; }, }), @@ -1416,7 +1429,7 @@ TabClient.prototype = { }, _reload: DebuggerClient.requester({ type: "reload", - options: args(0) + options: arg(0) }), /** @@ -1427,28 +1440,28 @@ TabClient.prototype = { */ navigateTo: DebuggerClient.requester({ type: "navigateTo", - url: args(0) + url: arg(0) }), /** * Reconfigure the tab actor. * - * @param object aOptions + * @param object options * A dictionary object of the new options to use in the tab actor. - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ reconfigure: DebuggerClient.requester({ type: "reconfigure", - options: args(0) + options: arg(0) }), listWorkers: DebuggerClient.requester({ type: "listWorkers" }), - attachWorker: function (aWorkerActor, aOnResponse) { - this.client.attachWorker(aWorkerActor, aOnResponse); + attachWorker: function (workerActor, onResponse) { + this.client.attachWorker(workerActor, onResponse); }, /** @@ -1461,17 +1474,17 @@ TabClient.prototype = { */ resolveLocation: DebuggerClient.requester({ type: "resolveLocation", - location: args(0) + location: arg(0) }), }; eventSource(TabClient.prototype); -function WorkerClient(aClient, aForm) { - this.client = aClient; - this._actor = aForm.from; +function WorkerClient(client, form) { + this.client = client; + this._actor = form.from; this._isClosed = false; - this._url = aForm.url; + this._url = form.url; this._onClose = this._onClose.bind(this); @@ -1502,23 +1515,23 @@ WorkerClient.prototype = { }, detach: DebuggerClient.requester({ type: "detach" }, { - after: function (aResponse) { + after: function (response) { if (this.thread) { this.client.unregisterClient(this.thread); } this.client.unregisterClient(this); - return aResponse; + return response; }, }), - attachThread: function (aOptions = {}, aOnResponse = noop) { + attachThread: function (options = {}, onResponse = noop) { if (this.thread) { let response = [{ type: "connected", threadActor: this.thread._actor, consoleActor: this.consoleActor, }, this.thread]; - DevToolsUtils.executeSoon(() => aOnResponse(response)); + DevToolsUtils.executeSoon(() => onResponse(response)); return response; } @@ -1526,31 +1539,31 @@ WorkerClient.prototype = { return this.request({ to: this._actor, type: "connect", - options: aOptions, - }).then(connectReponse => { - if (connectReponse.error) { - aOnResponse(connectReponse, null); + options, + }).then(connectResponse => { + if (connectResponse.error) { + onResponse(connectResponse, null); return [connectResponse, null]; } return this.request({ - to: connectReponse.threadActor, + to: connectResponse.threadActor, type: "attach", - options: aOptions + options, }).then(attachResponse => { if (attachResponse.error) { - aOnResponse(attachResponse, null); + onResponse(attachResponse, null); } - this.thread = new ThreadClient(this, connectReponse.threadActor); - this.consoleActor = connectReponse.consoleActor; + this.thread = new ThreadClient(this, connectResponse.threadActor); + this.consoleActor = connectResponse.consoleActor; this.client.registerClient(this.thread); - aOnResponse(connectReponse, this.thread); + onResponse(connectResponse, this.thread); return [connectResponse, this.thread]; }); }, error => { - aOnResponse(error, null); + onResponse(error, null); }); }, @@ -1573,32 +1586,36 @@ WorkerClient.prototype = { eventSource(WorkerClient.prototype); -function AddonClient(aClient, aActor) { - this._client = aClient; - this._actor = aActor; +function AddonClient(client, actor) { + this._client = client; + this._actor = actor; this.request = this._client.request; this.events = []; } AddonClient.prototype = { - get actor() { return this._actor; }, - get _transport() { return this._client._transport; }, + get actor() { + return this._actor; + }, + get _transport() { + return this._client._transport; + }, /** * Detach the client from the addon actor. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - after: function (aResponse) { + after: function (response) { if (this._client.activeAddon === this) { this._client.activeAddon = null; } this._client.unregisterClient(this); - return aResponse; + return response; }, }) }; @@ -1609,9 +1626,9 @@ AddonClient.prototype = { * for the initial connection; DebuggerClient's 'listTabs' and * 'listChildProcesses' methods forward to that root actor. * - * @param aClient object + * @param client object * The client connection to which this actor belongs. - * @param aGreeting string + * @param greeting string * The greeting packet from the root actor we're to represent. * * Properties of a RootClient instance: @@ -1623,11 +1640,11 @@ AddonClient.prototype = { * @property traits object * The traits object, as given in the root actor's greeting packet. */ -function RootClient(aClient, aGreeting) { - this._client = aClient; - this.actor = aGreeting.from; - this.applicationType = aGreeting.applicationType; - this.traits = aGreeting.traits; +function RootClient(client, greeting) { + this._client = client; + this.actor = greeting.from; + this.applicationType = greeting.applicationType; + this.traits = greeting.traits; } exports.RootClient = RootClient; @@ -1637,7 +1654,7 @@ RootClient.prototype = { /** * List the open tabs. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listTabs: DebuggerClient.requester({ type: "listTabs" }), @@ -1645,7 +1662,7 @@ RootClient.prototype = { /** * List the installed addons. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listAddons: DebuggerClient.requester({ type: "listAddons" }), @@ -1653,7 +1670,7 @@ RootClient.prototype = { /** * List the registered workers. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listWorkers: DebuggerClient.requester({ type: "listWorkers" }), @@ -1661,7 +1678,7 @@ RootClient.prototype = { /** * List the registered service workers. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listServiceWorkerRegistrations: DebuggerClient.requester({ @@ -1671,7 +1688,7 @@ RootClient.prototype = { /** * List the running processes. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listProcesses: DebuggerClient.requester({ type: "listProcesses" }), @@ -1680,7 +1697,7 @@ RootClient.prototype = { * Fetch the TabActor for the currently selected tab, or for a specific * tab given as first parameter. * - * @param [optional] object aFilter + * @param [optional] object filter * A dictionary object with following optional attributes: * - outerWindowID: used to match tabs in parent process * - tabId: used to match tabs in child processes @@ -1688,19 +1705,19 @@ RootClient.prototype = { * If nothing is specified, returns the actor for the currently * selected tab. */ - getTab: function (aFilter) { + getTab: function (filter) { let packet = { to: this.actor, type: "getTab" }; - if (aFilter) { - if (typeof (aFilter.outerWindowID) == "number") { - packet.outerWindowID = aFilter.outerWindowID; - } else if (typeof (aFilter.tabId) == "number") { - packet.tabId = aFilter.tabId; - } else if ("tab" in aFilter) { - let browser = aFilter.tab.linkedBrowser; + if (filter) { + if (typeof (filter.outerWindowID) == "number") { + packet.outerWindowID = filter.outerWindowID; + } else if (typeof (filter.tabId) == "number") { + packet.tabId = filter.tabId; + } else if ("tab" in filter) { + let browser = filter.tab.linkedBrowser; if (browser.frameLoader.tabParent) { // Tabs in child process packet.tabId = browser.frameLoader.tabParent.tabId; @@ -1727,7 +1744,7 @@ RootClient.prototype = { /** * Description of protocol's actors and methods. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ protocolDescription: DebuggerClient.requester({ type: "protocolDescription" }), @@ -1736,8 +1753,12 @@ RootClient.prototype = { * Methods constructed by DebuggerClient.requester require these forwards * on their 'this'. */ - get _transport() { return this._client._transport; }, - get request() { return this._client.request; } + get _transport() { + return this._client._transport; + }, + get request() { + return this._client.request; + } }; /** @@ -1745,16 +1766,16 @@ RootClient.prototype = { * is a front to the thread actor created in the server side, hiding the * protocol details in a traditional JavaScript API. * - * @param aClient DebuggerClient|TabClient + * @param client DebuggerClient|TabClient * The parent of the thread (tab for tab-scoped debuggers, DebuggerClient * for chrome debuggers). - * @param aActor string + * @param actor string * The actor ID for this thread. */ -function ThreadClient(aClient, aActor) { - this._parent = aClient; - this.client = aClient instanceof DebuggerClient ? aClient : aClient.client; - this._actor = aActor; +function ThreadClient(client, actor) { + this._parent = client; + this.client = client instanceof DebuggerClient ? client : client.client; + this._actor = actor; this._frameCache = []; this._scriptCache = {}; this._pauseGrips = {}; @@ -1764,40 +1785,48 @@ function ThreadClient(aClient, aActor) { ThreadClient.prototype = { _state: "paused", - get state() { return this._state; }, - get paused() { return this._state === "paused"; }, + get state() { + return this._state; + }, + get paused() { + return this._state === "paused"; + }, _pauseOnExceptions: false, _ignoreCaughtExceptions: false, _pauseOnDOMEvents: null, _actor: null, - get actor() { return this._actor; }, + get actor() { + return this._actor; + }, - get _transport() { return this.client._transport; }, + get _transport() { + return this.client._transport; + }, - _assertPaused: function (aCommand) { + _assertPaused: function (command) { if (!this.paused) { - throw Error(aCommand + " command sent while not paused. Currently " + this._state); + throw Error(command + " command sent while not paused. Currently " + this._state); } }, /** - * Resume a paused thread. If the optional aLimit parameter is present, then + * Resume a paused thread. If the optional limit parameter is present, then * the thread will also pause when that limit is reached. * - * @param [optional] object aLimit + * @param [optional] object limit * An object with a type property set to the appropriate limit (next, * step, or finish) per the remote debugging protocol specification. * Use null to specify no limit. - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ _doResume: DebuggerClient.requester({ type: "resume", - resumeLimit: args(0) + resumeLimit: arg(0) }, { - before: function (aPacket) { + before: function (packet) { this._assertPaused("resume"); // Put the client in a tentative "resuming" state so we can prevent @@ -1806,150 +1835,152 @@ ThreadClient.prototype = { this._state = "resuming"; if (this._pauseOnExceptions) { - aPacket.pauseOnExceptions = this._pauseOnExceptions; + packet.pauseOnExceptions = this._pauseOnExceptions; } if (this._ignoreCaughtExceptions) { - aPacket.ignoreCaughtExceptions = this._ignoreCaughtExceptions; + packet.ignoreCaughtExceptions = this._ignoreCaughtExceptions; } if (this._pauseOnDOMEvents) { - aPacket.pauseOnDOMEvents = this._pauseOnDOMEvents; + packet.pauseOnDOMEvents = this._pauseOnDOMEvents; } - return aPacket; + return packet; }, - after: function (aResponse) { - if (aResponse.error && this._state == "resuming") { + after: function (response) { + if (response.error && this._state == "resuming") { // There was an error resuming, update the state to the new one // reported by the server, if given (only on wrongState), otherwise // reset back to the previous state. - if (aResponse.state) { - this._state = ThreadStateTypes[aResponse.state]; + if (response.state) { + this._state = ThreadStateTypes[response.state]; } else { this._state = this._previousState; } } delete this._previousState; - return aResponse; + return response; }, }), /** * Reconfigure the thread actor. * - * @param object aOptions + * @param object options * A dictionary object of the new options to use in the thread actor. - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ reconfigure: DebuggerClient.requester({ type: "reconfigure", - options: args(0) + options: arg(0) }), /** * Resume a paused thread. */ - resume: function (aOnResponse) { - return this._doResume(null, aOnResponse); + resume: function (onResponse) { + return this._doResume(null, onResponse); }, /** * Resume then pause without stepping. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - resumeThenPause: function (aOnResponse) { - return this._doResume({ type: "break" }, aOnResponse); + resumeThenPause: function (onResponse) { + return this._doResume({ type: "break" }, onResponse); }, /** * Step over a function call. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - stepOver: function (aOnResponse) { - return this._doResume({ type: "next" }, aOnResponse); + stepOver: function (onResponse) { + return this._doResume({ type: "next" }, onResponse); }, /** * Step into a function call. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - stepIn: function (aOnResponse) { - return this._doResume({ type: "step" }, aOnResponse); + stepIn: function (onResponse) { + return this._doResume({ type: "step" }, onResponse); }, /** * Step out of a function call. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - stepOut: function (aOnResponse) { - return this._doResume({ type: "finish" }, aOnResponse); + stepOut: function (onResponse) { + return this._doResume({ type: "finish" }, onResponse); }, /** * Immediately interrupt a running thread. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - interrupt: function (aOnResponse) { - return this._doInterrupt(null, aOnResponse); + interrupt: function (onResponse) { + return this._doInterrupt(null, onResponse); }, /** * Pause execution right before the next JavaScript bytecode is executed. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - breakOnNext: function (aOnResponse) { - return this._doInterrupt("onNext", aOnResponse); + breakOnNext: function (onResponse) { + return this._doInterrupt("onNext", onResponse); }, /** * Interrupt a running thread. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ _doInterrupt: DebuggerClient.requester({ type: "interrupt", - when: args(0) + when: arg(0) }), /** * Enable or disable pausing when an exception is thrown. * - * @param boolean aFlag + * @param boolean pauseOnExceptions * Enables pausing if true, disables otherwise. - * @param function aOnResponse + * @param boolean ignoreCaughtExceptions + * Whether to ignore caught exceptions + * @param function onResponse * Called with the response packet. */ - pauseOnExceptions: function (aPauseOnExceptions, - aIgnoreCaughtExceptions, - aOnResponse = noop) { - this._pauseOnExceptions = aPauseOnExceptions; - this._ignoreCaughtExceptions = aIgnoreCaughtExceptions; + pauseOnExceptions: function (pauseOnExceptions, + ignoreCaughtExceptions, + onResponse = noop) { + this._pauseOnExceptions = pauseOnExceptions; + this._ignoreCaughtExceptions = ignoreCaughtExceptions; // Otherwise send the flag using a standard resume request. if (!this.paused) { - return this.interrupt(aResponse => { - if (aResponse.error) { + return this.interrupt(response => { + if (response.error) { // Can't continue if pausing failed. - aOnResponse(aResponse); - return aResponse; + onResponse(response); + return response; } - return this.resume(aOnResponse); + return this.resume(onResponse); }); } - aOnResponse(); + onResponse(); return promise.resolve(); }, @@ -1988,48 +2019,48 @@ ThreadClient.prototype = { * Send a clientEvaluate packet to the debuggee. Response * will be a resume packet. * - * @param string aFrame + * @param string frame * The actor ID of the frame where the evaluation should take place. - * @param string aExpression + * @param string expression * The expression that will be evaluated in the scope of the frame * above. - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ eval: DebuggerClient.requester({ type: "clientEvaluate", - frame: args(0), - expression: args(1) + frame: arg(0), + expression: arg(1) }, { - before: function (aPacket) { + before: function (packet) { this._assertPaused("eval"); // Put the client in a tentative "resuming" state so we can prevent // further requests that should only be sent in the paused state. this._state = "resuming"; - return aPacket; + return packet; }, - after: function (aResponse) { - if (aResponse.error) { + after: function (response) { + if (response.error) { // There was an error resuming, back to paused state. this._state = "paused"; } - return aResponse; + return response; }, }), /** * Detach from the thread actor. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - after: function (aResponse) { + after: function (response) { this.client.unregisterClient(this); this._parent.thread = null; - return aResponse; + return response; }, }), @@ -2043,7 +2074,7 @@ ThreadClient.prototype = { */ releaseMany: DebuggerClient.requester({ type: "releaseMany", - actors: args(0), + actors: arg(0), }), /** @@ -2054,13 +2085,13 @@ ThreadClient.prototype = { */ threadGrips: DebuggerClient.requester({ type: "threadGrips", - actors: args(0) + actors: arg(0) }), /** * Return the event listeners defined on the page. * - * @param aOnResponse Function + * @param onResponse Function * Called with the thread's response. */ eventListeners: DebuggerClient.requester({ @@ -2070,7 +2101,7 @@ ThreadClient.prototype = { /** * Request the loaded sources for the current thread. * - * @param aOnResponse Function + * @param onResponse Function * Called with the thread's response. */ getSources: DebuggerClient.requester({ @@ -2091,19 +2122,19 @@ ThreadClient.prototype = { /** * Request frames from the callstack for the current thread. * - * @param aStart integer + * @param start integer * The number of the youngest stack frame to return (the youngest * frame is 0). - * @param aCount integer + * @param count integer * The maximum number of frames to return, or null to return all * frames. - * @param aOnResponse function + * @param onResponse function * Called with the thread's response. */ getFrames: DebuggerClient.requester({ type: "frames", - start: args(0), - count: args(1) + start: arg(0), + count: arg(1) }), /** @@ -2111,7 +2142,9 @@ ThreadClient.prototype = { * framescleared event to keep up to date on changes to this cache, * and can fill it using the fillFrames method. */ - get cachedFrames() { return this._frameCache; }, + get cachedFrames() { + return this._frameCache; + }, /** * true if there are more stack frames available on the server. @@ -2122,34 +2155,34 @@ ThreadClient.prototype = { }, /** - * Ensure that at least aTotal stack frames have been loaded in the + * Ensure that at least total stack frames have been loaded in the * ThreadClient's stack frame cache. A framesadded event will be * sent when the stack frame cache is updated. * - * @param aTotal number + * @param total number * The minimum number of stack frames to be included. - * @param aCallback function + * @param callback function * Optional callback function called when frames have been loaded * @returns true if a framesadded notification should be expected. */ - fillFrames: function (aTotal, aCallback = noop) { + fillFrames: function (total, callback = noop) { this._assertPaused("fillFrames"); - if (this._frameCache.length >= aTotal) { + if (this._frameCache.length >= total) { return false; } let numFrames = this._frameCache.length; - this.getFrames(numFrames, aTotal - numFrames, (aResponse) => { - if (aResponse.error) { - aCallback(aResponse); + this.getFrames(numFrames, total - numFrames, (response) => { + if (response.error) { + callback(response); return; } let threadGrips = DevToolsUtils.values(this._threadGrips); - for (let i in aResponse.frames) { - let frame = aResponse.frames[i]; + for (let i in response.frames) { + let frame = response.frames[i]; if (!frame.where.source) { // Older servers use urls instead, so we need to resolve // them to source actors @@ -2167,7 +2200,7 @@ ThreadClient.prototype = { // frames available. this.emit("framesadded"); - aCallback(aResponse); + callback(response); }); return true; @@ -2187,16 +2220,16 @@ ThreadClient.prototype = { /** * Return a ObjectClient object for the given object grip. * - * @param aGrip object + * @param grip object * A pause-lifetime object grip returned by the protocol. */ - pauseGrip: function (aGrip) { - if (aGrip.actor in this._pauseGrips) { - return this._pauseGrips[aGrip.actor]; + pauseGrip: function (grip) { + if (grip.actor in this._pauseGrips) { + return this._pauseGrips[grip.actor]; } - let client = new ObjectClient(this.client, aGrip); - this._pauseGrips[aGrip.actor] = client; + let client = new ObjectClient(this.client, grip); + this._pauseGrips[grip.actor] = client; return client; }, @@ -2204,19 +2237,19 @@ ThreadClient.prototype = { * Get or create a long string client, checking the grip client cache if it * already exists. * - * @param aGrip Object + * @param grip Object * The long string grip returned by the protocol. - * @param aGripCacheName String + * @param gripCacheName String * The property name of the grip client cache to check for existing * clients in. */ - _longString: function (aGrip, aGripCacheName) { - if (aGrip.actor in this[aGripCacheName]) { - return this[aGripCacheName][aGrip.actor]; + _longString: function (grip, gripCacheName) { + if (grip.actor in this[gripCacheName]) { + return this[gripCacheName][grip.actor]; } - let client = new LongStringClient(this.client, aGrip); - this[aGripCacheName][aGrip.actor] = client; + let client = new LongStringClient(this.client, grip); + this[gripCacheName][grip.actor] = client; return client; }, @@ -2224,35 +2257,35 @@ ThreadClient.prototype = { * Return an instance of LongStringClient for the given long string grip that * is scoped to the current pause. * - * @param aGrip Object + * @param grip Object * The long string grip returned by the protocol. */ - pauseLongString: function (aGrip) { - return this._longString(aGrip, "_pauseGrips"); + pauseLongString: function (grip) { + return this._longString(grip, "_pauseGrips"); }, /** * Return an instance of LongStringClient for the given long string grip that * is scoped to the thread lifetime. * - * @param aGrip Object + * @param grip Object * The long string grip returned by the protocol. */ - threadLongString: function (aGrip) { - return this._longString(aGrip, "_threadGrips"); + threadLongString: function (grip) { + return this._longString(grip, "_threadGrips"); }, /** * Clear and invalidate all the grip clients from the given cache. * - * @param aGripCacheName + * @param gripCacheName * The property name of the grip cache we want to clear. */ - _clearObjectClients: function (aGripCacheName) { - for (let id in this[aGripCacheName]) { - this[aGripCacheName][id].valid = false; + _clearObjectClients: function (gripCacheName) { + for (let id in this[gripCacheName]) { + this[gripCacheName][id].valid = false; } - this[aGripCacheName] = {}; + this[gripCacheName] = {}; }, /** @@ -2275,16 +2308,16 @@ ThreadClient.prototype = { * Handle thread state change by doing necessary cleanup and notifying all * registered listeners. */ - _onThreadState: function (aPacket) { - this._state = ThreadStateTypes[aPacket.type]; + _onThreadState: function (packet) { + this._state = ThreadStateTypes[packet.type]; // The debugger UI may not be initialized yet so we want to keep // the packet around so it knows what to pause state to display // when it's initialized - this._lastPausePacket = aPacket.type === "resumed" ? null : aPacket; + this._lastPausePacket = packet.type === "resumed" ? null : packet; this._clearFrames(); this._clearPauseGrips(); - aPacket.type === ThreadStateTypes.detached && this._clearThreadGrips(); - this.client._eventsEnabled && this.emit(aPacket.type, aPacket); + packet.type === ThreadStateTypes.detached && this._clearThreadGrips(); + this.client._eventsEnabled && this.emit(packet.type, packet); }, getLastPausePacket: function () { @@ -2294,32 +2327,33 @@ ThreadClient.prototype = { /** * Return an EnvironmentClient instance for the given environment actor form. */ - environment: function (aForm) { - return new EnvironmentClient(this.client, aForm); + environment: function (form) { + return new EnvironmentClient(this.client, form); }, /** * Return an instance of SourceClient for the given source actor form. */ - source: function (aForm) { - if (aForm.actor in this._threadGrips) { - return this._threadGrips[aForm.actor]; + source: function (form) { + if (form.actor in this._threadGrips) { + return this._threadGrips[form.actor]; } - return this._threadGrips[aForm.actor] = new SourceClient(this, aForm); + this._threadGrips[form.actor] = new SourceClient(this, form); + return this._threadGrips[form.actor]; }, /** * Request the prototype and own properties of mutlipleObjects. * - * @param aOnResponse function + * @param onResponse function * Called with the request's response. * @param actors [string] * List of actor ID of the queried objects. */ getPrototypesAndProperties: DebuggerClient.requester({ type: "prototypesAndProperties", - actors: args(0) + actors: arg(0) }), events: ["newSource"] @@ -2333,14 +2367,14 @@ eventSource(ThreadClient.prototype); * server side, hiding the protocol details in a traditional * JavaScript API. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aActor string + * @param actor string * The actor ID for this thread. */ -function TraceClient(aClient, aActor) { - this._client = aClient; - this._actor = aActor; +function TraceClient(client, actor) { + this._client = client; + this._actor = actor; this._activeTraces = new Set(); this._waitingPackets = new Map(); this._expectedPacket = 0; @@ -2349,10 +2383,16 @@ function TraceClient(aClient, aActor) { } TraceClient.prototype = { - get actor() { return this._actor; }, - get tracing() { return this._activeTraces.size > 0; }, + get actor() { + return this._actor; + }, + get tracing() { + return this._activeTraces.size > 0; + }, - get _transport() { return this._client._transport; }, + get _transport() { + return this._client._transport; + }, /** * Detach from the trace actor. @@ -2360,41 +2400,41 @@ TraceClient.prototype = { detach: DebuggerClient.requester({ type: "detach" }, { - after: function (aResponse) { + after: function (response) { this._client.unregisterClient(this); - return aResponse; + return response; }, }), /** * Start a new trace. * - * @param aTrace [string] + * @param trace [string] * An array of trace types to be recorded by the new trace. * - * @param aName string + * @param name string * The name of the new trace. * - * @param aOnResponse function + * @param onResponse function * Called with the request's response. */ startTrace: DebuggerClient.requester({ type: "startTrace", - name: args(1), - trace: args(0) + name: arg(1), + trace: arg(0) }, { - after: function (aResponse) { - if (aResponse.error) { - return aResponse; + after: function (response) { + if (response.error) { + return response; } if (!this.tracing) { this._waitingPackets.clear(); this._expectedPacket = 0; } - this._activeTraces.add(aResponse.name); + this._activeTraces.add(response.name); - return aResponse; + return response; }, }), @@ -2402,24 +2442,24 @@ TraceClient.prototype = { * End a trace. If a name is provided, stop the named * trace. Otherwise, stop the most recently started trace. * - * @param aName string + * @param name string * The name of the trace to stop. * - * @param aOnResponse function + * @param onResponse function * Called with the request's response. */ stopTrace: DebuggerClient.requester({ type: "stopTrace", - name: args(0) + name: arg(0) }, { - after: function (aResponse) { - if (aResponse.error) { - return aResponse; + after: function (response) { + if (response.error) { + return response; } - this._activeTraces.delete(aResponse.name); + this._activeTraces.delete(response.name); - return aResponse; + return response; }, }) }; @@ -2427,22 +2467,25 @@ TraceClient.prototype = { /** * Grip clients are used to retrieve information about the relevant object. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aGrip object + * @param grip object * A pause-lifetime object grip returned by the protocol. */ -function ObjectClient(aClient, aGrip) -{ - this._grip = aGrip; - this._client = aClient; +function ObjectClient(client, grip) { + this._grip = grip; + this._client = client; this.request = this._client.request; } exports.ObjectClient = ObjectClient; ObjectClient.prototype = { - get actor() { return this._grip.actor; }, - get _transport() { return this._client._transport; }, + get actor() { + return this._grip.actor; + }, + get _transport() { + return this._client._transport; + }, valid: true, @@ -2459,18 +2502,18 @@ ObjectClient.prototype = { getDefinitionSite: DebuggerClient.requester({ type: "definitionSite" }, { - before: function (aPacket) { + before: function (packet) { if (this._grip.class != "Function") { throw new Error("getDefinitionSite is only valid for function grips."); } - return aPacket; + return packet; } }), /** * Request the names of a function's formal parameters. * - * @param aOnResponse function + * @param onResponse function * Called with an object of the form: * { parameterNames:[, ...] } * where each is the name of a parameter. @@ -2478,11 +2521,11 @@ ObjectClient.prototype = { getParameterNames: DebuggerClient.requester({ type: "parameterNames" }, { - before: function (aPacket) { - if (this._grip["class"] !== "Function") { + before: function (packet) { + if (this._grip.class !== "Function") { throw new Error("getParameterNames is only valid for function grips."); } - return aPacket; + return packet; }, }), @@ -2490,7 +2533,7 @@ ObjectClient.prototype = { * Request the names of the properties defined on the object and not its * prototype. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getOwnPropertyNames: DebuggerClient.requester({ type: "ownPropertyNames" @@ -2499,7 +2542,7 @@ ObjectClient.prototype = { /** * Request the prototype and own properties of the object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getPrototypeAndProperties: DebuggerClient.requester({ type: "prototypeAndProperties" @@ -2521,17 +2564,17 @@ ObjectClient.prototype = { * - sort Boolean * If true, the iterator will sort the properties by name * before dispatching them. - * @param aOnResponse function Called with the client instance. + * @param onResponse function Called with the client instance. */ enumProperties: DebuggerClient.requester({ type: "enumProperties", - options: args(0) + options: arg(0) }, { - after: function (aResponse) { - if (aResponse.iterator) { - return { iterator: new PropertyIteratorClient(this._client, aResponse.iterator) }; + after: function (response) { + if (response.iterator) { + return { iterator: new PropertyIteratorClient(this._client, response.iterator) }; } - return aResponse; + return response; }, }), @@ -2539,7 +2582,7 @@ ObjectClient.prototype = { * Request a PropertyIteratorClient instance to enumerate entries in a * Map/Set-like object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ enumEntries: DebuggerClient.requester({ type: "enumEntries" @@ -2563,18 +2606,18 @@ ObjectClient.prototype = { /** * Request the property descriptor of the object's specified property. * - * @param aName string The name of the requested property. - * @param aOnResponse function Called with the request's response. + * @param name string The name of the requested property. + * @param onResponse function Called with the request's response. */ getProperty: DebuggerClient.requester({ type: "property", - name: args(0) + name: arg(0) }), /** * Request the prototype of the object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getPrototype: DebuggerClient.requester({ type: "prototype" @@ -2583,7 +2626,7 @@ ObjectClient.prototype = { /** * Request the display string of the object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getDisplayString: DebuggerClient.requester({ type: "displayString" @@ -2592,16 +2635,16 @@ ObjectClient.prototype = { /** * Request the scope of the object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getScope: DebuggerClient.requester({ type: "scope" }, { - before: function (aPacket) { + before: function (packet) { if (this._grip.class !== "Function") { throw new Error("scope is only valid for function grips."); } - return aPacket; + return packet; }, }), @@ -2611,12 +2654,12 @@ ObjectClient.prototype = { getDependentPromises: DebuggerClient.requester({ type: "dependentPromises" }, { - before: function (aPacket) { + before: function (packet) { if (this._grip.class !== "Promise") { throw new Error("getDependentPromises is only valid for promise " + "grips."); } - return aPacket; + return packet; } }), @@ -2626,11 +2669,11 @@ ObjectClient.prototype = { getPromiseAllocationStack: DebuggerClient.requester({ type: "allocationStack" }, { - before: function (aPacket) { + before: function (packet) { if (this._grip.class !== "Promise") { throw new Error("getAllocationStack is only valid for promise grips."); } - return aPacket; + return packet; } }), @@ -2672,25 +2715,29 @@ ObjectClient.prototype = { * this is controled while creating the PropertyIteratorClient * from ObjectClient.enumProperties. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aGrip Object + * @param grip Object * A PropertyIteratorActor grip returned by the protocol via * TabActor.enumProperties request. */ -function PropertyIteratorClient(aClient, aGrip) { - this._grip = aGrip; - this._client = aClient; +function PropertyIteratorClient(client, grip) { + this._grip = grip; + this._client = client; this.request = this._client.request; } PropertyIteratorClient.prototype = { - get actor() { return this._grip.actor; }, + get actor() { + return this._grip.actor; + }, /** * Get the total number of properties available in the iterator. */ - get count() { return this._grip.count; }, + get count() { + return this._grip.count; + }, /** * Get one or more property names that correspond to the positions in the @@ -2698,12 +2745,12 @@ PropertyIteratorClient.prototype = { * * @param indexes Array * An array of property indexes. - * @param aCallback Function + * @param callback Function * The function called when we receive the property names. */ names: DebuggerClient.requester({ type: "names", - indexes: args(0) + indexes: arg(0) }, {}), /** @@ -2713,19 +2760,19 @@ PropertyIteratorClient.prototype = { * The index of the first property to fetch. * @param count Number * The number of properties to fetch. - * @param aCallback Function + * @param callback Function * The function called when we receive the property values. */ slice: DebuggerClient.requester({ type: "slice", - start: args(0), - count: args(1) + start: arg(0), + count: arg(1) }, {}), /** * Get all the property values. * - * @param aCallback Function + * @param callback Function * The function called when we receive the property values. */ all: DebuggerClient.requester({ @@ -2737,57 +2784,65 @@ PropertyIteratorClient.prototype = { * A LongStringClient provides a way to access "very long" strings from the * debugger server. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aGrip Object + * @param grip Object * A pause-lifetime long string grip returned by the protocol. */ -function LongStringClient(aClient, aGrip) { - this._grip = aGrip; - this._client = aClient; +function LongStringClient(client, grip) { + this._grip = grip; + this._client = client; this.request = this._client.request; } exports.LongStringClient = LongStringClient; LongStringClient.prototype = { - get actor() { return this._grip.actor; }, - get length() { return this._grip.length; }, - get initial() { return this._grip.initial; }, - get _transport() { return this._client._transport; }, + get actor() { + return this._grip.actor; + }, + get length() { + return this._grip.length; + }, + get initial() { + return this._grip.initial; + }, + get _transport() { + return this._client._transport; + }, valid: true, /** - * Get the substring of this LongString from aStart to aEnd. + * Get the substring of this LongString from start to end. * - * @param aStart Number + * @param start Number * The starting index. - * @param aEnd Number + * @param end Number * The ending index. - * @param aCallback Function + * @param callback Function * The function called when we receive the substring. */ substring: DebuggerClient.requester({ type: "substring", - start: args(0), - end: args(1) + start: arg(0), + end: arg(1) }), }; /** * A SourceClient provides a way to access the source text of a script. * - * @param aClient ThreadClient + * @param client ThreadClient * The thread client parent. - * @param aForm Object + * @param form Object * The form sent across the remote debugging protocol. */ -function SourceClient(aClient, aForm) { - this._form = aForm; - this._isBlackBoxed = aForm.isBlackBoxed; - this._isPrettyPrinted = aForm.isPrettyPrinted; - this._activeThread = aClient; - this._client = aClient.client; +function SourceClient(client, form) { + this._form = form; + this._isBlackBoxed = form.isBlackBoxed; + this._isPrettyPrinted = form.isPrettyPrinted; + this._activeThread = client; + this._client = client.client; } SourceClient.prototype = { @@ -2813,47 +2868,47 @@ SourceClient.prototype = { /** * Black box this SourceClient's source. * - * @param aCallback Function + * @param callback Function * The callback function called when we receive the response from the server. */ blackBox: DebuggerClient.requester({ type: "blackbox" }, { - after: function (aResponse) { - if (!aResponse.error) { + after: function (response) { + if (!response.error) { this._isBlackBoxed = true; if (this._activeThread) { this._activeThread.emit("blackboxchange", this); } } - return aResponse; + return response; } }), /** * Un-black box this SourceClient's source. * - * @param aCallback Function + * @param callback Function * The callback function called when we receive the response from the server. */ unblackBox: DebuggerClient.requester({ type: "unblackbox" }, { - after: function (aResponse) { - if (!aResponse.error) { + after: function (response) { + if (!response.error) { this._isBlackBoxed = false; if (this._activeThread) { this._activeThread.emit("blackboxchange", this); } } - return aResponse; + return response; } }), /** * Get Executable Lines from a source * - * @param aCallback Function + * @param callback Function * The callback function called when we receive the response from the server. */ getExecutableLines: function (cb = noop) { @@ -2871,105 +2926,105 @@ SourceClient.prototype = { /** * Get a long string grip for this SourceClient's source. */ - source: function (aCallback = noop) { + source: function (callback = noop) { let packet = { to: this._form.actor, type: "source" }; - return this._client.request(packet).then(aResponse => { - return this._onSourceResponse(aResponse, aCallback); + return this._client.request(packet).then(response => { + return this._onSourceResponse(response, callback); }); }, /** * Pretty print this source's text. */ - prettyPrint: function (aIndent, aCallback = noop) { + prettyPrint: function (indent, callback = noop) { const packet = { to: this._form.actor, type: "prettyPrint", - indent: aIndent + indent }; - return this._client.request(packet).then(aResponse => { - if (!aResponse.error) { + return this._client.request(packet).then(response => { + if (!response.error) { this._isPrettyPrinted = true; this._activeThread._clearFrames(); this._activeThread.emit("prettyprintchange", this); } - return this._onSourceResponse(aResponse, aCallback); + return this._onSourceResponse(response, callback); }); }, /** * Stop pretty printing this source's text. */ - disablePrettyPrint: function (aCallback = noop) { + disablePrettyPrint: function (callback = noop) { const packet = { to: this._form.actor, type: "disablePrettyPrint" }; - return this._client.request(packet).then(aResponse => { - if (!aResponse.error) { + return this._client.request(packet).then(response => { + if (!response.error) { this._isPrettyPrinted = false; this._activeThread._clearFrames(); this._activeThread.emit("prettyprintchange", this); } - return this._onSourceResponse(aResponse, aCallback); + return this._onSourceResponse(response, callback); }); }, - _onSourceResponse: function (aResponse, aCallback) { - if (aResponse.error) { - aCallback(aResponse); - return aResponse; + _onSourceResponse: function (response, callback) { + if (response.error) { + callback(response); + return response; } - if (typeof aResponse.source === "string") { - aCallback(aResponse); - return aResponse; + if (typeof response.source === "string") { + callback(response); + return response; } - let { contentType, source } = aResponse; + let { contentType, source } = response; let longString = this._activeThread.threadLongString(source); - return longString.substring(0, longString.length).then(function (aResponse) { - if (aResponse.error) { - aCallback(aResponse); - return aReponse; + return longString.substring(0, longString.length).then(function (resp) { + if (resp.error) { + callback(resp); + return resp; } - let response = { - source: aResponse.substring, + let newResponse = { + source: resp.substring, contentType: contentType }; - aCallback(response); - return response; + callback(newResponse); + return newResponse; }); }, /** * Request to set a breakpoint in the specified location. * - * @param object aLocation + * @param object location * The location and condition of the breakpoint in * the form of { line[, column, condition] }. - * @param function aOnResponse + * @param function onResponse * Called with the thread's response. */ - setBreakpoint: function ({ line, column, condition, noSliding }, aOnResponse = noop) { + setBreakpoint: function ({ line, column, condition, noSliding }, onResponse = noop) { // A helper function that sets the breakpoint. - let doSetBreakpoint = aCallback => { + let doSetBreakpoint = callback => { let root = this._client.mainRoot; let location = { - line: line, - column: column + line, + column, }; let packet = { to: this.actor, type: "setBreakpoint", - location: location, - condition: condition, - noSliding: noSliding + location, + condition, + noSliding, }; // Backwards compatibility: send the breakpoint request to the @@ -2979,24 +3034,24 @@ SourceClient.prototype = { packet.location.url = this.url; } - return this._client.request(packet).then(aResponse => { + return this._client.request(packet).then(response => { // Ignoring errors, since the user may be setting a breakpoint in a // dead script that will reappear on a page reload. let bpClient; - if (aResponse.actor) { + if (response.actor) { bpClient = new BreakpointClient( this._client, this, - aResponse.actor, + response.actor, location, root.traits.conditionalBreakpoints ? condition : undefined ); } - aOnResponse(aResponse, bpClient); - if (aCallback) { - aCallback(); + onResponse(response, bpClient); + if (callback) { + callback(); } - return [aResponse, bpClient]; + return [response, bpClient]; }); }; @@ -3005,14 +3060,14 @@ SourceClient.prototype = { return doSetBreakpoint(); } // Otherwise, force a pause in order to set the breakpoint. - return this._activeThread.interrupt().then(aResponse => { - if (aResponse.error) { + return this._activeThread.interrupt().then(response => { + if (response.error) { // Can't set the breakpoint if pausing failed. - aOnResponse(aResponse); - return aResponse; + onResponse(response); + return response; } - const { type, why } = aResponse; + const { type, why } = response; const cleanUp = type == "paused" && why.type == "interrupted" ? () => this._activeThread.resume() : noop; @@ -3025,38 +3080,42 @@ SourceClient.prototype = { /** * Breakpoint clients are used to remove breakpoints that are no longer used. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aSourceClient SourceClient + * @param sourceClient SourceClient * The source where this breakpoint exists - * @param aActor string + * @param actor string * The actor ID for this breakpoint. - * @param aLocation object + * @param location object * The location of the breakpoint. This is an object with two properties: * url and line. - * @param aCondition string + * @param condition string * The conditional expression of the breakpoint */ -function BreakpointClient(aClient, aSourceClient, aActor, aLocation, aCondition) { - this._client = aClient; - this._actor = aActor; - this.location = aLocation; - this.location.actor = aSourceClient.actor; - this.location.url = aSourceClient.url; - this.source = aSourceClient; +function BreakpointClient(client, sourceClient, actor, location, condition) { + this._client = client; + this._actor = actor; + this.location = location; + this.location.actor = sourceClient.actor; + this.location.url = sourceClient.url; + this.source = sourceClient; this.request = this._client.request; // The condition property should only exist if it's a truthy value - if (aCondition) { - this.condition = aCondition; + if (condition) { + this.condition = condition; } } BreakpointClient.prototype = { _actor: null, - get actor() { return this._actor; }, - get _transport() { return this._client._transport; }, + get actor() { + return this._actor; + }, + get _transport() { + return this._client._transport; + }, /** * Remove the breakpoint from the server. @@ -3074,9 +3133,8 @@ BreakpointClient.prototype = { // conditional breakpoints if (root.traits.conditionalBreakpoints) { return "condition" in this; - } else { - return "conditionalExpression" in this; } + return "conditionalExpression" in this; }, /** @@ -3090,15 +3148,14 @@ BreakpointClient.prototype = { let root = this._client.mainRoot; if (root.traits.conditionalBreakpoints) { return this.condition; - } else { - return this.conditionalExpression; } + return this.conditionalExpression; }, /** * Set the condition of this breakpoint */ - setCondition: function (gThreadClient, aCondition) { + setCondition: function (gThreadClient, condition) { let root = this._client.mainRoot; let deferred = promise.defer(); @@ -3106,32 +3163,31 @@ BreakpointClient.prototype = { let info = { line: this.location.line, column: this.location.column, - condition: aCondition + condition: condition }; // Remove the current breakpoint and add a new one with the // condition. - this.remove(aResponse => { - if (aResponse && aResponse.error) { - deferred.reject(aResponse); + this.remove(response => { + if (response && response.error) { + deferred.reject(response); return; } - this.source.setBreakpoint(info, (aResponse, aNewBreakpoint) => { - if (aResponse && aResponse.error) { - deferred.reject(aResponse); + this.source.setBreakpoint(info, (resp, newBreakpoint) => { + if (resp && resp.error) { + deferred.reject(resp); } else { - deferred.resolve(aNewBreakpoint); + deferred.resolve(newBreakpoint); } }); }); } else { // The property shouldn't even exist if the condition is blank - if (aCondition === "") { + if (condition === "") { delete this.conditionalExpression; - } - else { - this.conditionalExpression = aCondition; + } else { + this.conditionalExpression = condition; } deferred.resolve(this); } @@ -3145,14 +3201,14 @@ eventSource(BreakpointClient.prototype); /** * Environment clients are used to manipulate the lexical environment actors. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aForm Object + * @param form Object * The form sent across the remote debugging protocol. */ -function EnvironmentClient(aClient, aForm) { - this._client = aClient; - this._form = aForm; +function EnvironmentClient(client, form) { + this._client = client; + this._form = form; this.request = this._client.request; } exports.EnvironmentClient = EnvironmentClient; @@ -3162,7 +3218,9 @@ EnvironmentClient.prototype = { get actor() { return this._form.actor; }, - get _transport() { return this._client._transport; }, + get _transport() { + return this._client._transport; + }, /** * Fetches the bindings introduced by this lexical environment. @@ -3177,8 +3235,8 @@ EnvironmentClient.prototype = { */ assign: DebuggerClient.requester({ type: "assign", - name: args(0), - value: args(1) + name: arg(0), + value: arg(1) }) }; diff --git a/devtools/shared/discovery/discovery.js b/devtools/shared/discovery/discovery.js index d0b49f1290cd..a07f21d445e7 100644 --- a/devtools/shared/discovery/discovery.js +++ b/devtools/shared/discovery/discovery.js @@ -47,8 +47,8 @@ const REPLY_TIMEOUT = 5000; const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {}); XPCOMUtils.defineLazyGetter(this, "converter", () => { - let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]. - createInstance(Ci.nsIScriptableUnicodeConverter); + let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"] + .createInstance(Ci.nsIScriptableUnicodeConverter); conv.charset = "utf8"; return conv; }); @@ -77,7 +77,8 @@ function log(msg) { function Transport(port) { EventEmitter.decorate(this); try { - this.socket = new UDPSocket(port, false, Services.scriptSecurityManager.getSystemPrincipal()); + this.socket = new UDPSocket(port, false, + Services.scriptSecurityManager.getSystemPrincipal()); this.socket.joinMulticast(ADDRESS); this.socket.asyncListen(this); } catch (e) { @@ -146,7 +147,8 @@ function LocalDevice() { Cc["@mozilla.org/settingsService;1"].getService(Ci.nsISettingsService); Services.obs.addObserver(this, "mozsettings-changed", false); } - this._get(); // Trigger |_get| to load name eagerly + // Trigger |_get| to load name eagerly + this._get(); } LocalDevice.SETTING = "devtools.discovery.device"; @@ -344,7 +346,8 @@ Discovery.prototype = { _startListeningForScan: function () { if (this._transports.scan) { - return; // Already listening + // Already listening + return; } log("LISTEN FOR SCAN"); this._transports.scan = new this.Transport(SCAN_PORT); @@ -353,7 +356,8 @@ Discovery.prototype = { _stopListeningForScan: function () { if (!this._transports.scan) { - return; // Not listening + // Not listening + return; } this._transports.scan.off("message", this._onRemoteScan); this._transports.scan.destroy(); @@ -362,7 +366,8 @@ Discovery.prototype = { _startListeningForUpdate: function () { if (this._transports.update) { - return; // Already listening + // Already listening + return; } log("LISTEN FOR UPDATE"); this._transports.update = new this.Transport(UPDATE_PORT); @@ -371,7 +376,8 @@ Discovery.prototype = { _stopListeningForUpdate: function () { if (!this._transports.update) { - return; // Not listening + // Not listening + return; } this._transports.update.off("message", this._onRemoteUpdate); this._transports.update.destroy(); diff --git a/devtools/shared/discovery/tests/unit/.eslintrc.js b/devtools/shared/discovery/tests/unit/.eslintrc.js new file mode 100644 index 000000000000..f21b71f67ad0 --- /dev/null +++ b/devtools/shared/discovery/tests/unit/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../../.eslintrc.xpcshell.js" +}; \ No newline at end of file diff --git a/devtools/shared/discovery/tests/unit/test_discovery.js b/devtools/shared/discovery/tests/unit/test_discovery.js index c31340b08966..56b0bc1e7c94 100644 --- a/devtools/shared/discovery/tests/unit/test_discovery.js +++ b/devtools/shared/discovery/tests/unit/test_discovery.js @@ -8,7 +8,6 @@ var Cu = Components.utils; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); const Services = require("Services"); -const promise = require("promise"); const defer = require("devtools/shared/defer"); const EventEmitter = require("devtools/shared/event-emitter"); const discovery = require("devtools/shared/discovery/discovery"); diff --git a/devtools/shared/performance/recording-common.js b/devtools/shared/performance/recording-common.js index d0826bd1881e..8aa6440e4ee1 100644 --- a/devtools/shared/performance/recording-common.js +++ b/devtools/shared/performance/recording-common.js @@ -9,7 +9,7 @@ * and LegacyPerformanceRecording for helper methods to access data. */ -const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { +exports.PerformanceRecordingCommon = { // Private fields, only needed when a recording is started or stopped. _console: false, _imported: false, @@ -35,18 +35,32 @@ const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { * Helper methods for returning the status of the recording. * These methods should be consistent on both the front and actor. */ - isRecording: function () { return this._recording; }, - isCompleted: function () { return this._completed || this.isImported(); }, - isFinalizing: function () { return !this.isRecording() && !this.isCompleted(); }, - isConsole: function () { return this._console; }, - isImported: function () { return this._imported; }, + isRecording: function () { + return this._recording; + }, + isCompleted: function () { + return this._completed || this.isImported(); + }, + isFinalizing: function () { + return !this.isRecording() && !this.isCompleted(); + }, + isConsole: function () { + return this._console; + }, + isImported: function () { + return this._imported; + }, /** * Helper methods for returning configuration for the recording. * These methods should be consistent on both the front and actor. */ - getConfiguration: function () { return this._configuration; }, - getLabel: function () { return this._label; }, + getConfiguration: function () { + return this._configuration; + }, + getLabel: function () { + return this._label; + }, /** * Gets duration of this recording, in milliseconds. @@ -59,25 +73,43 @@ const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { // the duration from the profiler; if between recording and being finalized, // use the last estimated duration. if (this.isRecording()) { - return this._estimatedDuration = Date.now() - this._localStartTime; - } else { - return this._duration || this._estimatedDuration || 0; + this._estimatedDuration = Date.now() - this._localStartTime; + return this._estimatedDuration; } + return this._duration || this._estimatedDuration || 0; }, /** * Helper methods for returning recording data. * These methods should be consistent on both the front and actor. */ - getMarkers: function () { return this._markers; }, - getFrames: function () { return this._frames; }, - getMemory: function () { return this._memory; }, - getTicks: function () { return this._ticks; }, - getAllocations: function () { return this._allocations; }, - getProfile: function () { return this._profile; }, - getHostSystemInfo: function () { return this._systemHost; }, - getClientSystemInfo: function () { return this._systemClient; }, - getStartingBufferStatus: function () { return this._startingBufferStatus; }, + getMarkers: function () { + return this._markers; + }, + getFrames: function () { + return this._frames; + }, + getMemory: function () { + return this._memory; + }, + getTicks: function () { + return this._ticks; + }, + getAllocations: function () { + return this._allocations; + }, + getProfile: function () { + return this._profile; + }, + getHostSystemInfo: function () { + return this._systemHost; + }, + getClientSystemInfo: function () { + return this._systemClient; + }, + getStartingBufferStatus: function () { + return this._startingBufferStatus; + }, getAllData: function () { let label = this.getLabel(); @@ -92,6 +124,18 @@ const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { let systemHost = this.getHostSystemInfo(); let systemClient = this.getClientSystemInfo(); - return { label, duration, markers, frames, memory, ticks, allocations, profile, configuration, systemHost, systemClient }; + return { + label, + duration, + markers, + frames, + memory, + ticks, + allocations, + profile, + configuration, + systemHost, + systemClient + }; }, }; diff --git a/devtools/shared/performance/recording-utils.js b/devtools/shared/performance/recording-utils.js index 64ed12c71f1c..3b9c4cbca0fd 100644 --- a/devtools/shared/performance/recording-utils.js +++ b/devtools/shared/performance/recording-utils.js @@ -3,7 +3,6 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Cc, Ci, Cu, Cr } = require("chrome"); loader.lazyRequireGetter(this, "extend", "sdk/util/object", true); @@ -16,7 +15,8 @@ function mapRecordingOptions(type, options) { if (type === "profiler") { return { entries: options.bufferSize, - interval: options.sampleFrequency ? (1000 / (options.sampleFrequency * 1000)) : void 0 + interval: options.sampleFrequency ? (1000 / (options.sampleFrequency * 1000)) + : void 0 }; } @@ -568,7 +568,8 @@ UniqueStacks.prototype.getOrAddFrameIndex = function (frame) { let implementationIndex = this.getOrAddStringIndex(frame.implementation); // Super dumb. - let hash = `${locationIndex} ${implementationIndex || ""} ${frame.line || ""} ${frame.category || ""}`; + let hash = `${locationIndex} ${implementationIndex || ""} ` + + `${frame.line || ""} ${frame.category || ""}`; let index = frameHash[hash]; if (index !== undefined) { diff --git a/devtools/shared/performance/test/.eslintrc.js b/devtools/shared/performance/test/.eslintrc.js new file mode 100644 index 000000000000..90ed7706421b --- /dev/null +++ b/devtools/shared/performance/test/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../.eslintrc.xpcshell.js" +}; \ No newline at end of file diff --git a/devtools/shared/performance/test/head.js b/devtools/shared/performance/test/head.js index 9e7748055723..414831c96443 100644 --- a/devtools/shared/performance/test/head.js +++ b/devtools/shared/performance/test/head.js @@ -1,7 +1,10 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ + +/* exported require */ + "use strict"; -var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; +var { utils: Cu } = Components; var { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); diff --git a/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js b/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js index 6429eff2d434..141395652275 100644 --- a/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js +++ b/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + /** * Tests if allocations data received from the performance actor is properly * converted to something that follows the same structure as the samples data @@ -65,9 +67,15 @@ var EXPECTED_OUTPUT = { }, "data": [ null, - [ null, 1 ], // x (A:1:2) - [ 1, 2 ], // x (A:1:2) > y (B:3:4) - [ 2, 3 ] // x (A:1:2) > y (B:3:4) > C:5:6 + + // x (A:1:2) + [ null, 1 ], + + // x (A:1:2) > y (B:3:4) + [ 1, 2 ], + + // x (A:1:2) > y (B:3:4) > C:5:6 + [ 2, 3 ] ] }, frameTable: { diff --git a/devtools/shared/qrcode/index.js b/devtools/shared/qrcode/index.js index ec3442426402..7bf97e1babc0 100644 --- a/devtools/shared/qrcode/index.js +++ b/devtools/shared/qrcode/index.js @@ -4,7 +4,6 @@ "use strict"; -const { Cu } = require("chrome"); const promise = require("promise"); const defer = require("devtools/shared/defer"); diff --git a/devtools/shared/qrcode/tests/unit/.eslintrc.js b/devtools/shared/qrcode/tests/unit/.eslintrc.js new file mode 100644 index 000000000000..f21b71f67ad0 --- /dev/null +++ b/devtools/shared/qrcode/tests/unit/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../../.eslintrc.xpcshell.js" +}; \ No newline at end of file diff --git a/devtools/shared/security/auth.js b/devtools/shared/security/auth.js index 9272f602ebdc..52c9070b77bc 100644 --- a/devtools/shared/security/auth.js +++ b/devtools/shared/security/auth.js @@ -8,7 +8,6 @@ var { Ci, Cc } = require("chrome"); var Services = require("Services"); -var promise = require("promise"); var defer = require("devtools/shared/defer"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); var { dumpn, dumpv } = DevToolsUtils; @@ -408,7 +407,8 @@ OOBCert.Client.prototype = { }), _createRandom() { - const length = 16; // 16 bytes / 128 bits + // 16 bytes / 128 bits + const length = 16; let rng = Cc["@mozilla.org/security/random-generator;1"] .createInstance(Ci.nsIRandomGenerator); let bytes = rng.generateRandomBytes(length); @@ -545,9 +545,11 @@ OOBCert.Server.prototype = { switch (authResult) { case AuthenticationResult.ALLOW_PERSIST: case AuthenticationResult.ALLOW: - break; // Further processing + // Further processing + break; default: - return authResult; // Abort for any negative results + // Abort for any negative results + return authResult; } // Examine additional data for authentication diff --git a/devtools/shared/security/cert.js b/devtools/shared/security/cert.js index 7dbeded63116..7c101f3dbf0e 100644 --- a/devtools/shared/security/cert.js +++ b/devtools/shared/security/cert.js @@ -7,7 +7,6 @@ "use strict"; var { Ci, Cc } = require("chrome"); -var promise = require("promise"); var defer = require("devtools/shared/defer"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); DevToolsUtils.defineLazyGetter(this, "localCertService", () => { diff --git a/devtools/shared/security/socket.js b/devtools/shared/security/socket.js index 068a8ea81f0a..64d882c01b5d 100644 --- a/devtools/shared/security/socket.js +++ b/devtools/shared/security/socket.js @@ -6,7 +6,7 @@ "use strict"; -var { Ci, Cc, CC, Cr, Cu } = require("chrome"); +var { Ci, Cc, CC, Cr } = require("chrome"); // Ensure PSM is initialized to support TLS sockets Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports); @@ -143,7 +143,8 @@ var _getTransport = Task.async(function* (settings) { let attempt = yield _attemptTransport(settings); if (attempt.transport) { - return attempt.transport; // Success + // Success + return attempt.transport; } // If the server cert failed validation, store a temporary override and make @@ -156,7 +157,8 @@ var _getTransport = Task.async(function* (settings) { attempt = yield _attemptTransport(settings); if (attempt.transport) { - return attempt.transport; // Success + // Success + return attempt.transport; } throw new Error("Connection failed even after cert override"); @@ -356,7 +358,7 @@ function _storeCertOverride(s, host, port) { let overrideBits = Ci.nsICertOverrideService.ERROR_UNTRUSTED | Ci.nsICertOverrideService.ERROR_MISMATCH; certOverrideService.rememberValidityOverride(host, port, cert, overrideBits, - true /* temporary */); + true /* temporary */); // eslint-disable-line } /** diff --git a/devtools/shared/security/tests/chrome/.eslintrc.js b/devtools/shared/security/tests/chrome/.eslintrc.js new file mode 100644 index 000000000000..6dc0ab32b6e9 --- /dev/null +++ b/devtools/shared/security/tests/chrome/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../../../testing/mochitest/chrome.eslintrc.js" +}; diff --git a/devtools/shared/security/tests/chrome/test_websocket-transport.html b/devtools/shared/security/tests/chrome/test_websocket-transport.html index 542206ecfbfe..edcb5b2ffad7 100644 --- a/devtools/shared/security/tests/chrome/test_websocket-transport.html +++ b/devtools/shared/security/tests/chrome/test_websocket-transport.html @@ -9,7 +9,9 @@ diff --git a/devtools/shared/security/tests/unit/head_dbg.js b/devtools/shared/security/tests/unit/head_dbg.js index f3b2a9a9744d..790675c56dc7 100644 --- a/devtools/shared/security/tests/unit/head_dbg.js +++ b/devtools/shared/security/tests/unit/head_dbg.js @@ -2,20 +2,14 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; -var Cc = Components.classes; -var Ci = Components.interfaces; -var Cu = Components.utils; -var Cr = Components.results; -var CC = Components.Constructor; +/* exported defer, DebuggerClient, initTestDebuggerServer */ + +const { classes: Cc, interfaces: Ci, utils: Cu } = Components; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); -const promise = require("promise"); const defer = require("devtools/shared/defer"); -const { Task } = require("devtools/shared/task"); - const Services = require("Services"); -const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const xpcInspector = require("xpcInspector"); const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/main"); @@ -31,43 +25,43 @@ Services.prefs.setBoolPref("devtools.debugger.remote-enabled", true); // Fast timeout for TLS tests Services.prefs.setIntPref("devtools.remote.tls-handshake-timeout", 1000); -// Convert an nsIScriptError 'aFlags' value into an appropriate string. -function scriptErrorFlagsToKind(aFlags) { - var kind; - if (aFlags & Ci.nsIScriptError.warningFlag) +// Convert an nsIScriptError 'flags' value into an appropriate string. +function scriptErrorFlagsToKind(flags) { + let kind; + if (flags & Ci.nsIScriptError.warningFlag) { kind = "warning"; - if (aFlags & Ci.nsIScriptError.exceptionFlag) + } + if (flags & Ci.nsIScriptError.exceptionFlag) { kind = "exception"; - else + } else { kind = "error"; + } - if (aFlags & Ci.nsIScriptError.strictFlag) + if (flags & Ci.nsIScriptError.strictFlag) { kind = "strict " + kind; + } return kind; } // Register a console listener, so console messages don't just disappear // into the ether. -var errorCount = 0; var listener = { - observe: function (aMessage) { - errorCount++; + observe: function (message) { + let string; try { - // If we've been given an nsIScriptError, then we can print out - // something nicely formatted, for tools like Emacs to pick up. - var scriptError = aMessage.QueryInterface(Ci.nsIScriptError); - dump(aMessage.sourceName + ":" + aMessage.lineNumber + ": " + - scriptErrorFlagsToKind(aMessage.flags) + ": " + - aMessage.errorMessage + "\n"); - var string = aMessage.errorMessage; - } catch (x) { + message.QueryInterface(Ci.nsIScriptError); + dump(message.sourceName + ":" + message.lineNumber + ": " + + scriptErrorFlagsToKind(message.flags) + ": " + + message.errorMessage + "\n"); + string = message.errorMessage; + } catch (ex) { // Be a little paranoid with message, as the whole goal here is to lose // no information. try { - var string = "" + aMessage.message; - } catch (x) { - var string = ""; + string = "" + message.message; + } catch (e) { + string = ""; } } @@ -77,7 +71,7 @@ var listener = { } // Print in most cases, but ignore the "strict" messages - if (!(aMessage.flags & Ci.nsIScriptError.strictFlag)) { + if (!(message.flags & Ci.nsIScriptError.strictFlag)) { do_print("head_dbg.js got console message: " + string + "\n"); } } diff --git a/devtools/shared/security/tests/unit/test_oob_cert_auth.js b/devtools/shared/security/tests/unit/test_oob_cert_auth.js index 1e820af52b2e..e37a0f589d80 100644 --- a/devtools/shared/security/tests/unit/test_oob_cert_auth.js +++ b/devtools/shared/security/tests/unit/test_oob_cert_auth.js @@ -38,7 +38,8 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests + // Skip prompt for tests + serverAuth.receiveOOB = () => oobData.promise; let listener = DebuggerServer.createListener(); ok(listener, "Socket listener created"); @@ -98,7 +99,8 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests + // Skip prompt for tests + serverAuth.receiveOOB = () => oobData.promise; let listener = DebuggerServer.createListener(); ok(listener, "Socket listener created"); @@ -161,7 +163,8 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests + // Skip prompt for tests + serverAuth.receiveOOB = () => oobData.promise; let clientAuth = new AuthenticatorType.Client(); clientAuth.sendOOB = ({ oob }) => { @@ -215,7 +218,8 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests + // Skip prompt for tests + serverAuth.receiveOOB = () => oobData.promise; let clientAuth = new AuthenticatorType.Client(); clientAuth.sendOOB = ({ oob }) => { diff --git a/devtools/shared/security/tests/unit/testactors.js b/devtools/shared/security/tests/unit/testactors.js index 80d5d4e18abe..1a170cba78e9 100644 --- a/devtools/shared/security/tests/unit/testactors.js +++ b/devtools/shared/security/tests/unit/testactors.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + const { ActorPool, appendExtraActors, createExtraActors } = require("devtools/server/actors/common"); const { RootActor } = require("devtools/server/actors/root"); @@ -9,8 +11,8 @@ const { DebuggerServer } = require("devtools/server/main"); const promise = require("promise"); var gTestGlobals = []; -DebuggerServer.addTestGlobal = function (aGlobal) { - gTestGlobals.push(aGlobal); +DebuggerServer.addTestGlobal = function (global) { + gTestGlobals.push(global); }; // A mock tab list, for use by tests. This simply presents each global in @@ -20,18 +22,18 @@ DebuggerServer.addTestGlobal = function (aGlobal) { // As implemented now, we consult gTestGlobals when we're constructed, not // when we're iterated over, so tests have to add their globals before the // root actor is created. -function TestTabList(aConnection) { - this.conn = aConnection; +function TestTabList(connection) { + this.conn = connection; // An array of actors for each global added with // DebuggerServer.addTestGlobal. this._tabActors = []; // A pool mapping those actors' names to the actors. - this._tabActorPool = new ActorPool(aConnection); + this._tabActorPool = new ActorPool(connection); for (let global of gTestGlobals) { - let actor = new TestTabActor(aConnection, global); + let actor = new TestTabActor(connection, global); actor.selected = false; this._tabActors.push(actor); this._tabActorPool.addActor(actor); @@ -40,7 +42,7 @@ function TestTabList(aConnection) { this._tabActors[0].selected = true; } - aConnection.addActorPool(this._tabActorPool); + connection.addActorPool(this._tabActorPool); } TestTabList.prototype = { @@ -50,18 +52,18 @@ TestTabList.prototype = { } }; -function createRootActor(aConnection) { - let root = new RootActor(aConnection, { - tabList: new TestTabList(aConnection), +function createRootActor(connection) { + let root = new RootActor(connection, { + tabList: new TestTabList(connection), globalActorFactories: DebuggerServer.globalActorFactories }); root.applicationType = "xpcshell-tests"; return root; } -function TestTabActor(aConnection, aGlobal) { - this.conn = aConnection; - this._global = aGlobal; +function TestTabActor(connection, global) { + this.conn = connection; + this._global = global; this._threadActor = new ThreadActor(this, this._global); this.conn.addActor(this._threadActor); this._attached = false; @@ -96,7 +98,7 @@ TestTabActor.prototype = { return response; }, - onAttach: function (aRequest) { + onAttach: function (request) { this._attached = true; let response = { type: "tabAttached", threadActor: this._threadActor.actorID }; @@ -105,9 +107,9 @@ TestTabActor.prototype = { return response; }, - onDetach: function (aRequest) { + onDetach: function (request) { if (!this._attached) { - return { "error":"wrongState" }; + return { "error": "wrongState" }; } return { type: "detached" }; }, diff --git a/devtools/shared/shims/event-emitter.js b/devtools/shared/shims/event-emitter.js index 6b3672162917..bf648e373ad4 100644 --- a/devtools/shared/shims/event-emitter.js +++ b/devtools/shared/shims/event-emitter.js @@ -9,10 +9,13 @@ * specific path. */ -(function (factory) { // Module boilerplate - if (this.module && module.id.indexOf("event-emitter") >= 0) { // require +(function (factory) { + // Module boilerplate + if (this.module && module.id.indexOf("event-emitter") >= 0) { + // require factory.call(this, require, exports, module); - } else { // Cu.import + } else { + // Cu.import const Cu = Components.utils; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); diff --git a/devtools/shared/tests/browser/browser_async_storage.js b/devtools/shared/tests/browser/browser_async_storage.js index 4329d639aee2..141965cf00b4 100644 --- a/devtools/shared/tests/browser/browser_async_storage.js +++ b/devtools/shared/tests/browser/browser_async_storage.js @@ -30,7 +30,7 @@ add_task(function* () { }); add_task(function* () { - var object = { + let object = { x: 1, y: "foo", z: true diff --git a/devtools/shared/tests/unit/exposeLoader.js b/devtools/shared/tests/unit/exposeLoader.js index 949640a03e4e..7c8acdd75945 100644 --- a/devtools/shared/tests/unit/exposeLoader.js +++ b/devtools/shared/tests/unit/exposeLoader.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + exports.exerciseLazyRequire = (name, path) => { const o = {}; loader.lazyRequireGetter(o, name, path); diff --git a/devtools/shared/tests/unit/head_devtools.js b/devtools/shared/tests/unit/head_devtools.js index f0f47c93ac15..2854d9389758 100644 --- a/devtools/shared/tests/unit/head_devtools.js +++ b/devtools/shared/tests/unit/head_devtools.js @@ -1,13 +1,12 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; -var Cc = Components.classes; -var Ci = Components.interfaces; -var Cu = Components.utils; -var Cr = Components.results; +/* exported DevToolsUtils, DevToolsLoader */ -const {require, DevToolsLoader, devtools} = Cu.import("resource://devtools/shared/Loader.jsm", {}); +"use strict"; + +const { classes: Cc, interfaces: Ci, utils: Cu } = Components; +const { require, DevToolsLoader } = Cu.import("resource://devtools/shared/Loader.jsm", {}); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const flags = require("devtools/shared/flags"); @@ -23,25 +22,22 @@ do_register_cleanup(() => { // failures, set this to true. var ALLOW_CONSOLE_ERRORS = false; -var errorCount = 0; var listener = { - observe: function (aMessage) { - errorCount++; + observe: function (message) { + let string; try { - // If we've been given an nsIScriptError, then we can print out - // something nicely formatted, for tools like Emacs to pick up. - var scriptError = aMessage.QueryInterface(Ci.nsIScriptError); - dump(aMessage.sourceName + ":" + aMessage.lineNumber + ": " + - scriptErrorFlagsToKind(aMessage.flags) + ": " + - aMessage.errorMessage + "\n"); - var string = aMessage.errorMessage; - } catch (x) { + message.QueryInterface(Ci.nsIScriptError); + dump(message.sourceName + ":" + message.lineNumber + ": " + + scriptErrorFlagsToKind(message.flags) + ": " + + message.errorMessage + "\n"); + string = message.errorMessage; + } catch (ex) { // Be a little paranoid with message, as the whole goal here is to lose // no information. try { - var string = "" + aMessage.message; - } catch (x) { - var string = ""; + string = "" + message.message; + } catch (e) { + string = ""; } } diff --git a/devtools/shared/tests/unit/test_assert.js b/devtools/shared/tests/unit/test_assert.js index b871717511a4..e5fe01974139 100644 --- a/devtools/shared/tests/unit/test_assert.js +++ b/devtools/shared/tests/unit/test_assert.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test DevToolsUtils.assert ALLOW_CONSOLE_ERRORS = true; @@ -32,5 +34,6 @@ function run_test() { } ok(assertionFailed, - "The assertion should have failed, which should throw an error when assertions are enabled."); + "The assertion should have failed, which should throw an error when assertions " + + "are enabled."); } diff --git a/devtools/shared/tests/unit/test_async-utils.js b/devtools/shared/tests/unit/test_async-utils.js index 2b09b82608ca..8c640c473bca 100644 --- a/devtools/shared/tests/unit/test_async-utils.js +++ b/devtools/shared/tests/unit/test_async-utils.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test async-utils.js const {Task} = require("devtools/shared/task"); @@ -60,12 +62,13 @@ function test_async_return(async) { function test_async_throw(async) { let obj = { method: async(function* () { - throw "boom"; + throw new Error("boom"); }) }; return obj.method().then(null, error => { - do_check_eq(error, "boom"); + do_check_true(error instanceof Error); + do_check_eq(error.message, "boom"); }); } @@ -116,7 +119,6 @@ function test_async_once() { function test_async_invoke() { return Task.spawn(function* () { function func(a, b, expectedThis, callback) { - "use strict"; do_check_eq(a, "foo"); do_check_eq(b, "bar"); do_check_eq(this, expectedThis); @@ -127,13 +129,11 @@ function test_async_invoke() { let callResult = yield promiseCall(func, "foo", "bar", undefined); do_check_eq(callResult, "foobar"); - // Test invoke. let obj = { method: func }; let invokeResult = yield promiseInvoke(obj, obj.method, "foo", "bar", obj); do_check_eq(invokeResult, "foobar"); - // Test passing multiple values to the callback. function multipleResults(callback) { callback("foo", "bar"); @@ -144,14 +144,14 @@ function test_async_invoke() { do_check_eq(results[0], "foo"); do_check_eq(results[1], "bar"); - // Test throwing from the function. function thrower() { - throw "boom"; + throw new Error("boom"); } yield promiseCall(thrower).then(null, error => { - do_check_eq(error, "boom"); + do_check_true(error instanceof Error); + do_check_eq(error.message, "boom"); }); }); } diff --git a/devtools/shared/tests/unit/test_console_filtering.js b/devtools/shared/tests/unit/test_console_filtering.js index 6ee620ebbe6f..e126981d0cfa 100644 --- a/devtools/shared/tests/unit/test_console_filtering.js +++ b/devtools/shared/tests/unit/test_console_filtering.js @@ -11,19 +11,19 @@ var seenMessages = 0; var seenTypes = 0; var callback = { - onConsoleAPICall: function (aMessage) { - if (aMessage.consoleID && aMessage.consoleID == "addon/foo") { - do_check_eq(aMessage.level, "warn"); - do_check_eq(aMessage.arguments[0], "Warning from foo"); + onConsoleAPICall: function (message) { + if (message.consoleID && message.consoleID == "addon/foo") { + do_check_eq(message.level, "warn"); + do_check_eq(message.arguments[0], "Warning from foo"); seenTypes |= 1; - } else if (aMessage.originAttributes && - aMessage.originAttributes.addonId == "bar") { - do_check_eq(aMessage.level, "error"); - do_check_eq(aMessage.arguments[0], "Error from bar"); + } else if (message.originAttributes && + message.originAttributes.addonId == "bar") { + do_check_eq(message.level, "error"); + do_check_eq(message.arguments[0], "Error from bar"); seenTypes |= 2; } else { - do_check_eq(aMessage.level, "log"); - do_check_eq(aMessage.arguments[0], "Hello from default console"); + do_check_eq(message.level, "log"); + do_check_eq(message.arguments[0], "Hello from default console"); seenTypes |= 4; } seenMessages++; diff --git a/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js b/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js index d729e747398d..452d01847306 100644 --- a/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js +++ b/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js @@ -1,13 +1,13 @@ -/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test DevToolsUtils.defineLazyPrototypeGetter function Class() {} DevToolsUtils.defineLazyPrototypeGetter(Class.prototype, "foo", () => []); - function run_test() { test_prototype_attributes(); test_instance_attributes(); diff --git a/devtools/shared/tests/unit/test_executeSoon.js b/devtools/shared/tests/unit/test_executeSoon.js index 6154a3e67e35..78bdcd6a4ea3 100644 --- a/devtools/shared/tests/unit/test_executeSoon.js +++ b/devtools/shared/tests/unit/test_executeSoon.js @@ -11,7 +11,6 @@ */ var { executeSoon } = require("devtools/shared/DevToolsUtils"); -var promise = require("promise"); var defer = require("devtools/shared/defer"); var Services = require("Services"); diff --git a/devtools/shared/tests/unit/test_flatten.js b/devtools/shared/tests/unit/test_flatten.js index f5a186770cc0..11c2ac047479 100644 --- a/devtools/shared/tests/unit/test_flatten.js +++ b/devtools/shared/tests/unit/test_flatten.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test ThreadSafeDevToolsUtils.flatten function run_test() { diff --git a/devtools/shared/tests/unit/test_independent_loaders.js b/devtools/shared/tests/unit/test_independent_loaders.js index 20abed27d208..6d3aaead6935 100644 --- a/devtools/shared/tests/unit/test_independent_loaders.js +++ b/devtools/shared/tests/unit/test_independent_loaders.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + /** * Ensure that each instance of the Dev Tools loader contains its own loader * instance, and also returns unique objects. This ensures there is no sharing diff --git a/devtools/shared/tests/unit/test_isSet.js b/devtools/shared/tests/unit/test_isSet.js index f85d6ae3c3f1..a9e1fcafa9ab 100644 --- a/devtools/shared/tests/unit/test_isSet.js +++ b/devtools/shared/tests/unit/test_isSet.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test ThreadSafeDevToolsUtils.isSet function run_test() { diff --git a/devtools/shared/tests/unit/test_require.js b/devtools/shared/tests/unit/test_require.js index 005e5665633e..2d10d1e0f8c0 100644 --- a/devtools/shared/tests/unit/test_require.js +++ b/devtools/shared/tests/unit/test_require.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test require // Ensure that DevtoolsLoader.require doesn't spawn multiple diff --git a/devtools/shared/tests/unit/test_require_lazy.js b/devtools/shared/tests/unit/test_require_lazy.js index 8ef5a7d23e7b..72c83e880fcb 100644 --- a/devtools/shared/tests/unit/test_require_lazy.js +++ b/devtools/shared/tests/unit/test_require_lazy.js @@ -1,6 +1,9 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +const { devtools } = Cu.import("resource://devtools/shared/Loader.jsm", {}); // Test devtools.lazyRequireGetter function run_test() { @@ -18,7 +21,8 @@ function run_test() { const o2 = {}; let loader = new DevToolsLoader(); - // We have to init the loader by loading any module before lazyRequireGetter is available + // We have to init the loader by loading any module before + // lazyRequireGetter is available loader.require("devtools/shared/DevToolsUtils"); loader.lazyRequireGetter(o2, name, path); diff --git a/devtools/shared/tests/unit/test_require_raw.js b/devtools/shared/tests/unit/test_require_raw.js index 5bec82b55bb0..1cfd0d3f3d22 100644 --- a/devtools/shared/tests/unit/test_require_raw.js +++ b/devtools/shared/tests/unit/test_require_raw.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test require using "raw!". function run_test() { diff --git a/devtools/shared/tests/unit/test_safeErrorString.js b/devtools/shared/tests/unit/test_safeErrorString.js index 9892f34d1e63..afde7d7c97c5 100644 --- a/devtools/shared/tests/unit/test_safeErrorString.js +++ b/devtools/shared/tests/unit/test_safeErrorString.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test DevToolsUtils.safeErrorString function run_test() { diff --git a/devtools/shared/tests/unit/test_stack.js b/devtools/shared/tests/unit/test_stack.js index ef747c83f6de..7342526e45eb 100644 --- a/devtools/shared/tests/unit/test_stack.js +++ b/devtools/shared/tests/unit/test_stack.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test stack.js. function run_test() { diff --git a/devtools/shared/touch/simulator-content.js b/devtools/shared/touch/simulator-content.js index 0b10579ca586..6c9f3f2bfdec 100644 --- a/devtools/shared/touch/simulator-content.js +++ b/devtools/shared/touch/simulator-content.js @@ -1,7 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - /* globals addMessageListener, sendAsyncMessage */ + /* globals addMessageListener, sendAsyncMessage, docShell */ "use strict"; const { utils: Cu } = Components; diff --git a/devtools/shared/touch/simulator-core.js b/devtools/shared/touch/simulator-core.js index 6933f9207cbd..52ff5c124df2 100644 --- a/devtools/shared/touch/simulator-core.js +++ b/devtools/shared/touch/simulator-core.js @@ -1,6 +1,9 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* global XPCNativeWrapper */ + "use strict"; const { Ci, Cu } = require("chrome"); @@ -272,12 +275,14 @@ SimulatorCore.prototype = { } } let unwrapped = XPCNativeWrapper.unwrap(target); + /* eslint-disable no-inline-comments */ unwrapped.sendTouchEvent(name, clone([0]), // event type, id clone([evt.clientX]), // x clone([evt.clientY]), // y clone([1]), clone([1]), // rx, ry clone([0]), clone([0]), // rotation, force 1); // count + /* eslint-enable no-inline-comments */ return; } let document = target.ownerDocument; @@ -339,10 +344,10 @@ SimulatorCore.prototype = { let utils = content.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); - let allowZoom = {}, - minZoom = {}, - maxZoom = {}, - autoSize = {}; + let allowZoom = {}; + let minZoom = {}; + let maxZoom = {}; + let autoSize = {}; utils.getViewportInfo(content.innerWidth, content.innerHeight, {}, allowZoom, minZoom, maxZoom, {}, {}, autoSize); @@ -352,14 +357,15 @@ SimulatorCore.prototype = { // delay. But Firefox didn't support this property now, we can't get // this value from utils.getVisitedDependentComputedStyle() to check // if we should suppress 300ms delay. + /* eslint-disable no-inline-comments */ if (!allowZoom.value || // user-scalable = no minZoom.value === maxZoom.value || // minimum-scale = maximum-scale autoSize.value // width = device-width ) { + /* eslint-enable no-inline-comments */ return 0; - } else { - return 300; } + return 300; } }; From 8eca822d589a6bf6b1f0f265ebacdf31265a82f3 Mon Sep 17 00:00:00 2001 From: Greg Tatum Date: Fri, 23 Dec 2016 15:57:03 -0600 Subject: [PATCH 043/229] Bug 1245921 - Monkey patch ReactDOM event system for XUL; r+miker r=miker XUL iframes inside of a privileged XUL document propagate events between the documents. This breaks React's event model, as React captures all events at the document level. In the XUL document containing a XUL iframe, these events end up being dispatched twice. This fix tricks react into thinking the toolbox.xul document is the only root document, thus fixing the event system. MozReview-Commit-ID: B3XF3L6rax1 --HG-- extra : rebase_source : 723d21342dc876a8342882ae066b36c26daf37d2 --- devtools/client/shared/vendor/REACT_UPGRADING | 33 +++- devtools/client/shared/vendor/react-dom.js | 152 +++++++++++++++++- 2 files changed, 183 insertions(+), 2 deletions(-) diff --git a/devtools/client/shared/vendor/REACT_UPGRADING b/devtools/client/shared/vendor/REACT_UPGRADING index 0532ce93522c..dfd722e67240 100644 --- a/devtools/client/shared/vendor/REACT_UPGRADING +++ b/devtools/client/shared/vendor/REACT_UPGRADING @@ -53,9 +53,40 @@ version over: You also need to copy the ReactDOM and ReactDOMServer package. It requires React, so right now we are just manually changing the path from `react` to -`devtools/client/shared/vendor/react`. +`devtools/client/shared/vendor/react`. Also, to have React's event system working +correctly in certain XUL situations, ReactDOM must be monkey patched with a fix. This +fix is currently applied in devtools/client/shared/vendor/react-dom.js. When upgrading, +copy and paste the existing block of code into the new file in the same location. It is +delimited by a header and footer, and then the monkeyPatchReactDOM() needs to be applied +to the returned value. + +e.g. Turn this: + +``` +})(function(React) { + return React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; +}); +``` + +Into this: + +``` +})(function(React) { + //-------------------------------------------------------------------------------------- + // START MONKEY PATCH + + ... + + // END MONKEY PATCH + //-------------------------------------------------------------------------------------- + + return monkeyPatchReactDOM(React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED); +}); +``` * cp build/react-dom.js /devtools/client/shared/vendor/react-dom.js * (change `require('react')` at the top of the file to the right path) +* Copy/paste existing monkey patch +* Apply monkeyPatchReactDOM() to the returned object ReactDOM object. * cp build/react-dom.js /devtools/client/shared/vendor/react-dom-server.js * (change `require('react')` at the top of the file to the right path) diff --git a/devtools/client/shared/vendor/react-dom.js b/devtools/client/shared/vendor/react-dom.js index 7621c33dfcea..9e734f965751 100644 --- a/devtools/client/shared/vendor/react-dom.js +++ b/devtools/client/shared/vendor/react-dom.js @@ -38,5 +38,155 @@ } })(function(React) { - return React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + //-------------------------------------------------------------------------------------- + // START MONKEY PATCH + /** + * This section contains a monkey patch for React DOM, so that it functions correctly in + * certain XUL situations. React centralizes events to specific DOM nodes by only + * binding a single listener to the document of the page. It then captures these events, + * and then uses a SyntheticEvent system to dispatch these throughout the page. + * + * In privileged XUL with a XUL iframe, and React in both documents, this system breaks. + * By design, these XUL frames can still talk to each other, while in a normal HTML + * situation, they would not be able to. The events from the XUL iframe propagate to the + * parent document as well. This leads to the React event system incorrectly dispatching + * TWO SyntheticEvents for for every ONE action. + * + * The fix here is trick React into thinking that the owning document for every node in + * a XUL iframe to be the toolbox.xul. This is done by creating a Proxy object that + * captures any usage of HTMLElement.ownerDocument, and then passing in the toolbox.xul + * document rather than (for example) the netmonitor.xul document. React will then hook + * up the event system correctly on the top level controlling document. + * + * @return {object} The proxied and monkey patched ReactDOM + */ + function monkeyPatchReactDOM(ReactDOM) { + // This is the actual monkey patched function. + const reactDomRender = monkeyPatchRender(ReactDOM); + + // Proxied method calls might need to be bound, but do this lazily with caching. + const lazyFunctionBinding = functionLazyBinder(); + + // Create a proxy, but the render property is not writable on the ReactDOM object, so + // a direct proxy will fail with an error. Instead, create a proxy on a a blank object. + // Pass on getting and setting behaviors. + return new Proxy({}, { + get: (target, name) => { + return name === "render" + ? reactDomRender + : lazyFunctionBinding(ReactDOM, name); + }, + set: (target, name, value) => { + ReactDOM[name] = value; + } + }); + }; + + /** + * Creates a function that replaces the ReactDOM.render method. It does this by + * creating a proxy for the dom node being mounted. This proxy rewrites the + * "ownerDocument" property to point to the toolbox.xul document. This function + * is only used for XUL iframes inside of a XUL document. + * + * @param {object} ReactDOM + * @return {function} The patched ReactDOM.render function. + */ + function monkeyPatchRender(ReactDOM) { + const elementProxyCache = new WeakMap(); + + return (...args) => { + const container = args[1]; + const toolboxDoc = getToolboxDocIfXulOnly(container); + + if (toolboxDoc) { + // Re-use any existing cached HTMLElement proxies. + let proxy = elementProxyCache.get(container); + + if (!proxy) { + // Proxied method calls need to be bound, but do this lazily. + const lazyFunctionBinding = functionLazyBinder(); + + // Create a proxy to the container HTMLElement. If React tries to access the + // ownerDocument, pass in the toolbox's document, as the event dispatching system + // is rooted from the toolbox document. + proxy = new Proxy(container, { + get: function (target, name) { + if (name === "ownerDocument") { + return toolboxDoc; + } + return lazyFunctionBinding(target, name); + } + }); + + elementProxyCache.set(container, proxy); + } + + // Update the args passed to ReactDOM.render. + args[1] = proxy; + } + + return ReactDOM.render.apply(this, args); + }; + } + + /** + * Try to access the containing toolbox XUL document, but only if all of the iframes + * in the heirarchy are XUL documents. Events dispatch differently in the case of all + * privileged XUL documents. Events that fire in an iframe propagate up to the parent + * frame. This does not happen when HTML is in the mix. Only return the toolbox if + * it matches the proper case of a XUL iframe inside of a XUL document. + * + * @param {HTMLElement} node - The DOM node inside of an iframe. + * @return {XULDocument|null} The toolbox.xul document, or null. + */ + function getToolboxDocIfXulOnly(node) { + // This execution context doesn't know about XULDocuments, so don't get the toolbox. + if (typeof XULDocument !== "function") { + return null; + } + + let doc = node.ownerDocument; + + while (doc instanceof XULDocument) { + const {frameElement} = doc.defaultView; + + if (!frameElement) { + // We're at the root element, and no toolbox was found. + return null; + } + + doc = frameElement.parentElement.ownerDocument; + if (doc.documentURI === "about:devtools-toolbox") { + return doc; + } + } + + return null; + } + + /** + * When accessing proxied functions, the instance becomes unbound to the method. This + * utility either passes a value through if it's not a function, or automatically binds a + * function and caches that bound function for repeated calls. + */ + function functionLazyBinder() { + const boundFunctions = {}; + + return (target, name) => { + if (typeof target[name] === "function") { + // Lazily cache function bindings. + if (boundFunctions[name]) { + return boundFunctions[name]; + } + boundFunctions[name] = target[name].bind(target); + return boundFunctions[name]; + } + return target[name]; + }; + } + + // END MONKEY PATCH + //-------------------------------------------------------------------------------------- + + return monkeyPatchReactDOM(React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED); }); From 555caa01f2fe70b0eadfcea85eb42501f61b581c Mon Sep 17 00:00:00 2001 From: Greg Tatum Date: Fri, 18 Nov 2016 15:02:21 -0600 Subject: [PATCH 044/229] Bug 1245921 - Turn toolbox toolbar into a React component r+miker r=miker MozReview-Commit-ID: 4UZbcfw2YI9 --HG-- extra : rebase_source : 9e9e8bfed8c8511ade6c7307a0201b88b0781fba --- addon-sdk/source/test/test-dev-panel.js | 12 +- .../mochitest/browser_dbg_addon-panels.js | 12 +- .../browser_dbg_on-pause-highlight.js | 15 +- .../mochitest/browser_dbg_on-pause-raise.js | 18 +- .../mochitest/browser_dbg_worker-window.js | 2 +- devtools/client/definitions.js | 5 + .../client/framework/components/moz.build | 12 + .../components/toolbox-controller.js | 151 ++++ .../framework/components/toolbox-tab.js | 62 ++ .../framework/components/toolbox-toolbar.js | 250 ++++++ devtools/client/framework/moz.build | 4 + .../framework/test/browser_devtools_api.js | 10 +- .../test/browser_new_activation_workflow.js | 2 +- .../browser_toolbox_dynamic_registration.js | 9 +- .../test/browser_toolbox_highlight.js | 102 +-- .../framework/test/browser_toolbox_hosts.js | 2 +- .../framework/test/browser_toolbox_options.js | 18 +- ...browser_toolbox_options_disable_buttons.js | 55 +- ..._toolbox_tools_per_toolbox_registration.js | 9 +- .../test/browser_toolbox_transport_events.js | 10 +- ...owser_toolbox_window_title_frame_select.js | 4 +- .../framework/toolbox-highlighter-utils.js | 4 +- devtools/client/framework/toolbox-options.js | 36 +- devtools/client/framework/toolbox.js | 823 +++++++++--------- devtools/client/framework/toolbox.xul | 23 +- .../browser_inspector_highlighter-preview.js | 2 +- .../test/browser_inspector_initialization.js | 4 +- devtools/client/locales/en-US/toolbox.dtd | 13 - .../client/locales/en-US/toolbox.properties | 15 + .../test/browser_perf-highlighted.js | 14 +- devtools/client/preferences/devtools.js | 1 + devtools/client/shared/developer-toolbar.js | 81 +- .../browser_telemetry_button_paintflashing.js | 1 + .../browser_telemetry_button_scratchpad.js | 2 + devtools/client/themes/firebug-theme.css | 40 +- devtools/client/themes/toolbars.css | 2 +- devtools/client/themes/toolbox.css | 139 ++- .../test/browser_webconsole_split.js | 135 ++- .../test/browser_webconsole_split_persist.js | 2 +- 39 files changed, 1317 insertions(+), 784 deletions(-) create mode 100644 devtools/client/framework/components/moz.build create mode 100644 devtools/client/framework/components/toolbox-controller.js create mode 100644 devtools/client/framework/components/toolbox-tab.js create mode 100644 devtools/client/framework/components/toolbox-toolbar.js diff --git a/addon-sdk/source/test/test-dev-panel.js b/addon-sdk/source/test/test-dev-panel.js index fb786b04304b..e1a3cf2b77b6 100644 --- a/addon-sdk/source/test/test-dev-panel.js +++ b/addon-sdk/source/test/test-dev-panel.js @@ -27,11 +27,13 @@ const test = function(unit) { return function*(assert) { assert.isRendered = (panel, toolbox) => { const doc = toolbox.doc; - assert.ok(doc.querySelector("[value='" + panel.label + "']"), - "panel.label is found in the developer toolbox DOM"); - assert.ok(doc.querySelector("[tooltiptext='" + panel.tooltip + "']"), - "panel.tooltip is found in the developer toolbox DOM"); - + assert.ok(Array.from(doc.querySelectorAll(".devtools-tab")) + .find(el => el.textContent === panel.label), + "panel.label is found in the developer toolbox DOM " + panel.label); + if (panel.tooltip) { + assert.ok(doc.querySelector("[title='" + panel.tooltip + "']"), + `panel.tooltip is found in the developer toolbox DOM "${panel.tooltip}"`); + } assert.ok(doc.querySelector("#toolbox-panel-" + panel.id), "toolbar panel with a matching id is present"); }; diff --git a/devtools/client/debugger/test/mochitest/browser_dbg_addon-panels.js b/devtools/client/debugger/test/mochitest/browser_dbg_addon-panels.js index aeda501b0381..5b370e1cf2e2 100644 --- a/devtools/client/debugger/test/mochitest/browser_dbg_addon-panels.js +++ b/devtools/client/debugger/test/mochitest/browser_dbg_addon-panels.js @@ -17,6 +17,7 @@ var PREFS = [ ["devtools.netmonitor.enabled", true], ["devtools.scratchpad.enabled", true] ]; + function test() { Task.spawn(function* () { // Store and enable all optional dev tools panels @@ -26,20 +27,19 @@ function test() { let addonDebugger = yield initAddonDebugger(ADDON_ID); // Check only valid tabs are shown - let tabs = addonDebugger.frame.contentDocument.getElementById("toolbox-tabs").children; + let tabs = addonDebugger.frame.contentDocument.querySelectorAll(".toolbox-tabs button") + let expectedTabs = ["webconsole", "jsdebugger", "scratchpad"]; is(tabs.length, expectedTabs.length, "displaying only " + expectedTabs.length + " tabs in addon debugger"); Array.forEach(tabs, (tab, i) => { let toolName = expectedTabs[i]; - is(tab.getAttribute("toolid"), toolName, "displaying " + toolName); + is(tab.getAttribute("data-id"), toolName, "displaying " + toolName); }); // Check no toolbox buttons are shown - let buttons = addonDebugger.frame.contentDocument.getElementById("toolbox-buttons").children; - Array.forEach(buttons, (btn, i) => { - is(btn.hidden, true, "no toolbox buttons for the addon debugger -- " + btn.className); - }); + let buttons = addonDebugger.frame.contentDocument.querySelectorAll("#toolbox-buttons-end button"); + is(buttons.length, 0, "no toolbox buttons for the addon debugger"); yield addonDebugger.destroy(); yield removeAddon(addon); diff --git a/devtools/client/debugger/test/mochitest/browser_dbg_on-pause-highlight.js b/devtools/client/debugger/test/mochitest/browser_dbg_on-pause-highlight.js index 07e2360afcb7..52f09bf565c3 100644 --- a/devtools/client/debugger/test/mochitest/browser_dbg_on-pause-highlight.js +++ b/devtools/client/debugger/test/mochitest/browser_dbg_on-pause-highlight.js @@ -35,18 +35,14 @@ function testPause() { gDebugger.gThreadClient.addOneTimeListener("paused", () => { gToolbox.selectTool("webconsole").then(() => { - ok(gToolboxTab.hasAttribute("highlighted") && - gToolboxTab.getAttribute("highlighted") == "true", + ok(gToolboxTab.classList.contains("highlighted"), "The highlighted class is present"); - ok(!gToolboxTab.hasAttribute("selected") || - gToolboxTab.getAttribute("selected") != "true", + ok(!gToolboxTab.classList.contains("selected"), "The tab is not selected"); }).then(() => gToolbox.selectTool("jsdebugger")).then(() => { - ok(gToolboxTab.hasAttribute("highlighted") && - gToolboxTab.getAttribute("highlighted") == "true", + ok(gToolboxTab.classList.contains("highlighted"), "The highlighted class is present"); - ok(gToolboxTab.hasAttribute("selected") && - gToolboxTab.getAttribute("selected") == "true", + ok(gToolboxTab.classList.contains("selected"), "...and the tab is selected, so the glow will not be present."); }).then(testResume); }); @@ -66,8 +62,7 @@ function testResume() { gToolbox.selectTool("webconsole").then(() => { ok(!gToolboxTab.classList.contains("highlighted"), "The highlighted class is not present now after the resume"); - ok(!gToolboxTab.hasAttribute("selected") || - gToolboxTab.getAttribute("selected") != "true", + ok(!gToolboxTab.classList.contains("selected"), "The tab is not selected"); }).then(() => closeDebuggerAndFinish(gPanel)); }); diff --git a/devtools/client/debugger/test/mochitest/browser_dbg_on-pause-raise.js b/devtools/client/debugger/test/mochitest/browser_dbg_on-pause-raise.js index 6f6f152477b7..8cf8fb80162d 100644 --- a/devtools/client/debugger/test/mochitest/browser_dbg_on-pause-raise.js +++ b/devtools/client/debugger/test/mochitest/browser_dbg_on-pause-raise.js @@ -79,18 +79,14 @@ add_task(function *() { } yield toolbox.selectTool("webconsole"); - ok(toolboxTab.hasAttribute("highlighted") && - toolboxTab.getAttribute("highlighted") == "true", + ok(toolboxTab.classList.contains("highlighted"), "The highlighted class is present"); - ok(!toolboxTab.hasAttribute("selected") || - toolboxTab.getAttribute("selected") != "true", + ok(!toolboxTab.classList.contains("selected"), "The tab is not selected"); yield toolbox.selectTool("jsdebugger"); - ok(toolboxTab.hasAttribute("highlighted") && - toolboxTab.getAttribute("highlighted") == "true", + ok(toolboxTab.classList.contains("highlighted"), "The highlighted class is present"); - ok(toolboxTab.hasAttribute("selected") && - toolboxTab.getAttribute("selected") == "true", + ok(toolboxTab.classList.contains("selected"), "...and the tab is selected, so the glow will not be present."); } @@ -104,11 +100,9 @@ add_task(function *() { yield onPaused; yield toolbox.selectTool("webconsole"); - ok(!toolboxTab.hasAttribute("highlighted") || - toolboxTab.getAttribute("highlighted") != "true", + ok(!toolboxTab.classList.contains("highlighted"), "The highlighted class is not present now after the resume"); - ok(!toolboxTab.hasAttribute("selected") || - toolboxTab.getAttribute("selected") != "true", + ok(!toolboxTab.classList.contains("selected"), "The tab is not selected"); } }); diff --git a/devtools/client/debugger/test/mochitest/browser_dbg_worker-window.js b/devtools/client/debugger/test/mochitest/browser_dbg_worker-window.js index 46198d31cd7f..19ef1c15cf10 100644 --- a/devtools/client/debugger/test/mochitest/browser_dbg_worker-window.js +++ b/devtools/client/debugger/test/mochitest/browser_dbg_worker-window.js @@ -48,7 +48,7 @@ add_task(function* () { "worker URL in host title"); let toolTabs = toolbox.doc.querySelectorAll(".devtools-tab"); - let activeTools = [...toolTabs].map(tab=>tab.getAttribute("toolid")); + let activeTools = [...toolTabs].map(tab=>tab.getAttribute("data-id")); is(activeTools.join(","), "webconsole,jsdebugger,scratchpad,options", "Correct set of tools supported by worker"); diff --git a/devtools/client/definitions.js b/devtools/client/definitions.js index fc85bf43965f..d8135508dbf1 100644 --- a/devtools/client/definitions.js +++ b/devtools/client/definitions.js @@ -470,6 +470,11 @@ exports.defaultThemes = [ // addons that have manually inserted toolbarbuttons into DOM. // (By default, supported target is only local tab) exports.ToolboxButtons = [ + { id: "command-button-pick", + isTargetSupported: target => { + return target.activeTab && target.activeTab.traits.frames; + } + }, { id: "command-button-frames", isTargetSupported: target => { return target.activeTab && target.activeTab.traits.frames; diff --git a/devtools/client/framework/components/moz.build b/devtools/client/framework/components/moz.build new file mode 100644 index 000000000000..96e5e94a35a8 --- /dev/null +++ b/devtools/client/framework/components/moz.build @@ -0,0 +1,12 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +DevToolsModules( + 'toolbox-controller.js', + 'toolbox-tab.js', + 'toolbox-toolbar.js', +) diff --git a/devtools/client/framework/components/toolbox-controller.js b/devtools/client/framework/components/toolbox-controller.js new file mode 100644 index 000000000000..cd212d1e8cd0 --- /dev/null +++ b/devtools/client/framework/components/toolbox-controller.js @@ -0,0 +1,151 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +const {createClass, createFactory} = require("devtools/client/shared/vendor/react"); +const ToolboxToolbar = createFactory(require("devtools/client/framework/components/toolbox-toolbar")); +const ELEMENT_PICKER_ID = "command-button-pick"; + +/** + * This component serves as a state controller for the toolbox React component. It's a + * thin layer for translating events and state of the outside world into the React update + * cycle. This solution was used to keep the amount of code changes to a minimimum while + * adapting the existing codebase to start using React. + */ +module.exports = createClass({ + displayName: "ToolboxController", + + getInitialState() { + // See the ToolboxToolbar propTypes for documentation on each of these items in state, + // and for the defintions of the props that are expected to be passed in. + return { + focusedButton: ELEMENT_PICKER_ID, + currentToolId: null, + canRender: false, + highlightedTool: "", + areDockButtonsEnabled: true, + panelDefinitions: [], + hostTypes: [], + canCloseToolbox: true, + toolboxButtons: [], + buttonIds: [], + checkedButtonsUpdated: () => { + this.forceUpdate(); + } + }; + }, + + componentWillUnmount() { + this.state.toolboxButtons.forEach(button => { + button.off("updatechecked", this.state.checkedButtonsUpdated); + }); + }, + + /** + * The button and tab ids must be known in order to be able to focus left and right + * using the arrow keys. + */ + updateButtonIds() { + const {panelDefinitions, toolboxButtons, optionsPanel, hostTypes, + canCloseToolbox} = this.state; + + // This is a little gnarly, but go through all of the state and extract the IDs. + this.setState({ + buttonIds: [ + ...toolboxButtons.filter(btn => btn.isInStartContainer).map(({id}) => id), + ...panelDefinitions.map(({id}) => id), + ...toolboxButtons.filter(btn => !btn.isInStartContainer).map(({id}) => id), + optionsPanel ? optionsPanel.id : null, + ...hostTypes.map(({position}) => "toolbox-dock-" + position), + canCloseToolbox ? "toolbox-close" : null + ].filter(id => id) + }); + + this.updateFocusedButton(); + }, + + updateFocusedButton() { + this.setFocusedButton(this.state.focusedButton); + }, + + setFocusedButton(focusedButton) { + const {buttonIds} = this.state; + + this.setState({ + focusedButton: focusedButton && buttonIds.includes(focusedButton) + ? focusedButton + : buttonIds[0] + }); + }, + + setCurrentToolId(currentToolId) { + this.setState({currentToolId}); + // Also set the currently focused button to this tool. + this.setFocusedButton(currentToolId); + }, + + setCanRender() { + this.setState({ canRender: true }); + this.updateButtonIds(); + }, + + setOptionsPanel(optionsPanel) { + this.setState({ optionsPanel }); + this.updateButtonIds(); + }, + + highlightTool(highlightedTool) { + this.setState({ highlightedTool }); + }, + + unhighlightTool(id) { + if (this.state.highlightedTool === id) { + this.setState({ highlightedTool: "" }); + } + }, + + setDockButtonsEnabled(areDockButtonsEnabled) { + this.setState({ areDockButtonsEnabled }); + this.updateButtonIds(); + }, + + setHostTypes(hostTypes) { + this.setState({ hostTypes }); + this.updateButtonIds(); + }, + + setCanCloseToolbox(canCloseToolbox) { + this.setState({ canCloseToolbox }); + this.updateButtonIds(); + }, + + setPanelDefinitions(panelDefinitions) { + this.setState({ panelDefinitions }); + this.updateButtonIds(); + }, + + setToolboxButtons(toolboxButtons) { + // Listen for updates of the checked attribute. + this.state.toolboxButtons.forEach(button => { + button.off("updatechecked", this.state.checkedButtonsUpdated); + }); + toolboxButtons.forEach(button => { + button.on("updatechecked", this.state.checkedButtonsUpdated); + }); + + this.setState({ toolboxButtons }); + this.updateButtonIds(); + }, + + setCanMinimize(canMinimize) { + /* Bug 1177463 - The minimize button is currently hidden until we agree on + the UI for it, and until bug 1173849 is fixed too. */ + + // this.setState({ canMinimize }); + }, + + render() { + return ToolboxToolbar(Object.assign({}, this.props, this.state)); + } +}); diff --git a/devtools/client/framework/components/toolbox-tab.js b/devtools/client/framework/components/toolbox-tab.js new file mode 100644 index 000000000000..643f231714a3 --- /dev/null +++ b/devtools/client/framework/components/toolbox-tab.js @@ -0,0 +1,62 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +const {DOM, createClass} = require("devtools/client/shared/vendor/react"); +const {img, button} = DOM; + +module.exports = createClass({ + displayName: "ToolboxTab", + + renderIcon(definition, isHighlighted) { + const {icon, highlightedicon} = definition; + if (!icon) { + return []; + } + return [ + img({ + className: "default-icon", + src: icon + }), + img({ + className: "highlighted-icon", + src: highlightedicon || icon + }) + ]; + }, + + render() { + const {panelDefinition, currentToolId, highlightedTool, selectTool, + focusedButton, focusButton} = this.props; + const {id, tooltip, label, iconOnly} = panelDefinition; + const isHighlighted = id === currentToolId; + + const className = [ + "devtools-tab", + panelDefinition.invertIconForLightTheme || panelDefinition.invertIconForDarkTheme + ? "icon-invertable" + : "", + panelDefinition.invertIconForLightTheme ? "icon-invertable-light-theme" : "", + panelDefinition.invertIconForDarkTheme ? "icon-invertable-dark-theme" : "", + currentToolId === id ? "selected" : "", + highlightedTool === id ? "highlighted" : "", + iconOnly ? "devtools-tab-icon-only" : "" + ].join(" "); + + return button( + { + className, + id: `toolbox-tab-${id}`, + "data-id": id, + title: tooltip, + type: "button", + tabIndex: focusedButton === id ? "0" : "-1", + onFocus: () => focusButton(id), + onClick: () => selectTool(id), + }, + ...this.renderIcon(panelDefinition, isHighlighted), + iconOnly ? null : label + ); + } +}); diff --git a/devtools/client/framework/components/toolbox-toolbar.js b/devtools/client/framework/components/toolbox-toolbar.js new file mode 100644 index 000000000000..bc8a470cd136 --- /dev/null +++ b/devtools/client/framework/components/toolbox-toolbar.js @@ -0,0 +1,250 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +const {DOM, createClass, createFactory, PropTypes} = require("devtools/client/shared/vendor/react"); +const {div, button} = DOM; +const ToolboxTab = createFactory(require("devtools/client/framework/components/toolbox-tab")); + +/** + * This is the overall component for the toolbox toolbar. It is designed to not know how + * the state is being managed, and attempts to be as pure as possible. The + * ToolboxController component controls the changing state, and passes in everything as + * props. + */ +module.exports = createClass({ + displayName: "ToolboxToolbar", + + propTypes: { + // The currently focused item (for arrow keyboard navigation) + // This ID determines the tabindex being 0 or -1. + focusedButton: PropTypes.string, + // List of command button definitions. + toolboxButtons: PropTypes.array, + // The id of the currently selected tool, e.g. "inspector" + currentToolId: PropTypes.string, + // An optionally highlighted tool, e.g. "inspector" + highlightedTool: PropTypes.string, + // List of tool panel definitions. + panelDefinitions: PropTypes.array, + // Function to select a tool based on its id. + selectTool: PropTypes.func, + // Keep a record of what button is focused. + focusButton: PropTypes.func, + // The options button definition. + optionsPanel: PropTypes.object, + // Hold off displaying the toolbar until enough information is ready for it to render + // nicely. + canRender: PropTypes.bool, + // Localization interface. + L10N: PropTypes.object, + }, + + /** + * The render function is kept fairly short for maintainability. See the individual + * render functions for how each of the sections is rendered. + */ + render() { + const containerProps = {className: "devtools-tabbar"}; + return this.props.canRender + ? ( + div( + containerProps, + renderToolboxButtonsStart(this.props), + renderTabs(this.props), + renderToolboxButtonsEnd(this.props), + renderOptions(this.props), + renderSeparator(), + renderDockButtons(this.props) + ) + ) + : div(containerProps); + } +}); + +/** + * Render all of the tabs, this takes in the panel definitions and builds out + * the buttons for each of them. + * + * @param {Array} panelDefinitions - Array of objects that define panels. + * @param {String} currentToolId - The currently selected tool's id; e.g. "inspector". + * @param {String} highlightedTool - If a tool is highlighted, this is it's id. + * @param {Function} selectTool - Function to select a tool in the toolbox. + * @param {String} focusedButton - The id of the focused button. + * @param {Function} focusButton - Keep a record of the currently focused button. + */ +function renderTabs({panelDefinitions, currentToolId, highlightedTool, selectTool, + focusedButton, focusButton}) { + // A wrapper is needed to get flex sizing correct in XUL. + return div({className: "toolbox-tabs-wrapper"}, + div({className: "toolbox-tabs"}, + ...panelDefinitions.map(panelDefinition => ToolboxTab({ + panelDefinition, + currentToolId, + highlightedTool, + selectTool, + focusedButton, + focusButton, + })) + ) + ); +} + +/** + * A little helper function to call renderToolboxButtons for buttons at the start + * of the toolbox. + */ +function renderToolboxButtonsStart(props) { + return renderToolboxButtons(props, true); +} + +/** +* A little helper function to call renderToolboxButtons for buttons at the end +* of the toolbox. + */ +function renderToolboxButtonsEnd(props) { + return renderToolboxButtons(props, false); +} + +/** + * Render all of the tabs, this takes in a list of toolbox button states. These are plain + * objects that have all of the relevant information needed to render the button. + * See Toolbox.prototype._createButtonState in devtools/client/framework/toolbox.js for + * documentation on this object. + * + * @param {Array} toolboxButtons - Array of objects that define the command buttons. + * @param {String} focusedButton - The id of the focused button. + * @param {Function} focusButton - Keep a record of the currently focused button. + * @param {boolean} isStart - Render either the starting buttons, or ending buttons. + */ +function renderToolboxButtons({toolboxButtons, focusedButton, focusButton}, isStart) { + const visibleButtons = toolboxButtons.filter(command => { + const {isVisible, isInStartContainer} = command; + return isVisible && (isStart ? isInStartContainer : !isInStartContainer); + }); + + if (visibleButtons.length === 0) { + return null; + } + + return div({id: `toolbox-buttons-${isStart ? "start" : "end"}`}, + ...visibleButtons.map(command => { + const {id, description, onClick, isChecked, className: buttonClass} = command; + return button({ + id, + title: description, + className: ( + "command-button command-button-invertable devtools-button " + + buttonClass + (isChecked ? " checked" : "") + ), + onClick: (event) => { + onClick(event); + focusButton(id); + }, + onFocus: () => focusButton(id), + tabIndex: id === focusedButton ? "0" : "-1" + }); + }) + ); +} + +/** + * The options button is a ToolboxTab just like in the renderTabs() function. However + * it is separate from the normal tabs, so deal with it separately here. + * + * @param {Object} optionsPanel - A single panel definition for the options panel. + * @param {String} currentToolId - The currently selected tool's id; e.g. "inspector". + * @param {Function} selectTool - Function to select a tool in the toolbox. + * @param {String} focusedButton - The id of the focused button. + * @param {Function} focusButton - Keep a record of the currently focused button. + */ +function renderOptions({optionsPanel, currentToolId, selectTool, focusedButton, + focusButton}) { + return div({id: "toolbox-option-container"}, ToolboxTab({ + panelDefinition: optionsPanel, + currentToolId, + selectTool, + focusedButton, + focusButton, + })); +} + +/** + * Render a separator. + */ +function renderSeparator() { + return div({ + id: "toolbox-controls-separator", + className: "devtools-separator" + }); +} + +/** + * Render the dock buttons, and handle all the cases for what type of host the toolbox + * is attached to. The following props are expected. + * + * @property {String} focusedButton - The id of the focused button. + * @property {Function} closeToolbox - Completely close the toolbox. + * @property {Array} hostTypes - Array of host type objects, containing: + * @property {String} position - Position name + * @property {Function} switchHost - Function to switch the host. + * @property {Function} focusButton - Keep a record of the currently focused button. + * @property {Object} L10N - Localization interface. + * @property {Boolean} areDockButtonsEnabled - They are not enabled in certain situations + * like when they are in the WebIDE. + * @property {Boolean} canCloseToolbox - Are the tools in a context where they can be + * closed? This is not always the case, e.g. in the + * WebIDE. + */ +function renderDockButtons(props) { + const { + focusedButton, + closeToolbox, + hostTypes, + focusButton, + L10N, + areDockButtonsEnabled, + canCloseToolbox, + } = props; + + let buttons = []; + + if (areDockButtonsEnabled) { + hostTypes.forEach(hostType => { + const id = "toolbox-dock-" + hostType.position; + buttons.push(button({ + id, + onFocus: () => focusButton(id), + className: "toolbox-dock-button devtools-button", + title: L10N.getStr(`toolboxDockButtons.${hostType.position}.tooltip`), + onClick: e => { + hostType.switchHost(); + focusButton(id); + }, + tabIndex: focusedButton === id ? "0" : "-1", + })); + }); + } + + const closeButtonId = "toolbox-close"; + + const closeButton = canCloseToolbox + ? button({ + id: closeButtonId, + onFocus: () => focusButton(closeButtonId), + className: "devtools-button", + title: L10N.getStr("toolbox.closebutton.tooltip"), + onClick: () => { + closeToolbox(); + focusButton(closeButtonId); + }, + tabIndex: focusedButton === "toolbox-close" ? "0" : "-1", + }) + : null; + + return div({id: "toolbox-controls"}, + div({id: "toolbox-dock-buttons"}, ...buttons), + closeButton + ); +} diff --git a/devtools/client/framework/moz.build b/devtools/client/framework/moz.build index 7b28b4b9e749..2b2c26f434a0 100644 --- a/devtools/client/framework/moz.build +++ b/devtools/client/framework/moz.build @@ -9,6 +9,10 @@ TEST_HARNESS_FILES.xpcshell.devtools.client.framework.test += [ 'test/shared-redux-head.js', ] +DIRS += [ + 'components', +] + DevToolsModules( 'about-devtools-toolbox.js', 'attach-thread.js', diff --git a/devtools/client/framework/test/browser_devtools_api.js b/devtools/client/framework/test/browser_devtools_api.js index 72d415c0b6b5..93e3838eb668 100644 --- a/devtools/client/framework/test/browser_devtools_api.js +++ b/devtools/client/framework/test/browser_devtools_api.js @@ -152,11 +152,13 @@ var continueTests = Task.async(function* (toolbox, panel) { ok(toolbox.getCurrentPanel(), "panel value is correct"); is(toolbox.currentToolId, toolId2, "toolbox _currentToolId is correct"); - ok(!toolbox.doc.getElementById("toolbox-tab-" + toolId2).hasAttribute("icon-invertable"), - "The tool tab does not have the invertable attribute"); + ok(!toolbox.doc.getElementById("toolbox-tab-" + toolId2) + .classList.contains("icon-invertable"), + "The tool tab does not have the invertable class"); - ok(toolbox.doc.getElementById("toolbox-tab-inspector").hasAttribute("icon-invertable"), - "The builtin tool tabs do have the invertable attribute"); + ok(toolbox.doc.getElementById("toolbox-tab-inspector") + .classList.contains("icon-invertable"), + "The builtin tool tabs do have the invertable class"); let toolDefinitions = gDevTools.getToolDefinitionMap(); ok(toolDefinitions.has(toolId2), "The tool is in gDevTools"); diff --git a/devtools/client/framework/test/browser_new_activation_workflow.js b/devtools/client/framework/test/browser_new_activation_workflow.js index 4092bf1a7421..365a6486b96b 100644 --- a/devtools/client/framework/test/browser_new_activation_workflow.js +++ b/devtools/client/framework/test/browser_new_activation_workflow.js @@ -41,7 +41,7 @@ function checkToolLoading() { function selectAndCheckById(id) { return toolbox.selectTool(id).then(function () { let tab = toolbox.doc.getElementById("toolbox-tab-" + id); - is(tab.hasAttribute("selected"), true, "The " + id + " tab is selected"); + is(tab.classList.contains("selected"), true, "The " + id + " tab is selected"); }); } diff --git a/devtools/client/framework/test/browser_toolbox_dynamic_registration.js b/devtools/client/framework/test/browser_toolbox_dynamic_registration.js index 57cb88190e6c..8b89a88701fd 100644 --- a/devtools/client/framework/test/browser_toolbox_dynamic_registration.js +++ b/devtools/client/framework/test/browser_toolbox_dynamic_registration.js @@ -97,8 +97,9 @@ function toolUnregistered(event, toolId) function cleanup() { - toolbox.destroy(); - toolbox = null; - gBrowser.removeCurrentTab(); - finish(); + toolbox.destroy().then(() => {; + toolbox = null; + gBrowser.removeCurrentTab(); + finish(); + }) } diff --git a/devtools/client/framework/test/browser_toolbox_highlight.js b/devtools/client/framework/test/browser_toolbox_highlight.js index d197fdc99195..fe6e9bc804b4 100644 --- a/devtools/client/framework/test/browser_toolbox_highlight.js +++ b/devtools/client/framework/test/browser_toolbox_highlight.js @@ -8,74 +8,78 @@ var {Toolbox} = require("devtools/client/framework/toolbox"); var toolbox = null; function test() { - const URL = "data:text/plain;charset=UTF-8,Nothing to see here, move along"; + Task.spawn(function* () { + const URL = "data:text/plain;charset=UTF-8,Nothing to see here, move along"; - const TOOL_ID_1 = "jsdebugger"; - const TOOL_ID_2 = "webconsole"; + const TOOL_ID_1 = "jsdebugger"; + const TOOL_ID_2 = "webconsole"; + yield addTab(URL); - addTab(URL).then(() => { - let target = TargetFactory.forTab(gBrowser.selectedTab); - gDevTools.showToolbox(target, TOOL_ID_1, Toolbox.HostType.BOTTOM) - .then(aToolbox => { - toolbox = aToolbox; - // select tool 2 - toolbox.selectTool(TOOL_ID_2) - // and highlight the first one - .then(highlightTab.bind(null, TOOL_ID_1)) - // to see if it has the proper class. - .then(checkHighlighted.bind(null, TOOL_ID_1)) - // Now switch back to first tool - .then(() => toolbox.selectTool(TOOL_ID_1)) - // to check again. But there is no easy way to test if - // it is showing orange or not. - .then(checkNoHighlightWhenSelected.bind(null, TOOL_ID_1)) - // Switch to tool 2 again - .then(() => toolbox.selectTool(TOOL_ID_2)) - // and check again. - .then(checkHighlighted.bind(null, TOOL_ID_1)) - // Now unhighlight the tool - .then(unhighlightTab.bind(null, TOOL_ID_1)) - // to see the classes gone. - .then(checkNoHighlight.bind(null, TOOL_ID_1)) - // Now close the toolbox and exit. - .then(() => executeSoon(() => { - toolbox.destroy() - .then(() => { - toolbox = null; - gBrowser.removeCurrentTab(); - finish(); - }); - })); - }); + const target = TargetFactory.forTab(gBrowser.selectedTab); + toolbox = yield gDevTools.showToolbox(target, TOOL_ID_1, Toolbox.HostType.BOTTOM) + + // select tool 2 + yield toolbox.selectTool(TOOL_ID_2) + // and highlight the first one + yield highlightTab(TOOL_ID_1); + // to see if it has the proper class. + yield checkHighlighted(TOOL_ID_1); + // Now switch back to first tool + yield toolbox.selectTool(TOOL_ID_1); + // to check again. But there is no easy way to test if + // it is showing orange or not. + yield checkNoHighlightWhenSelected(TOOL_ID_1); + // Switch to tool 2 again + yield toolbox.selectTool(TOOL_ID_2); + // and check again. + yield checkHighlighted(TOOL_ID_1); + // Now unhighlight the tool + yield unhighlightTab(TOOL_ID_1); + // to see the classes gone. + yield checkNoHighlight(TOOL_ID_1); + + // Now close the toolbox and exit. + executeSoon(() => { + toolbox.destroy().then(() => { + toolbox = null; + gBrowser.removeCurrentTab(); + finish(); + }); + }); + }) + .catch(error => { + ok(false, "There was an error running the test."); }); } function highlightTab(toolId) { - info("Highlighting tool " + toolId + "'s tab."); - toolbox.highlightTool(toolId); + info(`Highlighting tool ${toolId}'s tab.`); + return toolbox.highlightTool(toolId); } function unhighlightTab(toolId) { - info("Unhighlighting tool " + toolId + "'s tab."); - toolbox.unhighlightTool(toolId); + info(`Unhighlighting tool ${toolId}'s tab.`); + return toolbox.unhighlightTool(toolId); } function checkHighlighted(toolId) { let tab = toolbox.doc.getElementById("toolbox-tab-" + toolId); - ok(tab.hasAttribute("highlighted"), "The highlighted attribute is present"); - ok(!tab.hasAttribute("selected") || tab.getAttribute("selected") != "true", - "The tab is not selected"); + ok(tab.classList.contains("highlighted"), + `The highlighted class is present in ${toolId}.`); + ok(!tab.classList.contains("selected"), + `The tab is not selected in ${toolId}`); } function checkNoHighlightWhenSelected(toolId) { let tab = toolbox.doc.getElementById("toolbox-tab-" + toolId); - ok(tab.hasAttribute("highlighted"), "The highlighted attribute is present"); - ok(tab.hasAttribute("selected") && tab.getAttribute("selected") == "true", - "and the tab is selected, so the orange glow will not be present."); + ok(tab.classList.contains("highlighted"), + `The highlighted class is present in ${toolId}`); + ok(tab.classList.contains("selected"), + `And the tab is selected, so the orange glow will not be present. in ${toolId}`); } function checkNoHighlight(toolId) { let tab = toolbox.doc.getElementById("toolbox-tab-" + toolId); - ok(!tab.hasAttribute("highlighted"), - "The highlighted attribute is not present"); + ok(!tab.classList.contains("highlighted"), + `The highlighted class is not present in ${toolId}`); } diff --git a/devtools/client/framework/test/browser_toolbox_hosts.js b/devtools/client/framework/test/browser_toolbox_hosts.js index e16563ba7c87..adb0512a6af0 100644 --- a/devtools/client/framework/test/browser_toolbox_hosts.js +++ b/devtools/client/framework/test/browser_toolbox_hosts.js @@ -134,6 +134,6 @@ function* testPreviousHost() { } function checkToolboxLoaded(iframe) { - let tabs = iframe.contentDocument.getElementById("toolbox-tabs"); + let tabs = iframe.contentDocument.querySelector(".toolbox-tabs"); ok(tabs, "toolbox UI has been loaded into iframe"); } diff --git a/devtools/client/framework/test/browser_toolbox_options.js b/devtools/client/framework/test/browser_toolbox_options.js index 57430cefa080..79d4216617fc 100644 --- a/devtools/client/framework/test/browser_toolbox_options.js +++ b/devtools/client/framework/test/browser_toolbox_options.js @@ -293,22 +293,8 @@ function checkRegistered(toolId, deferred, event, data) { if (data == toolId) { ok(true, "Correct tool added back"); // checking tab on the toolbox - let radio = doc.getElementById("toolbox-tab-" + toolId); - ok(radio, "Tab added back for " + toolId); - if (radio.previousSibling) { - ok(+radio.getAttribute("ordinal") >= - +radio.previousSibling.getAttribute("ordinal"), - "Inserted tab's ordinal is greater than equal to its previous tab." + - "Expected " + radio.getAttribute("ordinal") + " >= " + - radio.previousSibling.getAttribute("ordinal")); - } - if (radio.nextSibling) { - ok(+radio.getAttribute("ordinal") < - +radio.nextSibling.getAttribute("ordinal"), - "Inserted tab's ordinal is less than its next tab. Expected " + - radio.getAttribute("ordinal") + " < " + - radio.nextSibling.getAttribute("ordinal")); - } + let button = doc.getElementById("toolbox-tab-" + toolId); + ok(button, "Tab added back for " + toolId); } else { ok(false, "Something went wrong, " + toolId + " was not registered"); } diff --git a/devtools/client/framework/test/browser_toolbox_options_disable_buttons.js b/devtools/client/framework/test/browser_toolbox_options_disable_buttons.js index 09cde4393e24..9240963192da 100644 --- a/devtools/client/framework/test/browser_toolbox_options_disable_buttons.js +++ b/devtools/client/framework/test/browser_toolbox_options_disable_buttons.js @@ -60,19 +60,16 @@ function testPreferenceAndUIStateIsConsistent() { let checkNodes = [...panelWin.document.querySelectorAll( "#enabled-toolbox-buttons-box input[type=checkbox]")]; let toolboxButtonNodes = [...doc.querySelectorAll(".command-button")]; - toolboxButtonNodes.push(doc.getElementById("command-button-frames")); - let toggleableTools = toolbox.toolboxButtons; // The noautohide button is only displayed in the browser toolbox - toggleableTools = toggleableTools.filter( + let toolbarButtons = toolbox.toolbarButtons.filter( tool => tool.id != "command-button-noautohide"); - for (let tool of toggleableTools) { + for (let tool of toolbarButtons) { let isVisible = getBoolPref(tool.visibilityswitch); - let button = toolboxButtonNodes.filter( - toolboxButton => toolboxButton.id === tool.id)[0]; - is(!button.hasAttribute("hidden"), isVisible, + let button = toolboxButtonNodes.find(toolboxButton => toolboxButton.id === tool.id); + is(!!button, isVisible, "Button visibility matches pref for " + tool.id); let check = checkNodes.filter(node => node.id === tool.id)[0]; @@ -84,48 +81,52 @@ function testPreferenceAndUIStateIsConsistent() { function testToggleToolboxButtons() { let checkNodes = [...panelWin.document.querySelectorAll( "#enabled-toolbox-buttons-box input[type=checkbox]")]; - let toolboxButtonNodes = [...doc.querySelectorAll(".command-button")]; - let toggleableTools = toolbox.toolboxButtons; // The noautohide button is only displayed in the browser toolbox, and the element // picker button is not toggleable. - toggleableTools = toggleableTools.filter( - tool => tool.id != "command-button-noautohide" && tool.id != "command-button-pick"); - toolboxButtonNodes = toolboxButtonNodes.filter( - btn => btn.id != "command-button-noautohide" && btn.id != "command-button-pick"); + let toolbarButtons = toolbox.toolbarButtons.filter( + tool => tool.id != "command-button-noautohide"); - is(checkNodes.length, toggleableTools.length, + let visibleToolbarButtons = toolbox.toolbarButtons.filter(tool => tool.isVisible); + + let toolbarButtonNodes = [...doc.querySelectorAll(".command-button")].filter( + btn => btn.id != "command-button-noautohide"); + + is(checkNodes.length, toolbarButtons.length, "All of the buttons are toggleable."); - is(checkNodes.length, toolboxButtonNodes.length, + is(visibleToolbarButtons.length, toolbarButtonNodes.length, "All of the DOM buttons are toggleable."); - for (let tool of toggleableTools) { + for (let tool of toolbarButtons) { let id = tool.id; let matchedCheckboxes = checkNodes.filter(node => node.id === id); - let matchedButtons = toolboxButtonNodes.filter(button => button.id === id); + let matchedButtons = toolbarButtonNodes.filter(button => button.id === id); is(matchedCheckboxes.length, 1, "There should be a single toggle checkbox for: " + id); - is(matchedButtons.length, 1, - "There should be a DOM button for: " + id); - is(matchedButtons[0], tool.button, - "DOM buttons should match for: " + id); + if (tool.isVisible) { + is(matchedButtons.length, 1, + "There should be a DOM button for the visible: " + id); + is(matchedButtons[0].getAttribute("title"), tool.description, + "The tooltip for button matches the tool definition."); + } else { + is(matchedButtons.length, 0, + "There should not be a DOM button for the invisible: " + id); + } - is(matchedCheckboxes[0].nextSibling.textContent, tool.label, + is(matchedCheckboxes[0].nextSibling.textContent, tool.description, "The label for checkbox matches the tool definition."); - is(matchedButtons[0].getAttribute("title"), tool.label, - "The tooltip for button matches the tool definition."); } // Store modified pref names so that they can be cleared on error. - for (let tool of toggleableTools) { + for (let tool of toolbarButtons) { let pref = tool.visibilityswitch; modifiedPrefs.push(pref); } // Try checking each checkbox, making sure that it changes the preference for (let node of checkNodes) { - let tool = toggleableTools.filter( - toggleableTool => toggleableTool.id === node.id)[0]; + let tool = toolbarButtons.filter( + commandButton => commandButton.id === node.id)[0]; let isVisible = getBoolPref(tool.visibilityswitch); testPreferenceAndUIStateIsConsistent(); diff --git a/devtools/client/framework/test/browser_toolbox_tools_per_toolbox_registration.js b/devtools/client/framework/test/browser_toolbox_tools_per_toolbox_registration.js index 8c43286597c9..51e0084cec87 100644 --- a/devtools/client/framework/test/browser_toolbox_tools_per_toolbox_registration.js +++ b/devtools/client/framework/test/browser_toolbox_tools_per_toolbox_registration.js @@ -132,8 +132,9 @@ function toolboxToolUnregistered() { } function cleanup() { - toolbox.destroy(); - toolbox = null; - gBrowser.removeCurrentTab(); - finish(); + toolbox.destroy().then(() => {; + toolbox = null; + gBrowser.removeCurrentTab(); + finish(); + }); } diff --git a/devtools/client/framework/test/browser_toolbox_transport_events.js b/devtools/client/framework/test/browser_toolbox_transport_events.js index 1e2b67ac48f7..106596cc2961 100644 --- a/devtools/client/framework/test/browser_toolbox_transport_events.js +++ b/devtools/client/framework/test/browser_toolbox_transport_events.js @@ -30,10 +30,12 @@ function cleanUp(toolbox) { off(DebuggerClient, "connect", onDebuggerClientConnect); toolbox.destroy().then(function () { - gBrowser.removeCurrentTab(); - executeSoon(function () { - finish(); - }); + setTimeout(() => { + gBrowser.removeCurrentTab(); + executeSoon(function () { + finish(); + }); + }, 1000); }); } diff --git a/devtools/client/framework/test/browser_toolbox_window_title_frame_select.js b/devtools/client/framework/test/browser_toolbox_window_title_frame_select.js index 1e3d6664684b..b0abfbc744eb 100644 --- a/devtools/client/framework/test/browser_toolbox_window_title_frame_select.js +++ b/devtools/client/framework/test/browser_toolbox_window_title_frame_select.js @@ -44,11 +44,11 @@ add_task(function* () { // Open frame menu and wait till it's available on the screen. // Also check 'open' attribute on the command button. let btn = toolbox.doc.getElementById("command-button-frames"); - ok(!btn.getAttribute("open"), "The open attribute must not be present"); + ok(!btn.classList.contains("checked"), "The checked class must not be present"); let menu = toolbox.showFramesMenu({target: btn}); yield once(menu, "open"); - is(btn.getAttribute("open"), "true", "The open attribute must be set"); + ok(btn.classList.contains("checked"), "The checked class must be set"); // Verify that the frame list menu is populated let frames = menu.items; diff --git a/devtools/client/framework/toolbox-highlighter-utils.js b/devtools/client/framework/toolbox-highlighter-utils.js index 3488e7cf8ccd..0bff5a4d7bcf 100644 --- a/devtools/client/framework/toolbox-highlighter-utils.js +++ b/devtools/client/framework/toolbox-highlighter-utils.js @@ -122,7 +122,7 @@ exports.getHighlighterUtils = function (toolbox) { } isPicking = true; - toolbox.pickerButtonChecked = true; + toolbox.pickerButton.isChecked = true; yield toolbox.selectTool("inspector"); toolbox.on("select", cancelPicker); @@ -156,7 +156,7 @@ exports.getHighlighterUtils = function (toolbox) { } isPicking = false; - toolbox.pickerButtonChecked = false; + toolbox.pickerButton.isChecked = false; if (isRemoteHighlightable()) { yield toolbox.highlighter.cancelPick(); diff --git a/devtools/client/framework/toolbox-options.js b/devtools/client/framework/toolbox-options.js index 80d377854347..9885ac5fb08a 100644 --- a/devtools/client/framework/toolbox-options.js +++ b/devtools/client/framework/toolbox-options.js @@ -135,30 +135,36 @@ OptionsPanel.prototype = { } }, - setupToolbarButtonsList: function () { + setupToolbarButtonsList: Task.async(function* () { + // Ensure the toolbox is open, and the buttons are all set up. + yield this.toolbox.isOpen; + let enabledToolbarButtonsBox = this.panelDoc.getElementById( "enabled-toolbox-buttons-box"); - let toggleableButtons = this.toolbox.toolboxButtons; - let setToolboxButtonsVisibility = - this.toolbox.setToolboxButtonsVisibility.bind(this.toolbox); + let toolbarButtons = this.toolbox.toolbarButtons; + + if (!toolbarButtons) { + console.warn("The command buttons weren't initiated yet."); + return; + } let onCheckboxClick = (checkbox) => { - let toolDefinition = toggleableButtons.filter( + let commandButton = toolbarButtons.filter( toggleableButton => toggleableButton.id === checkbox.id)[0]; Services.prefs.setBoolPref( - toolDefinition.visibilityswitch, checkbox.checked); - setToolboxButtonsVisibility(); + commandButton.visibilityswitch, checkbox.checked); + this.toolbox.updateToolboxButtonsVisibility(); }; - let createCommandCheckbox = tool => { + let createCommandCheckbox = button => { let checkboxLabel = this.panelDoc.createElement("label"); let checkboxSpanLabel = this.panelDoc.createElement("span"); - checkboxSpanLabel.textContent = tool.label; + checkboxSpanLabel.textContent = button.description; let checkboxInput = this.panelDoc.createElement("input"); checkboxInput.setAttribute("type", "checkbox"); - checkboxInput.setAttribute("id", tool.id); - if (InfallibleGetBoolPref(tool.visibilityswitch)) { + checkboxInput.setAttribute("id", button.id); + if (button.isVisible) { checkboxInput.setAttribute("checked", true); } checkboxInput.addEventListener("change", @@ -169,14 +175,14 @@ OptionsPanel.prototype = { return checkboxLabel; }; - for (let tool of toggleableButtons) { - if (!tool.isTargetSupported(this.toolbox.target)) { + for (let button of toolbarButtons) { + if (!button.isTargetSupported(this.toolbox.target)) { continue; } - enabledToolbarButtonsBox.appendChild(createCommandCheckbox(tool)); + enabledToolbarButtonsBox.appendChild(createCommandCheckbox(button)); } - }, + }), setupToolsList: function () { let defaultToolsBox = this.panelDoc.getElementById("default-tools-box"); diff --git a/devtools/client/framework/toolbox.js b/devtools/client/framework/toolbox.js index a413d004ceb7..c7c14df2967d 100644 --- a/devtools/client/framework/toolbox.js +++ b/devtools/client/framework/toolbox.js @@ -7,6 +7,7 @@ const MAX_ORDINAL = 99; const SPLITCONSOLE_ENABLED_PREF = "devtools.toolbox.splitconsoleEnabled"; const SPLITCONSOLE_HEIGHT_PREF = "devtools.toolbox.splitconsoleHeight"; +const DISABLE_AUTOHIDE_PREF = "ui.popup.disable_autohide"; const OS_HISTOGRAM = "DEVTOOLS_OS_ENUMERATED_PER_USER"; const OS_IS_64_BITS = "DEVTOOLS_OS_IS_64_BITS_PER_USER"; const HOST_HISTOGRAM = "DEVTOOLS_TOOLBOX_HOST"; @@ -62,6 +63,8 @@ loader.lazyRequireGetter(this, "settleAll", "devtools/shared/ThreadSafeDevToolsUtils", true); loader.lazyRequireGetter(this, "ToolboxButtons", "devtools/client/definitions", true); +loader.lazyRequireGetter(this, "ViewHelpers", + "devtools/client/shared/widgets/view-helpers", true); loader.lazyGetter(this, "registerHarOverlay", () => { return require("devtools/client/netmonitor/har/toolbox-overlay").register; @@ -105,7 +108,7 @@ function Toolbox(target, selectedTool, hostType, contentWindow, frameId) { this._toolRegistered = this._toolRegistered.bind(this); this._toolUnregistered = this._toolUnregistered.bind(this); this._refreshHostTitle = this._refreshHostTitle.bind(this); - this._toggleAutohide = this._toggleAutohide.bind(this); + this._toggleNoAutohide = this._toggleNoAutohide.bind(this); this.showFramesMenu = this.showFramesMenu.bind(this); this._updateFrames = this._updateFrames.bind(this); this._splitConsoleOnKeypress = this._splitConsoleOnKeypress.bind(this); @@ -127,12 +130,13 @@ function Toolbox(target, selectedTool, hostType, contentWindow, frameId) { this._onPerformanceFrontEvent = this._onPerformanceFrontEvent.bind(this); this._onBottomHostWillChange = this._onBottomHostWillChange.bind(this); this._toggleMinimizeMode = this._toggleMinimizeMode.bind(this); - this._onTabbarFocus = this._onTabbarFocus.bind(this); - this._onTabbarArrowKeypress = this._onTabbarArrowKeypress.bind(this); + this._onToolbarFocus = this._onToolbarFocus.bind(this); + this._onToolbarArrowKeypress = this._onToolbarArrowKeypress.bind(this); this._onPickerClick = this._onPickerClick.bind(this); this._onPickerKeypress = this._onPickerKeypress.bind(this); this._onPickerStarted = this._onPickerStarted.bind(this); this._onPickerStopped = this._onPickerStopped.bind(this); + this.selectTool = this.selectTool.bind(this); this._target.on("close", this.destroy); @@ -143,6 +147,9 @@ function Toolbox(target, selectedTool, hostType, contentWindow, frameId) { this._hostType = hostType; + this._isOpenDeferred = defer(); + this.isOpen = this._isOpenDeferred.promise; + EventEmitter.decorate(this); this._target.on("navigate", this._refreshHostTitle); @@ -180,7 +187,52 @@ Toolbox.prototype = { SIDE_ENABLED: "devtools.toolbox.sideEnabled", }, - currentToolId: null, + get currentToolId() { + return this._currentToolId; + }, + + set currentToolId(id) { + this._currentToolId = id; + this.component.setCurrentToolId(id); + }, + + get panelDefinitions() { + return this._panelDefinitions; + }, + + set panelDefinitions(definitions) { + this._panelDefinitions = definitions; + this._combineAndSortPanelDefinitions(); + }, + + get visibleAdditionalTools() { + if (!this._visibleAdditionalTools) { + this._visibleAdditionalTools = []; + } + + return this._visibleAdditionalTools; + }, + + set visibleAdditionalTools(tools) { + this._visibleAdditionalTools = tools; + this._combineAndSortPanelDefinitions(); + }, + + /** + * Combines the built-in panel definitions and the additional tool definitions that + * can be set by add-ons. + */ + _combineAndSortPanelDefinitions() { + const definitions = [...this._panelDefinitions, ...this.getVisibleAdditionalTools()]; + definitions.sort(definition => { + return -1 * (definition.ordinal == undefined || definition.ordinal < 0 + ? MAX_ORDINAL + : definition.ordinal + ); + }); + this.component.setPanelDefinitions(definitions); + }, + lastUsedToolId: null, /** @@ -366,21 +418,10 @@ Toolbox.prototype = { this.isReady = true; let framesPromise = this._listFrames(); - this.closeButton = this.doc.getElementById("toolbox-close"); - this.closeButton.addEventListener("click", this.destroy, true); - Services.prefs.addObserver("devtools.cache.disabled", this._applyCacheSettings, false); Services.prefs.addObserver("devtools.serviceWorkers.testing.enabled", this._applyServiceWorkersTestingSettings, false); - Services.prefs.addObserver("devtools.screenshot.clipboard.enabled", - this._buildButtons, false); - - let framesMenu = this.doc.getElementById("command-button-frames"); - framesMenu.addEventListener("click", this.showFramesMenu, false); - - let noautohideMenu = this.doc.getElementById("command-button-noautohide"); - noautohideMenu.addEventListener("click", this._toggleAutohide, true); this.textBoxContextMenuPopup = this.doc.getElementById("toolbox-textbox-context-popup"); @@ -390,6 +431,10 @@ Toolbox.prototype = { this.shortcuts = new KeyShortcuts({ window: this.doc.defaultView }); + // Get the DOM element to mount the ToolboxController to. + this._componentMount = this.doc.getElementById("toolbox-toolbar-mount"); + + this._mountReactComponent(); this._buildDockButtons(); this._buildOptions(); this._buildTabs(); @@ -403,10 +448,7 @@ Toolbox.prototype = { ZoomKeys.register(this.win); } - this.tabbar = this.doc.querySelector(".devtools-tabbar"); - this.tabbar.addEventListener("focus", this._onTabbarFocus, true); - this.tabbar.addEventListener("click", this._onTabbarFocus, true); - this.tabbar.addEventListener("keypress", this._onTabbarArrowKeypress); + this._componentMount.addEventListener("keypress", this._onToolbarArrowKeypress); this.webconsolePanel = this.doc.querySelector("#toolbox-panel-webconsole"); this.webconsolePanel.height = Services.prefs.getIntPref(SPLITCONSOLE_HEIGHT_PREF); @@ -424,6 +466,10 @@ Toolbox.prototype = { this._defaultToolId = "webconsole"; } + // Start rendering the toolbox toolbar before selecting the tool, as the tools + // can take a few hundred milliseconds seconds to start up. + this.component.setCanRender(); + yield this.selectTool(this._defaultToolId); // Wait until the original tool is selected so that the split @@ -451,6 +497,7 @@ Toolbox.prototype = { } this.emit("ready"); + this._isOpenDeferred.resolve(); }.bind(this)).then(null, console.error.bind(console)); }, @@ -470,6 +517,10 @@ Toolbox.prototype = { return this.browserRequire("devtools/client/shared/vendor/react-redux"); }, + get ToolboxController() { + return this.browserRequire("devtools/client/framework/components/toolbox-controller"); + }, + // Return HostType id for telemetry _getTelemetryHostId: function () { switch (this.hostType) { @@ -492,6 +543,51 @@ Toolbox.prototype = { this._telemetry.log(HOST_HISTOGRAM, this._getTelemetryHostId()); }, + /** + * Create a simple object to store the state of a toolbox button. The checked state of + * a button can be updated arbitrarily outside of the scope of the toolbar and its + * controllers. In order to simplify this interaction this object emits an + * "updatechecked" event any time the isChecked value is updated, allowing any consuming + * components to listen and respond to updates. + * + * @param {Object} options: + * + * @property {String} id - The id of the button or command. + * @property {String} className - An optional additional className for the button. + * @property {String} description - The value that will display as a tooltip and in + * the options panel for enabling/disabling. + * @property {Function} onClick - The function to run when the button is activated by + * click or keyboard shortcut. + * @property {Boolean} isInStartContainer - Buttons can either be placed at the start + * of the toolbar, or at the end. + */ + _createButtonState: function (options) { + let isChecked = false; + const {id, className, description, onClick, isInStartContainer} = options; + const button = { + id, + className, + description, + onClick, + get isChecked() { + return isChecked; + }, + set isChecked(value) { + isChecked = value; + this.emit("updatechecked"); + }, + // The preference for having this button visible. + visibilityswitch: `devtools.${id}.enabled`, + // The toolbar has a container at the start and end of the toolbar for + // holding buttons. By default the buttons are placed in the end container. + isInStartContainer: !!isInStartContainer + }; + + EventEmitter.decorate(button); + + return button; + }, + _buildOptions: function () { let selectOptions = (name, event) => { // Flip back to the last used panel if we are already @@ -754,29 +850,14 @@ Toolbox.prototype = { * the host changes. */ _buildDockButtons: function () { - let dockBox = this.doc.getElementById("toolbox-dock-buttons"); - - while (dockBox.firstChild) { - dockBox.removeChild(dockBox.firstChild); - } - if (!this._target.isLocalTab) { + this.component.setDockButtonsEnabled(false); return; } // Bottom-type host can be minimized, add a button for this. if (this.hostType == Toolbox.HostType.BOTTOM) { - let minimizeBtn = this.doc.createElementNS(HTML_NS, "button"); - minimizeBtn.id = "toolbox-dock-bottom-minimize"; - minimizeBtn.className = "devtools-button"; - /* Bug 1177463 - The minimize button is currently hidden until we agree on - the UI for it, and until bug 1173849 is fixed too. */ - minimizeBtn.setAttribute("hidden", "true"); - - minimizeBtn.addEventListener("click", this._toggleMinimizeMode); - dockBox.appendChild(minimizeBtn); - // Show the button in its maximized state. - this._onBottomHostMaximized(); + this.component.setCanMinimize(true); // Maximize again when a tool gets selected. this.on("before-select", this._onToolSelectWhileMinimized); @@ -784,14 +865,12 @@ Toolbox.prototype = { this.once("host-will-change", this._onBottomHostWillChange); } - if (this.hostType == Toolbox.HostType.WINDOW) { - this.closeButton.setAttribute("hidden", "true"); - } else { - this.closeButton.removeAttribute("hidden"); - } + this.component.setDockButtonsEnabled(true); + this.component.setCanCloseToolbox(this.hostType !== Toolbox.HostType.WINDOW); let sideEnabled = Services.prefs.getBoolPref(this._prefs.SIDE_ENABLED); + let hostTypes = []; for (let type in Toolbox.HostType) { let position = Toolbox.HostType[type]; if (position == this.hostType || @@ -800,39 +879,21 @@ Toolbox.prototype = { continue; } - let button = this.doc.createElementNS(HTML_NS, "button"); - button.id = "toolbox-dock-" + position; - button.className = "toolbox-dock-button devtools-button"; - button.setAttribute("title", L10N.getStr("toolboxDockButtons." + - position + ".tooltip")); - button.addEventListener("click", this.switchHost.bind(this, position)); - - dockBox.appendChild(button); + hostTypes.push({ + position, + switchHost: this.switchHost.bind(this, position) + }); } - }, - _getMinimizeButtonShortcutTooltip: function () { - let str = L10N.getStr("toolbox.minimize.key"); - let key = KeyShortcuts.parseElectronKey(this.win, str); - return "(" + KeyShortcuts.stringify(key) + ")"; + this.component.setHostTypes(hostTypes); }, _onBottomHostMinimized: function () { - let btn = this.doc.querySelector("#toolbox-dock-bottom-minimize"); - btn.className = "minimized"; - - btn.setAttribute("title", - L10N.getStr("toolboxDockButtons.bottom.maximize") + " " + - this._getMinimizeButtonShortcutTooltip()); + this.component.setMinimizeState("minimized"); }, _onBottomHostMaximized: function () { - let btn = this.doc.querySelector("#toolbox-dock-bottom-minimize"); - btn.className = "maximized"; - - btn.setAttribute("title", - L10N.getStr("toolboxDockButtons.bottom.minimize") + " " + - this._getMinimizeButtonShortcutTooltip()); + this.component.setMinimizeState("maximized"); }, _onToolSelectWhileMinimized: function () { @@ -867,8 +928,8 @@ Toolbox.prototype = { // Calculate the height to which the host should be minimized so the // tabbar is still visible. - let toolbarHeight = this.tabbar.getBoxQuads({box: "content"})[0].bounds - .height; + let toolbarHeight = this._componentMount.getBoxQuads({box: "content"})[0].bounds + .height; this.postMessage({ name: "toggle-minimize-mode", toolbarHeight @@ -876,50 +937,63 @@ Toolbox.prototype = { }, /** - * Add tabs to the toolbox UI for registered tools + * Initiate ToolboxTabs React component and all it's properties. Do the initial render. */ _buildTabs: function () { - // Build tabs for global registered tools. - for (let definition of gDevTools.getToolDefinitionArray()) { - this._buildTabForTool(definition); - } + // Get the initial list of tab definitions. This list can be amended at a later time + // by tools registering themselves. + const definitions = gDevTools.getToolDefinitionArray(); + definitions.forEach(definition => this._buildPanelForTool(definition)); + + // Get the definitions that will only affect the main tab area. + this.panelDefinitions = definitions.filter(definition => + definition.isTargetSupported(this._target) && definition.id !== "options"); + + this.optionsDefinition = definitions.find(({id}) => id === "options"); + // The options tool is treated slightly differently, and is in a different area. + this.component.setOptionsPanel(definitions.find(({id}) => id === "options")); + }, + + _mountReactComponent: function () { + // Ensure the toolbar doesn't try to render until the tool is ready. + const element = this.React.createElement(this.ToolboxController, { + L10N, + currentToolId: this.currentToolId, + selectTool: this.selectTool, + closeToolbox: this.destroy, + focusButton: this._onToolbarFocus, + toggleMinimizeMode: this._toggleMinimizeMode, + }); + + this.component = this.ReactDOM.render(element, this._componentMount); }, /** - * Get all dev tools tab bar focusable elements. These are visible elements - * such as buttons or elements with tabindex. - */ - get tabbarFocusableElms() { - return [...this.tabbar.querySelectorAll( - "[tabindex]:not([hidden]), button:not([hidden])")]; - }, - - /** - * Reset tabindex attributes across all focusable elements inside the tabbar. + * Reset tabindex attributes across all focusable elements inside the toolbar. * Only have one element with tabindex=0 at a time to make sure that tabbing - * results in navigating away from the tabbar container. + * results in navigating away from the toolbar container. * @param {FocusEvent} event */ - _onTabbarFocus: function (event) { - this.tabbarFocusableElms.forEach(elm => - elm.setAttribute("tabindex", event.target === elm ? "0" : "-1")); + _onToolbarFocus: function (id) { + this.component.setFocusedButton(id); }, /** - * On left/right arrow press, attempt to move the focus inside the tabbar to - * the previous/next focusable element. + * On left/right arrow press, attempt to move the focus inside the toolbar to + * the previous/next focusable element. This is not in the React component + * as it is difficult to coordinate between different component elements. + * The components are responsible for setting the correct tabindex value + * for if they are the focused element. * @param {KeyboardEvent} event */ - _onTabbarArrowKeypress: function (event) { + _onToolbarArrowKeypress: function (event) { let { key, target } = event; - let focusableElms = this.tabbarFocusableElms; - let curIndex = focusableElms.indexOf(target); + let buttons = [...this._componentMount.querySelectorAll("button")]; + let curIndex = buttons.indexOf(target); if (curIndex === -1) { console.warn(target + " is not found among Developer Tools tab bar " + - "focusable elements. It needs to either be a button or have " + - "tabindex. If it is intended to be hidden, 'hidden' attribute must " + - "be used."); + "focusable elements."); return; } @@ -930,19 +1004,17 @@ Toolbox.prototype = { if (curIndex === 0) { return; } - newTarget = focusableElms[curIndex - 1]; + newTarget = buttons[curIndex - 1]; } else if (key === "ArrowRight") { // Do nothing if already at the end. - if (curIndex === focusableElms.length - 1) { + if (curIndex === buttons.length - 1) { return; } - newTarget = focusableElms[curIndex + 1]; + newTarget = buttons[curIndex + 1]; } else { return; } - focusableElms.forEach(elm => - elm.setAttribute("tabindex", newTarget === elm ? "0" : "-1")); newTarget.focus(); event.preventDefault(); @@ -952,62 +1024,70 @@ Toolbox.prototype = { /** * Add buttons to the UI as specified in the devtools.toolbox.toolbarSpec pref */ - _buildButtons: function () { - if (this.target.getTrait("highlightable")) { - this._buildPickerButton(); + _buildButtons: Task.async(function* () { + // Beyond the normal preference filtering + this.toolbarButtons = [ + this._buildPickerButton(), + this._buildFrameButton(), + yield this._buildNoAutoHideButton() + ]; + + // Build buttons from the GCLI commands only if the GCLI actor is supported and the + // target isn't chrome. + if (this.target.hasActor("gcli") && !this.target.chrome) { + const options = { + environment: CommandUtils.createEnvironment(this, "_target") + }; + + this._requisition = yield CommandUtils.createRequisition(this.target, options); + const spec = this.getToolbarSpec(); + const commandButtons = yield CommandUtils.createCommandButtons( + spec, this.target, this.doc, this._requisition, this._createButtonState); + this.toolbarButtons = [...this.toolbarButtons, ...commandButtons]; } - this.setToolboxButtonsVisibility(); - - // Old servers don't have a GCLI Actor, so just return - if (!this.target.hasActor("gcli")) { - return promise.resolve(); - } - // Disable gcli in browser toolbox until there is usages of it - if (this.target.chrome) { - return promise.resolve(); - } - - const options = { - environment: CommandUtils.createEnvironment(this, "_target") - }; - - return CommandUtils.createRequisition(this.target, options).then(requisition => { - this._requisition = requisition; - - let spec = this.getToolbarSpec(); - return CommandUtils.createButtons(spec, this.target, this.doc, requisition) - .then(buttons => { - let container = this.doc.getElementById("toolbox-buttons"); - buttons.forEach(button => { - let currentButton = this.doc.getElementById(button.id); - if (currentButton) { - container.replaceChild(button, currentButton); - } else { - container.appendChild(button); - } - }); - this.setToolboxButtonsVisibility(); - }); + // Mutate the objects here with their visibility. + this.toolbarButtons.forEach(command => { + const definition = ToolboxButtons.find(t => t.id === command.id); + command.isTargetSupported = definition.isTargetSupported + ? definition.isTargetSupported + : target => target.isLocalTab; + command.isVisible = this._commandIsVisible(command.id); }); + + this.component.setToolboxButtons(this.toolbarButtons); + }), + + /** + * Button to select a frame for the inspector to target. + */ + _buildFrameButton() { + this.frameButton = this._createButtonState({ + id: "command-button-frames", + description: L10N.getStr("toolbox.frames.tooltip"), + onClick: this.showFramesMenu + }); + + return this.frameButton; }, /** - * Adding the element picker button is done here unlike the other buttons - * since we want it to work for remote targets too + * Button that disables/enables auto-hiding XUL pop-ups. When enabled, XUL + * pop-ups will not automatically close when they lose focus. */ - _buildPickerButton: function () { - this._pickerButton = this.doc.createElementNS(HTML_NS, "button"); - this._pickerButton.id = "command-button-pick"; - this._pickerButton.className = - "command-button command-button-invertable devtools-button"; - this._pickerButton.setAttribute("title", L10N.getStr("pickButton.tooltip")); + _buildNoAutoHideButton: Task.async(function* () { + this.autohideButton = this._createButtonState({ + id: "command-button-noautohide", + description: L10N.getStr("toolbox.noautohide.tooltip"), + onClick: this._toggleNoAutohide + }); - let container = this.doc.querySelector("#toolbox-picker-container"); - container.appendChild(this._pickerButton); + this._isDisableAutohideEnabled().then(enabled => { + this.autohideButton.isChecked = enabled; + }); - this._pickerButton.addEventListener("click", this._onPickerClick, false); - }, + return this.autohideButton; + }), /** * Toggle the picker, but also decide whether or not the highlighter should @@ -1041,6 +1121,21 @@ Toolbox.prototype = { this.doc.removeEventListener("keypress", this._onPickerKeypress, true); }, + /** + * The element picker button enables the ability to select a DOM node by clicking + * it on the page. + */ + _buildPickerButton() { + this.pickerButton = this._createButtonState({ + id: "command-button-pick", + description: L10N.getStr("pickButton.tooltip"), + onClick: this._onPickerClick, + isInStartContainer: true + }); + + return this.pickerButton; + }, + /** * Apply the current cache setting from devtools.cache.disabled to this * toolbox's tab. @@ -1070,9 +1165,9 @@ Toolbox.prototype = { } }, - /** - * Get the toolbar spec for toolbox - */ + /** + * Get the toolbar spec for toolbox + */ getToolbarSpec: function () { let spec = CommandUtils.getCommandbarSpec("devtools.toolbox.toolbarSpec"); // Special case for screenshot command button to check for clipboard preference @@ -1088,173 +1183,73 @@ Toolbox.prototype = { return spec; }, - /** - * Setter for the checked state of the picker button in the toolbar - * @param {Boolean} isChecked - */ - set pickerButtonChecked(isChecked) { - if (isChecked) { - this._pickerButton.setAttribute("checked", "true"); - } else { - this._pickerButton.removeAttribute("checked"); - } - }, + /** + * Return all toolbox buttons (command buttons, plus any others that were + * added manually). /** - * Return all toolbox buttons (command buttons, plus any others that were - * added manually). + * Update the visibility of the buttons. */ - get toolboxButtons() { - return ToolboxButtons.map(options => { - let button = this.doc.getElementById(options.id); - // Some buttons may not exist inside of Browser Toolbox - if (!button) { - return false; - } - - return { - id: options.id, - button: button, - label: button.getAttribute("title"), - visibilityswitch: "devtools." + options.id + ".enabled", - isTargetSupported: options.isTargetSupported - ? options.isTargetSupported - : target => target.isLocalTab, - }; - }).filter(button=>button); - }, - - /** - * Ensure the visibility of each toolbox button matches the - * preference value. Simply hide buttons that are preffed off. - */ - setToolboxButtonsVisibility: function () { - this.toolboxButtons.forEach(buttonSpec => { - let { visibilityswitch, button, isTargetSupported } = buttonSpec; - let on = true; - try { - on = Services.prefs.getBoolPref(visibilityswitch); - } catch (ex) { - // Do nothing. - } - - on = on && isTargetSupported(this.target); - - if (button) { - if (on) { - button.removeAttribute("hidden"); - } else { - button.setAttribute("hidden", "true"); - } - } + updateToolboxButtonsVisibility() { + this.toolbarButtons.forEach(command => { + command.isVisible = this._commandIsVisible(command.id); }); - - this._updateNoautohideButton(); + this.component.setToolboxButtons(this.toolbarButtons); }, /** - * Build a tab for one tool definition and add to the toolbox + * Ensure the visibility of each toolbox button matches the preference value. + */ + _commandIsVisible: function (id) { + const { + isTargetSupported, + visibilityswitch + } = this.toolbarButtons.find(btn => btn.id === id); + + let visible = true; + try { + visible = Services.prefs.getBoolPref(visibilityswitch); + } catch (ex) { + // Do nothing. + } + + if (isTargetSupported) { + return visible && isTargetSupported(this.target); + } + + return visible; + }, + + /** + * Build a panel for a tool definition. * * @param {string} toolDefinition * Tool definition of the tool to build a tab for. */ - _buildTabForTool: function (toolDefinition) { + _buildPanelForTool: function (toolDefinition) { if (!toolDefinition.isTargetSupported(this._target)) { return; } - let tabs = this.doc.getElementById("toolbox-tabs"); let deck = this.doc.getElementById("toolbox-deck"); - let id = toolDefinition.id; if (toolDefinition.ordinal == undefined || toolDefinition.ordinal < 0) { toolDefinition.ordinal = MAX_ORDINAL; } - let radio = this.doc.createElement("radio"); - // The radio element is not being used in the conventional way, thus - // the devtools-tab class replaces the radio XBL binding with its base - // binding (the control-item binding). - radio.className = "devtools-tab"; - radio.id = "toolbox-tab-" + id; - radio.setAttribute("toolid", id); - radio.setAttribute("tabindex", "0"); - radio.setAttribute("ordinal", toolDefinition.ordinal); - radio.setAttribute("tooltiptext", toolDefinition.tooltip); - if (toolDefinition.invertIconForLightTheme) { - radio.setAttribute("icon-invertable", "light-theme"); - } else if (toolDefinition.invertIconForDarkTheme) { - radio.setAttribute("icon-invertable", "dark-theme"); - } - - radio.addEventListener("command", this.selectTool.bind(this, id)); - - // spacer lets us center the image and label, while allowing cropping - let spacer = this.doc.createElement("spacer"); - spacer.setAttribute("flex", "1"); - radio.appendChild(spacer); - - if (toolDefinition.icon) { - let image = this.doc.createElement("image"); - image.className = "default-icon"; - image.setAttribute("src", - toolDefinition.icon || toolDefinition.highlightedicon); - radio.appendChild(image); - // Adding the highlighted icon image - image = this.doc.createElement("image"); - image.className = "highlighted-icon"; - image.setAttribute("src", - toolDefinition.highlightedicon || toolDefinition.icon); - radio.appendChild(image); - } - - if (toolDefinition.label && !toolDefinition.iconOnly) { - let label = this.doc.createElement("label"); - label.setAttribute("value", toolDefinition.label); - label.setAttribute("crop", "end"); - label.setAttribute("flex", "1"); - radio.appendChild(label); - } - if (!toolDefinition.bgTheme) { toolDefinition.bgTheme = "theme-toolbar"; } - let vbox = this.doc.createElement("vbox"); - vbox.className = "toolbox-panel " + toolDefinition.bgTheme; + let panel = this.doc.createElement("vbox"); + panel.className = "toolbox-panel " + toolDefinition.bgTheme; // There is already a container for the webconsole frame. if (!this.doc.getElementById("toolbox-panel-" + id)) { - vbox.id = "toolbox-panel-" + id; + panel.id = "toolbox-panel-" + id; } - if (id === "options") { - // Options panel is special. It doesn't belong in the same container as - // the other tabs. - radio.setAttribute("role", "button"); - let optionTabContainer = this.doc.getElementById("toolbox-option-container"); - optionTabContainer.appendChild(radio); - deck.appendChild(vbox); - } else { - radio.setAttribute("role", "tab"); - - // If there is no tab yet, or the ordinal to be added is the largest one. - if (tabs.childNodes.length == 0 || - tabs.lastChild.getAttribute("ordinal") <= toolDefinition.ordinal) { - tabs.appendChild(radio); - deck.appendChild(vbox); - } else { - // else, iterate over all the tabs to get the correct location. - Array.some(tabs.childNodes, (node, i) => { - if (+node.getAttribute("ordinal") > toolDefinition.ordinal) { - tabs.insertBefore(radio, node); - deck.insertBefore(vbox, deck.childNodes[i]); - return true; - } - return false; - }); - } - } + deck.appendChild(panel); this._addKeysToWindow(); }, @@ -1282,7 +1277,21 @@ Toolbox.prototype = { * the array of additional tool definitions registered on this toolbox. */ getAdditionalTools() { - return Array.from(this.additionalToolDefinitions.values()); + if (this._additionalToolDefinitions) { + return Array.from(this.additionalToolDefinitions.values()); + } + return []; + }, + + /** + * Get the additional tools that have been registered and are visible. + * + * @return {Array} + * the array of additional tool definitions registered on this toolbox. + */ + getVisibleAdditionalTools() { + return this.visibleAdditionalTools + .map(toolId => this.additionalToolDefinitions.get(toolId)); }, /** @@ -1313,9 +1322,11 @@ Toolbox.prototype = { throw new Error("Tool definition already registered: " + definition.id); } - this.additionalToolDefinitions.set(definition.id, definition); - this._buildTabForTool(definition); + this.visibleAdditionalTools = [...this.visibleAdditionalTools, definition.id]; + + this._combineAndSortPanelDefinitions(); + this._buildPanelForTool(definition); }, /** @@ -1330,8 +1341,10 @@ Toolbox.prototype = { toolId); } - this.unloadTool(toolId); this.additionalToolDefinitions.delete(toolId); + this.visibleAdditionalTools = this.visibleAdditionalTools + .filter(id => id !== toolId); + this.unloadTool(toolId); }, /** @@ -1385,6 +1398,7 @@ Toolbox.prototype = { if (!iframe.parentNode) { let vbox = this.doc.getElementById("toolbox-panel-" + id); vbox.appendChild(iframe); + vbox.visibility = "visible"; } let onLoad = () => { @@ -1522,18 +1536,6 @@ Toolbox.prototype = { selectTool: function (id) { this.emit("before-select", id); - let tabs = this.doc.querySelectorAll(".devtools-tab"); - this.selectSingleNode(tabs, "toolbox-tab-" + id); - - // If options is selected, the separator between it and the - // command buttons should be hidden. - let sep = this.doc.getElementById("toolbox-controls-separator"); - if (id === "options") { - sep.setAttribute("invisible", "true"); - } else { - sep.removeAttribute("invisible"); - } - if (this.currentToolId == id) { let panel = this._toolPanels.get(id); if (panel) { @@ -1554,9 +1556,10 @@ Toolbox.prototype = { throw new Error("Can't select tool, wait for toolbox 'ready' event"); } - let tab = this.doc.getElementById("toolbox-tab-" + id); - - if (tab) { + // Check if the tool exists. + if (this.panelDefinitions.find((definition) => definition.id === id) || + id === "options" || + this.additionalToolDefinitions.get(id)) { if (this.currentToolId) { this._telemetry.toolClosed(this.currentToolId); } @@ -1565,12 +1568,6 @@ Toolbox.prototype = { throw new Error("No tool found"); } - let tabstrip = this.doc.getElementById("toolbox-tabs"); - - // select the right tab, making 0th index the default tab if right tab not - // found. - tabstrip.selectedItem = tab || tabstrip.childNodes[0]; - // and select the right iframe let toolboxPanels = this.doc.querySelectorAll(".toolbox-panel"); this.selectSingleNode(toolboxPanels, "toolbox-panel-" + id); @@ -1644,9 +1641,9 @@ Toolbox.prototype = { this._splitConsole = true; Services.prefs.setBoolPref(SPLITCONSOLE_ENABLED_PREF, true); this._refreshConsoleDisplay(); - this.emit("split-console"); return this.loadTool("webconsole").then(() => { + this.emit("split-console"); this.focusConsoleInput(); }); }, @@ -1697,24 +1694,28 @@ Toolbox.prototype = { * Loads the tool next to the currently selected tool. */ selectNextTool: function () { - let tools = this.doc.querySelectorAll(".devtools-tab"); - let selected = this.doc.querySelector(".devtools-tab[selected]"); - let nextIndex = [...tools].indexOf(selected) + 1; - let next = tools[nextIndex] || tools[0]; - let tool = next.getAttribute("toolid"); - return this.selectTool(tool); + const index = this.panelDefinitions.findIndex(({id}) => id === this.currentToolId); + let definition = this.panelDefinitions[index + 1]; + if (!definition) { + definition = index === -1 + ? this.panelDefinitions[0] + : this.optionsDefinition; + } + return this.selectTool(definition.id); }, /** * Loads the tool just left to the currently selected tool. */ selectPreviousTool: function () { - let tools = this.doc.querySelectorAll(".devtools-tab"); - let selected = this.doc.querySelector(".devtools-tab[selected]"); - let prevIndex = [...tools].indexOf(selected) - 1; - let prev = tools[prevIndex] || tools[tools.length - 1]; - let tool = prev.getAttribute("toolid"); - return this.selectTool(tool); + const index = this.panelDefinitions.findIndex(({id}) => id === this.currentToolId); + let definition = this.panelDefinitions[index - 1]; + if (!definition) { + definition = index === -1 + ? this.panelDefinitions[this.panelDefinitions.length - 1] + : this.optionsDefinition; + } + return this.selectTool(definition.id); }, /** @@ -1723,10 +1724,12 @@ Toolbox.prototype = { * @param {string} id * The id of the tool to highlight */ - highlightTool: function (id) { - let tab = this.doc.getElementById("toolbox-tab-" + id); - tab && tab.setAttribute("highlighted", "true"); - }, + highlightTool: Task.async(function* (id) { + if (!this.component) { + yield this.isOpen; + } + this.component.highlightTool(id); + }), /** * De-highlights the tool's tab. @@ -1734,10 +1737,12 @@ Toolbox.prototype = { * @param {string} id * The id of the tool to unhighlight */ - unhighlightTool: function (id) { - let tab = this.doc.getElementById("toolbox-tab-" + id); - tab && tab.removeAttribute("highlighted"); - }, + unhighlightTool: Task.async(function* (id) { + if (!this.component) { + yield this.isOpen; + } + this.component.unhighlightTool(id); + }), /** * Raise the toolbox host. @@ -1767,36 +1772,35 @@ Toolbox.prototype = { // Returns an instance of the preference actor get _preferenceFront() { - return this.target.root.then(rootForm => { - return getPreferenceFront(this.target.client, rootForm); + return this.isOpen.then(() => { + return this.target.root.then(rootForm => { + return getPreferenceFront(this.target.client, rootForm); + }); }); }, - _toggleAutohide: Task.async(function* () { - let prefName = "ui.popup.disable_autohide"; + _toggleNoAutohide: Task.async(function* () { let front = yield this._preferenceFront; - let current = yield front.getBoolPref(prefName); - yield front.setBoolPref(prefName, !current); + let toggledValue = !(yield this._isDisableAutohideEnabled(front)); - this._updateNoautohideButton(); + front.setBoolPref(DISABLE_AUTOHIDE_PREF, toggledValue); + + this.autohideButton.isChecked = toggledValue; }), - _updateNoautohideButton: Task.async(function* () { - let menu = this.doc.getElementById("command-button-noautohide"); - if (menu.getAttribute("hidden") === "true") { - return; + _isDisableAutohideEnabled: Task.async(function* (prefFront) { + // Ensure that the tools are open, and the button is visible. + yield this.isOpen; + if (!this.autohideButton.isVisible) { + return false; } - if (!this.target.root) { - return; - } - let prefName = "ui.popup.disable_autohide"; - let front = yield this._preferenceFront; - let current = yield front.getBoolPref(prefName); - if (current) { - menu.setAttribute("checked", "true"); - } else { - menu.removeAttribute("checked"); + + // If no prefFront was provided, then get one. + if (!prefFront) { + prefFront = yield this._preferenceFront; } + + return yield prefFront.getBoolPref(DISABLE_AUTOHIDE_PREF); }), _listFrames: function (event) { @@ -1838,11 +1842,11 @@ Toolbox.prototype = { }); menu.once("open").then(() => { - target.setAttribute("open", "true"); + this.frameButton.isChecked = true; }); menu.once("close").then(() => { - target.removeAttribute("open"); + this.frameButton.isChecked = false; }); // Show a drop down menu with frames. @@ -1930,13 +1934,12 @@ Toolbox.prototype = { // Note that only child frame has parentID. let frame = this.frameMap.get(this.selectedFrameId); let topFrameSelected = frame ? !frame.parentID : false; - let button = this.doc.getElementById("command-button-frames"); - button.removeAttribute("checked"); + this._framesButtonChecked = false; // If non-top level frame is selected the toolbar button is // marked as 'checked' indicating that a child frame is active. if (!topFrameSelected && this.selectedFrameId) { - button.setAttribute("checked", "true"); + this._framesButtonChecked = false; } }, @@ -2040,25 +2043,32 @@ Toolbox.prototype = { this._toolPanels.delete(toolId); } - let radio = this.doc.getElementById("toolbox-tab-" + toolId); let panel = this.doc.getElementById("toolbox-panel-" + toolId); - if (radio) { - if (this.currentToolId == toolId) { - let nextToolName = null; - if (radio.nextSibling) { - nextToolName = radio.nextSibling.getAttribute("toolid"); - } - if (radio.previousSibling) { - nextToolName = radio.previousSibling.getAttribute("toolid"); - } - if (nextToolName) { - this.selectTool(nextToolName); - } + // Select another tool. + if (this.currentToolId == toolId) { + let index = this.panelDefinitions.findIndex(({id}) => id === toolId); + let nextTool = this.panelDefinitions[index + 1]; + let previousTool = this.panelDefinitions[index - 1]; + let toolNameToSelect; + + if (nextTool) { + toolNameToSelect = nextTool.id; + } + if (previousTool) { + toolNameToSelect = previousTool.id; + } + if (toolNameToSelect) { + this.selectTool(toolNameToSelect); } - radio.parentNode.removeChild(radio); } + // Remove this tool from the current panel definitions. + this.panelDefinitions = this.panelDefinitions.filter(({id}) => id !== toolId); + this.visibleAdditionalTools = this.visibleAdditionalTools + .filter(id => id !== toolId); + this._combineAndSortPanelDefinitions(); + if (panel) { panel.parentNode.removeChild(panel); } @@ -2080,17 +2090,28 @@ Toolbox.prototype = { * Id of the tool that was registered */ _toolRegistered: function (event, toolId) { - let tool = this.getToolDefinition(toolId); - if (!tool) { - // Ignore if the tool is not found, when a per-toolbox tool - // has been toggle in the toolbox options view, every toolbox will receive - // the toolbox-register and toolbox-unregister events. - return; + // Tools can either be in the global devtools, or added to this specific toolbox + // as an additional tool. + let definition = gDevTools.getToolDefinition(toolId); + let isAdditionalTool = false; + if (!definition) { + definition = this.additionalToolDefinitions.get(toolId); + isAdditionalTool = true; + } + + if (definition.isTargetSupported(this._target)) { + if (isAdditionalTool) { + this.visibleAdditionalTools = [...this.visibleAdditionalTools, toolId]; + this._combineAndSortPanelDefinitions(); + } else { + this.panelDefinitions = this.panelDefinitions.concat(definition); + } + this._buildPanelForTool(definition); + + // Emit the event so tools can listen to it from the toolbox level + // instead of gDevTools. + this.emit("tool-registered", toolId); } - this._buildTabForTool(tool); - // Emit the event so tools can listen to it from the toolbox level - // instead of gDevTools. - this.emit("tool-registered", toolId); }, /** @@ -2146,6 +2167,10 @@ Toolbox.prototype = { return; } + // Ensure that the inspector isn't still being initiated, otherwise race conditions + // in the initialization process can throw errors. + yield this._initInspector; + // Releasing the walker (if it has been created) // This can fail, but in any case, we want to continue destroying the // inspector/highlighter/selection @@ -2236,20 +2261,15 @@ Toolbox.prototype = { this._saveSplitConsoleHeight); this.webconsolePanel = null; } - if (this.closeButton) { - this.closeButton.removeEventListener("click", this.destroy, true); - this.closeButton = null; - } if (this.textBoxContextMenuPopup) { this.textBoxContextMenuPopup.removeEventListener("popupshowing", this._updateTextBoxMenuItems, true); this.textBoxContextMenuPopup = null; } - if (this.tabbar) { - this.tabbar.removeEventListener("focus", this._onTabbarFocus, true); - this.tabbar.removeEventListener("click", this._onTabbarFocus, true); - this.tabbar.removeEventListener("keypress", this._onTabbarArrowKeypress); - this.tabbar = null; + if (this._componentMount) { + this._componentMount.removeEventListener("keypress", this._onToolbarArrowKeypress); + this.ReactDOM.unmountComponentAtNode(this._componentMount); + this._componentMount = null; } let outstanding = []; @@ -2278,17 +2298,14 @@ Toolbox.prototype = { } // Destroying the walker and inspector fronts - outstanding.push(this.destroyInspector().then(() => { - // Removing buttons - if (this._pickerButton) { - this._pickerButton.removeEventListener("click", this._togglePicker, false); - this._pickerButton = null; - } - })); + outstanding.push(this.destroyInspector()); // Destroy the profiler connection outstanding.push(this.destroyPerformance()); + // Destroy the preference front + outstanding.push(this.destroyPreference()); + // Detach the thread detachThread(this._threadClient); this._threadClient = null; @@ -2451,6 +2468,14 @@ Toolbox.prototype = { this._performance = null; }), + /** + * Destroy the preferences actor when the toolbox is unloaded. + */ + destroyPreference: Task.async(function* () { + let front = yield this._preferenceFront; + front.destroy(); + }), + /** * Called when any event comes from the PerformanceFront. If the performance tool is * already loaded when the first event comes in, immediately unbind this handler, as diff --git a/devtools/client/framework/toolbox.xul b/devtools/client/framework/toolbox.xul index 94aaecebdd8a..0ac4dd8afb32 100644 --- a/devtools/client/framework/toolbox.xul +++ b/devtools/client/framework/toolbox.xul @@ -47,28 +47,7 @@
- - - - - - - - - - - - +
- - - - - diff --git a/devtools/client/locales/en-US/toolbox.properties b/devtools/client/locales/en-US/toolbox.properties index 225bd320bc7d..0217b578959c 100644 --- a/devtools/client/locales/en-US/toolbox.properties +++ b/devtools/client/locales/en-US/toolbox.properties @@ -158,3 +158,18 @@ toolbox.minimize.key=CmdOrCtrl+Shift+U # LOCALIZATION NOTE (toolbox.toggleHost.key) # Key shortcut used to move the toolbox in bottom or side of the browser window toolbox.toggleHost.key=CmdOrCtrl+Shift+D + +# LOCALIZATION NOTE (toolbox.frames.tooltip): This is the label for +# the iframes menu list that appears only when the document has some. +# It allows you to switch the context of the whole toolbox. +toolbox.frames.tooltip=Select an iframe as the currently targeted document + +# LOCALIZATION NOTE (toolbox.noautohide.tooltip): This is the label for +# the button to force the popups/panels to stay visible on blur. +# This is only visible in the browser toolbox as it is meant for +# addon developers and Firefox contributors. +toolbox.noautohide.tooltip=Disable popup auto hide + +# LOCALIZATION NOTE (toolbox.closebutton.tooltip): This is the tooltip for +# the close button the developer tools toolbox. +toolbox.closebutton.tooltip=Close Developer Tools diff --git a/devtools/client/performance/test/browser_perf-highlighted.js b/devtools/client/performance/test/browser_perf-highlighted.js index 72ad905476dd..111747ce0296 100644 --- a/devtools/client/performance/test/browser_perf-highlighted.js +++ b/devtools/client/performance/test/browser_perf-highlighted.js @@ -21,27 +21,27 @@ add_task(function* () { let tab = toolbox.doc.getElementById("toolbox-tab-performance"); yield console.profile("rust"); - yield waitUntil(() => tab.hasAttribute("highlighted")); + yield waitUntil(() => tab.classList.contains("highlighted")); - ok(tab.hasAttribute("highlighted"), "Performance tab is highlighted during recording " + - "from console.profile when unloaded."); + ok(tab.classList.contains("highlighted"), "Performance tab is highlighted during " + + "recording from console.profile when unloaded."); yield console.profileEnd("rust"); - yield waitUntil(() => !tab.hasAttribute("highlighted")); + yield waitUntil(() => !tab.classList.contains("highlighted")); - ok(!tab.hasAttribute("highlighted"), + ok(!tab.classList.contains("highlighted"), "Performance tab is no longer highlighted when console.profile recording finishes."); let { panel } = yield initPerformanceInTab({ tab: target.tab }); yield startRecording(panel); - ok(tab.hasAttribute("highlighted"), + ok(tab.classList.contains("highlighted"), "Performance tab is highlighted during recording while in performance tool."); yield stopRecording(panel); - ok(!tab.hasAttribute("highlighted"), + ok(!tab.classList.contains("highlighted"), "Performance tab is no longer highlighted when recording finishes."); yield teardownToolboxAndRemoveTab(panel); diff --git a/devtools/client/preferences/devtools.js b/devtools/client/preferences/devtools.js index b17362ff8693..325eb17b4472 100644 --- a/devtools/client/preferences/devtools.js +++ b/devtools/client/preferences/devtools.js @@ -37,6 +37,7 @@ pref("devtools.toolbox.splitconsoleEnabled", false); pref("devtools.toolbox.splitconsoleHeight", 100); // Toolbox Button preferences +pref("devtools.command-button-pick.enabled", true); pref("devtools.command-button-frames.enabled", true); pref("devtools.command-button-splitconsole.enabled", true); pref("devtools.command-button-paintflashing.enabled", false); diff --git a/devtools/client/shared/developer-toolbar.js b/devtools/client/shared/developer-toolbar.js index e80193dbe848..009006f64d5c 100644 --- a/devtools/client/shared/developer-toolbar.js +++ b/devtools/client/shared/developer-toolbar.js @@ -10,7 +10,6 @@ const defer = require("devtools/shared/defer"); const Services = require("Services"); const { TargetFactory } = require("devtools/client/framework/target"); const Telemetry = require("devtools/client/shared/telemetry"); -const {ViewHelpers} = require("devtools/client/shared/widgets/view-helpers"); const {LocalizationHelper} = require("devtools/shared/l10n"); const L10N = new LocalizationHelper("devtools/client/locales/toolbox.properties"); const {Task} = require("devtools/shared/task"); @@ -67,71 +66,56 @@ var CommandUtils = { }, /** - * A toolbarSpec is an array of strings each of which is a GCLI command. + * Create a list of props for React components that manage the state of the buttons. + * + * @param {Array} toolbarSpec - An array of strings each of which is a GCLI command. + * @param {Object} target + * @param {Object} document - Used to listen to unload event of the window. + * @param {Requisition} requisition + * @param {Function} createButtonState - A function that provides a common interface + * to create a button for the toolbox. + * + * @return {Array} List of ToolboxButton objects.. * * Warning: this method uses the unload event of the window that owns the * buttons that are of type checkbox. this means that we don't properly * unregister event handlers until the window is destroyed. */ - createButtons: function (toolbarSpec, target, document, requisition) { + createCommandButtons: function (toolbarSpec, target, document, requisition, + createButtonState) { return util.promiseEach(toolbarSpec, typed => { // Ask GCLI to parse the typed string (doesn't execute it) return requisition.update(typed).then(() => { - let button = document.createElementNS(NS_XHTML, "button"); - // Ignore invalid commands let command = requisition.commandAssignment.value; if (command == null) { throw new Error("No command '" + typed + "'"); } - - if (command.buttonId != null) { - button.id = command.buttonId; - if (command.buttonClass != null) { - button.className = command.buttonClass; - } - } else { - button.setAttribute("text-as-image", "true"); - button.setAttribute("label", command.name); + if (!command.buttonId) { + throw new Error("Attempting to add a button to the toolbar, and the command " + + "did not have an id."); } + // Create the ToolboxButton. + let button = createButtonState({ + id: command.buttonId, + className: command.buttonClass, + description: command.tooltipText || command.description, + onClick: requisition.updateExec.bind(requisition, typed) + }); - button.classList.add("devtools-button"); - - if (command.tooltipText != null) { - button.setAttribute("title", command.tooltipText); - } else if (command.description != null) { - button.setAttribute("title", command.description); - } - - button.addEventListener("click", - requisition.updateExec.bind(requisition, typed)); - - button.addEventListener("keypress", (event) => { - if (ViewHelpers.isSpaceOrReturn(event)) { - event.preventDefault(); - requisition.updateExec(typed); - } - }, false); - - // Allow the command button to be toggleable - let onChange = null; + // Allow the command button to be toggleable. if (command.state) { - button.setAttribute("autocheck", false); - /** * The onChange event should be called with an event object that * contains a target property which specifies which target the event * applies to. For legacy reasons the event object can also contain * a tab property. */ - onChange = (eventName, ev) => { + const onChange = (eventName, ev) => { if (ev.target == target || ev.tab == target.tab) { let updateChecked = (checked) => { - if (checked) { - button.setAttribute("checked", true); - } else if (button.hasAttribute("checked")) { - button.removeAttribute("checked"); - } + // This will emit a ToolboxButton update event. + button.isChecked = checked; }; // isChecked would normally be synchronous. An annoying quirk @@ -150,14 +134,13 @@ var CommandUtils = { command.state.onChange(target, onChange); onChange("", { target: target }); + + document.defaultView.addEventListener("unload", function (event) { + if (command.state.offChange) { + command.state.offChange(target, onChange); + } + }, { once: true }); } - document.defaultView.addEventListener("unload", function (event) { - if (onChange && command.state.offChange) { - command.state.offChange(target, onChange); - } - button.remove(); - button = null; - }, { once: true }); requisition.clear(); diff --git a/devtools/client/shared/test/browser_telemetry_button_paintflashing.js b/devtools/client/shared/test/browser_telemetry_button_paintflashing.js index dcce8f738c5f..1e3e78de09a8 100644 --- a/devtools/client/shared/test/browser_telemetry_button_paintflashing.js +++ b/devtools/client/shared/test/browser_telemetry_button_paintflashing.js @@ -13,6 +13,7 @@ const TOOL_DELAY = 200; add_task(function* () { yield addTab(TEST_URI); let Telemetry = loadTelemetryAndRecordLogs(); + yield pushPref("devtools.command-button-paintflashing.enabled", true); let target = TargetFactory.forTab(gBrowser.selectedTab); let toolbox = yield gDevTools.showToolbox(target, "inspector"); diff --git a/devtools/client/shared/test/browser_telemetry_button_scratchpad.js b/devtools/client/shared/test/browser_telemetry_button_scratchpad.js index e191bb25777a..11ee1f726fdf 100644 --- a/devtools/client/shared/test/browser_telemetry_button_scratchpad.js +++ b/devtools/client/shared/test/browser_telemetry_button_scratchpad.js @@ -14,6 +14,8 @@ add_task(function* () { yield addTab(TEST_URI); let Telemetry = loadTelemetryAndRecordLogs(); + yield pushPref("devtools.command-button-scratchpad.enabled", true); + let target = TargetFactory.forTab(gBrowser.selectedTab); let toolbox = yield gDevTools.showToolbox(target, "inspector"); info("inspector opened"); diff --git a/devtools/client/themes/firebug-theme.css b/devtools/client/themes/firebug-theme.css index 17b29ce8a458..21bf02031f2b 100644 --- a/devtools/client/themes/firebug-theme.css +++ b/devtools/client/themes/firebug-theme.css @@ -94,6 +94,22 @@ .theme-firebug .devtools-sidebar-tabs tab { } +.theme-firebug .devtools-tab span { + padding-inline-end: 0; +} + +/* Tweak the margin and padding values differently for sidebar and the main tab bar */ +.theme-firebug .devtools-tab, +.theme-firebug .devtools-tab.selected { + padding: 2px 4px 0 4px; + margin: 3px 1px -1px; +} + +.theme-firebug .devtools-sidebar-tabs tab { + margin: 3px 0 -1px 0; + padding: 2px 0 0 0; +} + /* In order to hide bottom-border of side panel tabs we need to make the parent element overflow visible, so child element can move one pixel down to hide the bottom border of the parent. */ @@ -107,7 +123,7 @@ border-bottom: 1px solid transparent; } -.theme-firebug .devtools-tab[selected], +.theme-firebug .devtools-tab.selected, .theme-firebug .devtools-sidebar-tabs tab[selected] { background-color: rgb(247, 251, 254); border: 1px solid rgb(170, 188, 207) !important; @@ -116,8 +132,8 @@ color: inherit; } -.theme-firebug .devtools-tab spacer, -.theme-firebug .devtools-tab image { +.theme-firebug .devtools-tabbar .devtools-separator, +.theme-firebug .devtools-tab img { display: none; } @@ -135,7 +151,7 @@ margin: 0 4px !important; } -.theme-firebug #panelSideBox .devtools-tab[selected], +.theme-firebug #panelSideBox .devtools-tab.selected, .theme-firebug .devtools-sidebar-tabs tab[selected] { background-color: white; } @@ -155,13 +171,21 @@ .theme-firebug #toolbox-tab-options::before { content: url(chrome://devtools/skin/images/firebug/tool-options.svg); display: block; - margin: 4px 7px 0; + margin: 4px 4px 0; } .theme-firebug #toolbox-tab-options:not([selected]):hover::before { filter: brightness(80%); } +/* Element picker */ +.theme-firebug #toolbox-buttons-start { + border: none; +} + +.theme-firebug #command-button-pick { + top: 6px; +} /* Toolbar */ .theme-firebug .theme-toolbar, @@ -233,3 +257,9 @@ .theme-firebug #element-picker { min-height: 21px; } + +/* Make sure the toolbar buttons shrink nicely. */ + +#toolbox-buttons-end { + background-image: linear-gradient(rgba(253, 253, 253, 0.2), rgba(253, 253, 253, 0)); +} diff --git a/devtools/client/themes/toolbars.css b/devtools/client/themes/toolbars.css index c515ee5da118..4dc89b463895 100644 --- a/devtools/client/themes/toolbars.css +++ b/devtools/client/themes/toolbars.css @@ -187,7 +187,7 @@ /* Invert the colors of certain light theme images for displaying * inside of the dark theme. */ -.devtools-tab[icon-invertable] > image, +.devtools-tab.icon-invertable > img, .devtools-toolbarbutton > image, .devtools-button::before, #breadcrumb-separator-normal, diff --git a/devtools/client/themes/toolbox.css b/devtools/client/themes/toolbox.css index 1db2bd01c944..5f3549cabd5a 100644 --- a/devtools/client/themes/toolbox.css +++ b/devtools/client/themes/toolbox.css @@ -49,15 +49,32 @@ padding: 0; background: var(--theme-tab-toolbar-background); border-bottom-color: var(--theme-splitter-color); + display: flex; } -#toolbox-tabs { +.toolbox-tabs { margin: 0; + flex: 1; +} + +.toolbox-tabs-wrapper { + position: relative; + display: flex; + flex: 1; +} + +.toolbox-tabs { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + display: flex; } /* Set flex attribute to Toolbox buttons and Picker container so, - they don't overlapp with the tab bar */ -#toolbox-buttons { + they don't overlap with the tab bar */ +#toolbox-buttons-end { display: flex; } @@ -65,22 +82,38 @@ display: flex; } -/* Toolbox tabs */ +#toolbox-buttons-start { + border: solid 0 var(--theme-splitter-color); + border-inline-end-width: 1px; +} +/* Toolbox tabs */ .devtools-tab { - -moz-appearance: none; - -moz-binding: url("chrome://global/content/bindings/general.xml#control-item"); - -moz-box-align: center; min-width: 32px; min-height: 24px; - max-width: 100px; margin: 0; padding: 0; border-style: solid; border-width: 0; border-inline-start-width: 1px; - -moz-box-align: center; - -moz-box-flex: 1; + padding-inline-end: 10px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + background-color: transparent; +} + +.devtools-tab-icon-only { + padding-inline-end: 2px; +} + +.devtools-tab span { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + padding-inline-end: 13px; + position: relative; + top: 1px; } /* Save space on the tab-strip in Firebug theme */ @@ -114,17 +147,17 @@ background-color: var(--toolbar-tab-hover-active); } -.theme-dark .devtools-tab:not([selected])[highlighted] { +.theme-dark .devtools-tab:not(.selected).highlighted { background-color: hsla(99, 100%, 14%, .3); } -.theme-light .devtools-tab:not([selected])[highlighted] { +.theme-light .devtools-tab:not(.selected).highlighted { background-color: rgba(44, 187, 15, .2); } /* Display execution pointer in the Debugger tab to indicate that the debugger is paused. */ -.theme-firebug #toolbox-tab-jsdebugger.devtools-tab:not([selected])[highlighted] { +.theme-firebug #toolbox-tab-jsdebugger.devtools-tab:not(.selected).highlighted { background-color: rgba(89, 178, 234, .2); background-image: url(chrome://devtools/skin/images/firebug/tool-debugger-paused.svg); background-repeat: no-repeat; @@ -132,27 +165,29 @@ background-position: 3px 6px; } -.devtools-tab > image { +.devtools-tab > img { border: none; margin: 0; - margin-inline-start: 4px; + margin-inline-start: 10px; opacity: 0.6; max-height: 16px; width: 16px; /* Prevents collapse during theme switching */ + vertical-align: text-top; + margin-inline-end: 6px; } /* Support invertable icon flags and make icon white when it's on a blue background */ -.theme-light .devtools-tab[icon-invertable="light-theme"]:not([selected]) > image, -.devtools-tab[icon-invertable="dark-theme"][selected] > image { +.theme-light .devtools-tab.icon-invertable-light-theme:not(.selected) > img, +.devtools-tab.icon-invertable-dark-theme.selected > img { filter: invert(1); } /* Don't apply any filter to non-invertable command button icons */ .command-button:not(.command-button-invertable), -/* [icon-invertable="light-theme"] icons are white, so do not invert them for the dark theme */ -.theme-dark .devtools-tab[icon-invertable="light-theme"] > image, +/* icon-invertable-light-theme icons are white, so do not invert them for the dark theme */ +.theme-dark .devtools-tab.icon-invertable-light-theme > img, /* Since "highlighted" icons are green, we should omit the filter */ -.devtools-tab[icon-invertable][highlighted]:not([selected]) > image { +.devtools-tab.icon-invertable.highlighted:not(.selected) > img { filter: none; } @@ -161,55 +196,50 @@ margin: 0 4px; } -.devtools-tab:hover > image { +.devtools-tab:hover > img { opacity: 0.8; } -.devtools-tab:active > image, -.devtools-tab[selected] > image { +.devtools-tab:active > img, +.devtools-tab.selected > img { opacity: 1; } -.devtools-tabbar .devtools-tab[selected], -.devtools-tabbar .devtools-tab[selected]:hover:active { +.devtools-tabbar .devtools-tab.selected, +.devtools-tabbar .devtools-tab.selected:hover:active { color: var(--theme-selection-color); background-color: var(--theme-selection-background); } -#toolbox-tabs .devtools-tab[selected], -#toolbox-tabs .devtools-tab[highlighted] { +.toolbox-tabs .devtools-tab.selected, +.toolbox-tabs .devtools-tab.highlighted { border-width: 0; padding-inline-start: 1px; } -#toolbox-tabs .devtools-tab[selected]:last-child, -#toolbox-tabs .devtools-tab[highlighted]:last-child { - padding-inline-end: 1px; -} - -#toolbox-tabs .devtools-tab[selected] + .devtools-tab, -#toolbox-tabs .devtools-tab[highlighted] + .devtools-tab { +.toolbox-tabs .devtools-tab.selected + .devtools-tab, +.toolbox-tabs .devtools-tab.highlighted + .devtools-tab { border-inline-start-width: 0; padding-inline-start: 1px; } -#toolbox-tabs .devtools-tab:first-child[selected] { +.toolbox-tabs .devtools-tab:first-child { border-inline-start-width: 0; } -#toolbox-tabs .devtools-tab:last-child { +.toolbox-tabs .devtools-tab:last-child { border-inline-end-width: 1px; } -.devtools-tab:not([highlighted]) > .highlighted-icon, -.devtools-tab[selected] > .highlighted-icon, -.devtools-tab:not([selected])[highlighted] > .default-icon { - visibility: collapse; +.devtools-tab:not(.highlighted) > .highlighted-icon, +.devtools-tab.selected > .highlighted-icon, +.devtools-tab:not(.selected).highlighted > .default-icon { + display: none; } /* The options tab is special - it doesn't have the same parent as the other tabs (toolbox-option-container vs toolbox-tabs) */ -#toolbox-option-container .devtools-tab:not([selected]) { +#toolbox-option-container .devtools-tab:not(.selected) { background-color: transparent; } #toolbox-option-container .devtools-tab { @@ -217,12 +247,16 @@ border-width: 0; padding-inline-start: 1px; } -#toolbox-tab-options > image { - margin: 0 8px; +#toolbox-option-container img { + margin-inline-end: 6px; + margin-inline-start: 6px; } /* Toolbox controls */ +#toolbox-controls, #toolbox-dock-buttons { + display: flex; +} #toolbox-controls > button, #toolbox-dock-buttons > button { -moz-appearance: none; @@ -263,7 +297,16 @@ background-image: url("chrome://devtools/skin/images/dock-bottom-maximize@2x.png"); } -#toolbox-buttons:empty + .devtools-separator, +/** + * Ensure that when the toolbar collapses in on itself when there is not enough room + * that it still looks reasonable. + */ +.devtools-tabbar > div { + background-color: var(--theme-tab-toolbar-background); + z-index: 0; +} + +#toolbox-buttons-end:empty + .devtools-separator, .devtools-separator[invisible] { visibility: hidden; } @@ -293,12 +336,12 @@ } .command-button:hover:active, -.command-button[checked=true]:not(:hover) { +.command-button.checked:not(:hover) { background-color: var(--toolbar-tab-hover-active) } .theme-light .command-button:hover:active, -.theme-light .command-button[checked=true]:not(:hover) { +.theme-light .command-button.checked:not(:hover) { background-color: inherit; } @@ -307,8 +350,8 @@ } .command-button:hover:active::before, -.command-button[checked=true]::before, -.command-button[open=true]::before { +.command-button.checked::before, +.command-button.open::before { opacity: 1; } diff --git a/devtools/client/webconsole/test/browser_webconsole_split.js b/devtools/client/webconsole/test/browser_webconsole_split.js index 0242d94b4c01..a855a246922c 100644 --- a/devtools/client/webconsole/test/browser_webconsole_split.js +++ b/devtools/client/webconsole/test/browser_webconsole_split.js @@ -85,17 +85,15 @@ function runTest() { webconsoleHeight: webconsoleHeight, splitterVisibility: splitterVisibility, openedConsolePanel: openedConsolePanel, - buttonSelected: cmdButton.hasAttribute("checked") + buttonSelected: cmdButton.classList.contains("checked") }; } - function checkWebconsolePanelOpened() { + const checkWebconsolePanelOpened = Task.async(function* () { info("About to check special cases when webconsole panel is open."); - let deferred = promise.defer(); - // Start with console split, so we can test for transition to main panel. - toolbox.toggleSplitConsole(); + yield toolbox.toggleSplitConsole(); let currentUIState = getCurrentUIState(); @@ -109,78 +107,54 @@ function runTest() { "The console panel is not the current tool"); ok(currentUIState.buttonSelected, "The command button is selected"); - openPanel("webconsole").then(() => { - currentUIState = getCurrentUIState(); + yield openPanel("webconsole"); + currentUIState = getCurrentUIState(); - ok(!currentUIState.splitterVisibility, - "Splitter is hidden when console is opened."); - is(currentUIState.deckHeight, 0, - "Deck has a height == 0 when console is opened."); - is(currentUIState.webconsoleHeight, currentUIState.containerHeight, - "Web console is full height."); - ok(currentUIState.openedConsolePanel, - "The console panel is the current tool"); - ok(currentUIState.buttonSelected, - "The command button is still selected."); + ok(!currentUIState.splitterVisibility, + "Splitter is hidden when console is opened."); + is(currentUIState.deckHeight, 0, + "Deck has a height == 0 when console is opened."); + is(currentUIState.webconsoleHeight, currentUIState.containerHeight, + "Web console is full height."); + ok(currentUIState.openedConsolePanel, + "The console panel is the current tool"); + ok(currentUIState.buttonSelected, + "The command button is still selected."); - // Make sure splitting console does nothing while webconsole is opened - toolbox.toggleSplitConsole(); + // Make sure splitting console does nothing while webconsole is opened + yield toolbox.toggleSplitConsole(); - currentUIState = getCurrentUIState(); + currentUIState = getCurrentUIState(); - ok(!currentUIState.splitterVisibility, - "Splitter is hidden when console is opened."); - is(currentUIState.deckHeight, 0, - "Deck has a height == 0 when console is opened."); - is(currentUIState.webconsoleHeight, currentUIState.containerHeight, - "Web console is full height."); - ok(currentUIState.openedConsolePanel, - "The console panel is the current tool"); - ok(currentUIState.buttonSelected, - "The command button is still selected."); + ok(!currentUIState.splitterVisibility, + "Splitter is hidden when console is opened."); + is(currentUIState.deckHeight, 0, + "Deck has a height == 0 when console is opened."); + is(currentUIState.webconsoleHeight, currentUIState.containerHeight, + "Web console is full height."); + ok(currentUIState.openedConsolePanel, + "The console panel is the current tool"); + ok(currentUIState.buttonSelected, + "The command button is still selected."); - // Make sure that split state is saved after opening another panel - openPanel("inspector").then(() => { - currentUIState = getCurrentUIState(); - ok(currentUIState.splitterVisibility, - "Splitter is visible when console is split"); - ok(currentUIState.deckHeight > 0, - "Deck has a height > 0 when console is split"); - ok(currentUIState.webconsoleHeight > 0, - "Web console has a height > 0 when console is split"); - ok(!currentUIState.openedConsolePanel, - "The console panel is not the current tool"); - ok(currentUIState.buttonSelected, - "The command button is still selected."); + // Make sure that split state is saved after opening another panel + yield openPanel("inspector"); + currentUIState = getCurrentUIState(); + ok(currentUIState.splitterVisibility, + "Splitter is visible when console is split"); + ok(currentUIState.deckHeight > 0, + "Deck has a height > 0 when console is split"); + ok(currentUIState.webconsoleHeight > 0, + "Web console has a height > 0 when console is split"); + ok(!currentUIState.openedConsolePanel, + "The console panel is not the current tool"); + ok(currentUIState.buttonSelected, + "The command button is still selected."); - toolbox.toggleSplitConsole(); - deferred.resolve(); - }); - }); - return deferred.promise; - } + yield toolbox.toggleSplitConsole(); + }); - function openPanel(toolId) { - let deferred = promise.defer(); - let target = TargetFactory.forTab(gBrowser.selectedTab); - gDevTools.showToolbox(target, toolId).then(function (box) { - toolbox = box; - deferred.resolve(); - }).then(null, console.error); - return deferred.promise; - } - - function openAndCheckPanel(toolId) { - let deferred = promise.defer(); - openPanel(toolId).then(() => { - info("Checking toolbox for " + toolId); - checkToolboxUI(toolbox.getCurrentPanel()); - deferred.resolve(); - }); - return deferred.promise; - } - - function checkToolboxUI() { + const checkToolboxUI = Task.async(function* () { let currentUIState = getCurrentUIState(); ok(!currentUIState.splitterVisibility, "Splitter is hidden by default"); @@ -192,7 +166,7 @@ function runTest() { "The console panel is not the current tool"); ok(!currentUIState.buttonSelected, "The command button is not selected."); - toolbox.toggleSplitConsole(); + yield toolbox.toggleSplitConsole(); currentUIState = getCurrentUIState(); @@ -209,7 +183,7 @@ function runTest() { "The console panel is not the current tool"); ok(currentUIState.buttonSelected, "The command button is selected."); - toolbox.toggleSplitConsole(); + yield toolbox.toggleSplitConsole(); currentUIState = getCurrentUIState(); @@ -221,6 +195,23 @@ function runTest() { ok(!currentUIState.openedConsolePanel, "The console panel is not the current tool"); ok(!currentUIState.buttonSelected, "The command button is not selected."); + }); + + function openPanel(toolId) { + let deferred = promise.defer(); + let target = TargetFactory.forTab(gBrowser.selectedTab); + gDevTools.showToolbox(target, toolId).then(function (box) { + toolbox = box; + deferred.resolve(); + }).then(null, console.error); + return deferred.promise; + } + + function openAndCheckPanel(toolId) { + return openPanel(toolId).then(() => { + info("Checking toolbox for " + toolId); + return checkToolboxUI(toolbox.getCurrentPanel()); + }); } function testBottomHost() { diff --git a/devtools/client/webconsole/test/browser_webconsole_split_persist.js b/devtools/client/webconsole/test/browser_webconsole_split_persist.js index e11bd48118f2..ea28e6843939 100644 --- a/devtools/client/webconsole/test/browser_webconsole_split_persist.js +++ b/devtools/client/webconsole/test/browser_webconsole_split_persist.js @@ -99,7 +99,7 @@ function isCommandButtonChecked() { return toolbox.doc.querySelector("#command-button-splitconsole") - .hasAttribute("checked"); + .classList.contains("checked"); } function toggleSplitConsoleWithEscape() { From c1e2855a5a47b1e8398bbe5d8a23f2beb9e77cca Mon Sep 17 00:00:00 2001 From: Hannes Verschore Date: Thu, 29 Dec 2016 16:57:53 +0100 Subject: [PATCH 045/229] Bug 1312480, r=jandem --- js/src/jit/MacroAssembler.cpp | 8 +++++++- js/src/vm/TypedArrayObject.cpp | 31 +++++++++++++++++++++++-------- js/src/vm/TypedArrayObject.h | 6 +++++- 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/js/src/jit/MacroAssembler.cpp b/js/src/jit/MacroAssembler.cpp index a14ad5485824..24808b0e45c1 100644 --- a/js/src/jit/MacroAssembler.cpp +++ b/js/src/jit/MacroAssembler.cpp @@ -1043,9 +1043,9 @@ AllocateObjectBufferWithInit(JSContext* cx, TypedArrayObject* obj, int32_t count // Negative numbers will bail out to the slow path, which in turn will raise // an invalid argument exception. if (count <= 0) { + obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(0)); if (count == 0) obj->setInlineElements(); - obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(0)); return; } @@ -1097,6 +1097,12 @@ MacroAssembler::initTypedArraySlots(Register obj, Register temp, Register length if (lengthKind == TypedArrayLength::Fixed && dataOffset + nbytes <= JSObject::MAX_BYTE_SIZE) { MOZ_ASSERT(dataOffset + nbytes <= templateObj->tenuredSizeOfThis()); + if (length == 0) { + // Store nullptr inside the data slot offset when size is 0. + storePtr(ImmPtr(nullptr), Address(obj, dataSlotOffset)); + return; + } + // Store data elements inside the remaining JSObject slots. computeEffectiveAddress(Address(obj, dataOffset), temp); storePtr(temp, Address(obj, dataSlotOffset)); diff --git a/js/src/vm/TypedArrayObject.cpp b/js/src/vm/TypedArrayObject.cpp index ebb61c1e59d9..d3bed9988514 100644 --- a/js/src/vm/TypedArrayObject.cpp +++ b/js/src/vm/TypedArrayObject.cpp @@ -240,14 +240,21 @@ JS_FOR_EACH_TYPED_ARRAY(OBJECT_MOVED_TYPED_ARRAY) bool TypedArrayObject::hasInlineElements() const { - return elements() == this->fixedData(TypedArrayObject::FIXED_DATA_START) && - byteLength() <= TypedArrayObject::INLINE_BUFFER_LIMIT; + if (byteLength() > TypedArrayObject::INLINE_BUFFER_LIMIT) + return false; + + return (!hasBuffer() && length() == 0) || + elements() == this->fixedData(TypedArrayObject::FIXED_DATA_START); } void TypedArrayObject::setInlineElements() { char* dataSlot = reinterpret_cast(this) + this->dataOffset(); + if (length() == 0) { + *reinterpret_cast(dataSlot) = nullptr; + return; + } *reinterpret_cast(dataSlot) = this->fixedData(TypedArrayObject::FIXED_DATA_START); } @@ -506,9 +513,13 @@ class TypedArrayObjectTemplate : public TypedArrayObject } } } else { - void* data = obj->fixedData(FIXED_DATA_START); - obj->initPrivate(data); - memset(data, 0, len * sizeof(NativeType)); + if (len == 0) { + obj->initPrivate(nullptr); + } else { + void* data = obj->fixedData(FIXED_DATA_START); + obj->initPrivate(data); + memset(data, 0, len * sizeof(NativeType)); + } } obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(len)); @@ -621,9 +632,13 @@ class TypedArrayObjectTemplate : public TypedArrayObject MOZ_ASSERT(offset + nbytes <= GetGCKindBytes(allocKind)); #endif - void* data = tarray->fixedData(FIXED_DATA_START); - tarray->initPrivate(data); - memset(data, 0, nbytes); + if (len == 0) { + tarray->initPrivate(nullptr); + } else { + void* data = tarray->fixedData(FIXED_DATA_START); + tarray->initPrivate(data); + memset(data, 0, nbytes); + } } } diff --git a/js/src/vm/TypedArrayObject.h b/js/src/vm/TypedArrayObject.h index 734234ec2239..35319b496820 100644 --- a/js/src/vm/TypedArrayObject.h +++ b/js/src/vm/TypedArrayObject.h @@ -164,8 +164,12 @@ class TypedArrayObject : public NativeObject bool hasInlineElements() const; void setInlineElements(); + + /* returns nullptr if length is zero or if this is a template object. */ uint8_t* elements() const { - return *(uint8_t **)((((char *)this) + this->dataOffset())); + uint8_t* output = *(uint8_t **)((((char *)this) + this->dataOffset())); + MOZ_ASSERT_IF(length() == 0 && !hasBuffer(), output == nullptr); + return output; } Value getElement(uint32_t index); From 9552a1bbde7287978fa8cceaf7dd708baa7af784 Mon Sep 17 00:00:00 2001 From: Sebastian Hengst Date: Thu, 29 Dec 2016 18:42:56 +0100 Subject: [PATCH 046/229] Backed out changeset 12de9b2dacba (bug 1312480) for breaking test_lz4.js and test_lz4_sync.js xpcshell tests. r=backout --- js/src/jit/MacroAssembler.cpp | 8 +------- js/src/vm/TypedArrayObject.cpp | 31 ++++++++----------------------- js/src/vm/TypedArrayObject.h | 6 +----- 3 files changed, 10 insertions(+), 35 deletions(-) diff --git a/js/src/jit/MacroAssembler.cpp b/js/src/jit/MacroAssembler.cpp index 24808b0e45c1..a14ad5485824 100644 --- a/js/src/jit/MacroAssembler.cpp +++ b/js/src/jit/MacroAssembler.cpp @@ -1043,9 +1043,9 @@ AllocateObjectBufferWithInit(JSContext* cx, TypedArrayObject* obj, int32_t count // Negative numbers will bail out to the slow path, which in turn will raise // an invalid argument exception. if (count <= 0) { - obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(0)); if (count == 0) obj->setInlineElements(); + obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(0)); return; } @@ -1097,12 +1097,6 @@ MacroAssembler::initTypedArraySlots(Register obj, Register temp, Register length if (lengthKind == TypedArrayLength::Fixed && dataOffset + nbytes <= JSObject::MAX_BYTE_SIZE) { MOZ_ASSERT(dataOffset + nbytes <= templateObj->tenuredSizeOfThis()); - if (length == 0) { - // Store nullptr inside the data slot offset when size is 0. - storePtr(ImmPtr(nullptr), Address(obj, dataSlotOffset)); - return; - } - // Store data elements inside the remaining JSObject slots. computeEffectiveAddress(Address(obj, dataOffset), temp); storePtr(temp, Address(obj, dataSlotOffset)); diff --git a/js/src/vm/TypedArrayObject.cpp b/js/src/vm/TypedArrayObject.cpp index d3bed9988514..ebb61c1e59d9 100644 --- a/js/src/vm/TypedArrayObject.cpp +++ b/js/src/vm/TypedArrayObject.cpp @@ -240,21 +240,14 @@ JS_FOR_EACH_TYPED_ARRAY(OBJECT_MOVED_TYPED_ARRAY) bool TypedArrayObject::hasInlineElements() const { - if (byteLength() > TypedArrayObject::INLINE_BUFFER_LIMIT) - return false; - - return (!hasBuffer() && length() == 0) || - elements() == this->fixedData(TypedArrayObject::FIXED_DATA_START); + return elements() == this->fixedData(TypedArrayObject::FIXED_DATA_START) && + byteLength() <= TypedArrayObject::INLINE_BUFFER_LIMIT; } void TypedArrayObject::setInlineElements() { char* dataSlot = reinterpret_cast(this) + this->dataOffset(); - if (length() == 0) { - *reinterpret_cast(dataSlot) = nullptr; - return; - } *reinterpret_cast(dataSlot) = this->fixedData(TypedArrayObject::FIXED_DATA_START); } @@ -513,13 +506,9 @@ class TypedArrayObjectTemplate : public TypedArrayObject } } } else { - if (len == 0) { - obj->initPrivate(nullptr); - } else { - void* data = obj->fixedData(FIXED_DATA_START); - obj->initPrivate(data); - memset(data, 0, len * sizeof(NativeType)); - } + void* data = obj->fixedData(FIXED_DATA_START); + obj->initPrivate(data); + memset(data, 0, len * sizeof(NativeType)); } obj->setFixedSlot(TypedArrayObject::LENGTH_SLOT, Int32Value(len)); @@ -632,13 +621,9 @@ class TypedArrayObjectTemplate : public TypedArrayObject MOZ_ASSERT(offset + nbytes <= GetGCKindBytes(allocKind)); #endif - if (len == 0) { - tarray->initPrivate(nullptr); - } else { - void* data = tarray->fixedData(FIXED_DATA_START); - tarray->initPrivate(data); - memset(data, 0, nbytes); - } + void* data = tarray->fixedData(FIXED_DATA_START); + tarray->initPrivate(data); + memset(data, 0, nbytes); } } diff --git a/js/src/vm/TypedArrayObject.h b/js/src/vm/TypedArrayObject.h index 35319b496820..734234ec2239 100644 --- a/js/src/vm/TypedArrayObject.h +++ b/js/src/vm/TypedArrayObject.h @@ -164,12 +164,8 @@ class TypedArrayObject : public NativeObject bool hasInlineElements() const; void setInlineElements(); - - /* returns nullptr if length is zero or if this is a template object. */ uint8_t* elements() const { - uint8_t* output = *(uint8_t **)((((char *)this) + this->dataOffset())); - MOZ_ASSERT_IF(length() == 0 && !hasBuffer(), output == nullptr); - return output; + return *(uint8_t **)((((char *)this) + this->dataOffset())); } Value getElement(uint32_t index); From 9bf0b6bb08427fbccbc76a30cf2ed8e577e9f553 Mon Sep 17 00:00:00 2001 From: Ehsan Akhgari Date: Thu, 29 Dec 2016 11:32:31 -0500 Subject: [PATCH 047/229] Bug 1326229 - Move the include for FrontendPluginRegistry.h to MozCheckAction.cpp; r=mystor --- build/clang-plugin/MozCheckAction.cpp | 2 ++ build/clang-plugin/plugin.h | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/build/clang-plugin/MozCheckAction.cpp b/build/clang-plugin/MozCheckAction.cpp index 15362be24b81..c2e2a28fa746 100644 --- a/build/clang-plugin/MozCheckAction.cpp +++ b/build/clang-plugin/MozCheckAction.cpp @@ -2,7 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +#include "plugin.h" #include "DiagnosticsMatcher.h" +#include "clang/Frontend/FrontendPluginRegistry.h" class MozCheckAction : public PluginASTAction { public: diff --git a/build/clang-plugin/plugin.h b/build/clang-plugin/plugin.h index 02303a76cbce..9fc547d3487e 100644 --- a/build/clang-plugin/plugin.h +++ b/build/clang-plugin/plugin.h @@ -12,7 +12,6 @@ #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Basic/Version.h" #include "clang/Frontend/CompilerInstance.h" -#include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/Frontend/MultiplexConsumer.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/DenseMap.h" From 5c8692f989cc17a125791ffadca6c8e973278d0b Mon Sep 17 00:00:00 2001 From: Tomislav Jovanovic Date: Wed, 23 Nov 2016 18:46:10 +0100 Subject: [PATCH 048/229] Bug 1319070 - Match against the principal. r=kmag MozReview-Commit-ID: BB6UfZ6qjKr --- .../test/addons/embedded-webextension/main.js | 2 +- .../components/extensions/ExtensionContent.jsm | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/addon-sdk/source/test/addons/embedded-webextension/main.js b/addon-sdk/source/test/addons/embedded-webextension/main.js index 4e51c2f9bb09..11249c50476a 100644 --- a/addon-sdk/source/test/addons/embedded-webextension/main.js +++ b/addon-sdk/source/test/addons/embedded-webextension/main.js @@ -135,7 +135,7 @@ exports.testEmbeddedWebExtensionContentScript = function* (assert, done) { browser.runtime.onConnect.addListener(portListener); }); - let url = "data:text/html;charset=utf-8,

Test Page

"; + let url = "http://example.org/"; var openedTab; tabs.once('open', function onOpen(tab) { diff --git a/toolkit/components/extensions/ExtensionContent.jsm b/toolkit/components/extensions/ExtensionContent.jsm index 53a2fff41d74..6d762348674a 100644 --- a/toolkit/components/extensions/ExtensionContent.jsm +++ b/toolkit/components/extensions/ExtensionContent.jsm @@ -143,6 +143,7 @@ Script.prototype = { matches(window) { let uri = window.document.documentURIObject; + let principal = window.document.nodePrincipal; // If mozAddonManager is present on this page, don't allow // content scripts. @@ -150,16 +151,25 @@ Script.prototype = { return false; } - if (this.match_about_blank && ["about:blank", "about:srcdoc"].includes(uri.spec)) { - const principal = window.document.nodePrincipal; - + if (this.match_about_blank) { // When matching top-level about:blank documents, // allow loading into any with a NullPrincipal. - if (window === window.top && principal.isNullPrincipal) { + if (uri.spec === "about:blank" && window === window.top && principal.isNullPrincipal) { return true; } + // When matching about:blank/srcdoc iframes, the checks below // need to be performed against the "owner" document's URI. + if (["about:blank", "about:srcdoc"].includes(uri.spec)) { + uri = principal.URI; + } + } + + // Documents from data: URIs also inherit the principal. + if (Services.netUtils.URIChainHasFlags(uri, Ci.nsIProtocolHandler.URI_INHERITS_SECURITY_CONTEXT)) { + if (!this.match_about_blank) { + return false; + } uri = principal.URI; } From 6bd1b87757212043614399fff61c2cb5c61a278c Mon Sep 17 00:00:00 2001 From: Denis Scott Date: Wed, 28 Dec 2016 20:36:00 -0500 Subject: [PATCH 049/229] Bug 1326142 - GenerateBailoutHandler/arm64: ION_PERF Use undefined variable "code". r=bbouvier --- js/src/jit/arm64/Trampoline-arm64.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/js/src/jit/arm64/Trampoline-arm64.cpp b/js/src/jit/arm64/Trampoline-arm64.cpp index 638d37bea17e..3535f8013897 100644 --- a/js/src/jit/arm64/Trampoline-arm64.cpp +++ b/js/src/jit/arm64/Trampoline-arm64.cpp @@ -540,13 +540,15 @@ JitRuntime::generateBailoutHandler(JSContext* cx) MacroAssembler masm(cx); GenerateBailoutThunk(cx, masm, NO_FRAME_SIZE_CLASS_ID); + Linker linker(masm); + AutoFlushICache afc("BailoutHandler"); + JitCode* code = linker.newCode(cx, OTHER_CODE); + #ifdef JS_ION_PERF writePerfSpewerJitCodeProfile(code, "BailoutHandler"); #endif - Linker linker(masm); - AutoFlushICache afc("BailoutHandler"); - return linker.newCode(cx, OTHER_CODE); + return code; } JitCode* From 0c7185391414f597839dc2cef66ae19aed9611ee Mon Sep 17 00:00:00 2001 From: Stephen A Pohl Date: Thu, 29 Dec 2016 14:05:11 -0500 Subject: [PATCH 050/229] Bug 1325906: Start using proper constant for PNG pasteboard type. r=mstange --- widget/cocoa/nsClipboard.mm | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/widget/cocoa/nsClipboard.mm b/widget/cocoa/nsClipboard.mm index d24b865081f3..48f9ff8f835f 100644 --- a/widget/cocoa/nsClipboard.mm +++ b/widget/cocoa/nsClipboard.mm @@ -29,9 +29,8 @@ using mozilla::gfx::DataSourceSurface; using mozilla::gfx::SourceSurface; using mozilla::LogLevel; -// Screenshots use the (undocumented) png pasteboard type. #define IMAGE_PASTEBOARD_TYPES NSPasteboardTypeTIFF, \ - @"Apple PNG pasteboard type", \ + NSPasteboardTypePNG, \ nil extern PRLogModuleInfo* sCocoaLog; From 10f0b72494b027c473ec802502978d725f8d95dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Blin?= Date: Tue, 29 Nov 2016 07:49:00 -0500 Subject: [PATCH 051/229] Bug 1315667 - Fix resizing inspector sidebar when zooming. r=Honza --- devtools/client/shared/components/splitter/split-box.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/devtools/client/shared/components/splitter/split-box.js b/devtools/client/shared/components/splitter/split-box.js index 2229b334e1eb..676b941d536c 100644 --- a/devtools/client/shared/components/splitter/split-box.js +++ b/devtools/client/shared/components/splitter/split-box.js @@ -97,6 +97,7 @@ const SplitBox = React.createClass({ const win = doc.defaultView; let size; + let ratio = win.devicePixelRatio || 1; let { endPanelControl } = this.props; if (this.state.vert) { @@ -107,7 +108,7 @@ const SplitBox = React.createClass({ endPanelControl = !endPanelControl; } - let innerOffset = x - win.mozInnerScreenX; + let innerOffset = (x / ratio) - win.mozInnerScreenX; size = endPanelControl ? (node.offsetLeft + node.offsetWidth) - innerOffset : innerOffset - node.offsetLeft; @@ -116,7 +117,7 @@ const SplitBox = React.createClass({ width: size }); } else { - let innerOffset = y - win.mozInnerScreenY; + let innerOffset = (y / ratio) - win.mozInnerScreenY; size = endPanelControl ? (node.offsetTop + node.offsetHeight) - innerOffset : innerOffset - node.offsetTop; From f3debaf2fbb14a766b646079a667d3e1667049de Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 13:19:25 -0800 Subject: [PATCH 052/229] Bug 1326105 part 1. dom::RootedCallback should hold on to a JSContext that it can then use in its destructor. r=smaug --- dom/bindings/CallbackObject.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dom/bindings/CallbackObject.h b/dom/bindings/CallbackObject.h index 8a3d45dfce21..fc387bd5ad8a 100644 --- a/dom/bindings/CallbackObject.h +++ b/dom/bindings/CallbackObject.h @@ -545,11 +545,12 @@ ImplCycleCollectionUnlink(CallbackObjectHolder& aField) // it ensures that the callback is traced, and that if something is holding onto // the callback when we're done with it HoldJSObjects is called. template -class RootedCallback : public JS::Rooted +class MOZ_RAII RootedCallback : public JS::Rooted { public: explicit RootedCallback(JSContext* cx) : JS::Rooted(cx) + , mCx(cx) {} // We need a way to make assignment from pointers (how we're normally used) @@ -599,6 +600,8 @@ private: { return aOwningNonNull.isInitialized(); } + + JSContext* mCx; }; } // namespace dom From e5f32d36099db545dc145ed2f0b27edb694d3d68 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 13:19:26 -0800 Subject: [PATCH 053/229] Bug 1326105 part 2. Rename CallbackObject::HoldJSObjectsIfMoreThanOneOwner to a more generic name and hand it a JSContext to use. r=smaug --- dom/bindings/CallbackObject.cpp | 2 +- dom/bindings/CallbackObject.h | 15 ++++++++------- dom/bindings/Codegen.py | 6 +++--- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/dom/bindings/CallbackObject.cpp b/dom/bindings/CallbackObject.cpp index 7c7d2c6b4c97..d83039d18bf9 100644 --- a/dom/bindings/CallbackObject.cpp +++ b/dom/bindings/CallbackObject.cpp @@ -56,7 +56,7 @@ CallbackObject::Trace(JSTracer* aTracer) } void -CallbackObject::HoldJSObjectsIfMoreThanOneOwner() +CallbackObject::FinishSlowJSInitIfMoreThanOneOwner(JSContext* aCx) { MOZ_ASSERT(mRefCnt.get() > 0); if (mRefCnt.get() > 1) { diff --git a/dom/bindings/CallbackObject.h b/dom/bindings/CallbackObject.h index fc387bd5ad8a..d5f13ba776d9 100644 --- a/dom/bindings/CallbackObject.h +++ b/dom/bindings/CallbackObject.h @@ -213,9 +213,10 @@ protected: void Trace(JSTracer* aTracer); // For use from subclasses that want to be traced for a bit then possibly - // switch to HoldJSObjects. If we have more than one owner, this will - // HoldJSObjects; otherwise it will just forget all our JS references. - void HoldJSObjectsIfMoreThanOneOwner(); + // switch to HoldJSObjects and do other slow JS-related init work we might do. + // If we have more than one owner, this will HoldJSObjects and do said slow + // init work; otherwise it will just forget all our JS references. + void FinishSlowJSInitIfMoreThanOneOwner(JSContext* aCx); // Struct used as a way to force a CallbackObject constructor to not call // HoldJSObjects. We're putting it here so that CallbackObject subclasses will @@ -577,11 +578,11 @@ public: ~RootedCallback() { // Ensure that our callback starts holding on to its own JS objects as - // needed. Having to null-check here when T is OwningNonNull is a bit - // silly, but it's simpler than creating two separate RootedCallback - // instantiations for OwningNonNull and RefPtr. + // needed. We really do need to check that things are initialized even when + // T is OwningNonNull, because we might be running before the OwningNonNull + // ever got assigned to! if (IsInitialized(this->get())) { - this->get()->HoldJSObjectsIfMoreThanOneOwner(); + this->get()->FinishSlowJSInitIfMoreThanOneOwner(mCx); } } diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index 2730092022fe..6467f5c65cba 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -15375,13 +15375,13 @@ class CGFastCallback(CGClass): bodyInHeader=True, visibility="public", body="%s::Trace(aTracer);\n" % baseName) - holdMethod = ClassMethod("HoldJSObjectsIfMoreThanOneOwner", "void", - [], + holdMethod = ClassMethod("FinishSlowJSInitIfMoreThanOneOwner", "void", + [Argument("JSContext*", "aCx")], inline=True, bodyInHeader=True, visibility="public", body=( - "%s::HoldJSObjectsIfMoreThanOneOwner();\n" % + "%s::FinishSlowJSInitIfMoreThanOneOwner(aCx);\n" % baseName)) CGClass.__init__(self, "Fast%s" % baseName, From ba1f5c039f0289b9fb97a61e5f0dbc7634e4f19c Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 13:19:26 -0800 Subject: [PATCH 054/229] Bug 1326105 part 3. Move async stack capture out of the 'fast' CallbackObject constructor and into FinishSlowJSInitIfMoreThanOneOwner. r=smaug --- dom/bindings/CallbackObject.cpp | 7 +++++++ dom/bindings/CallbackObject.h | 16 +++++----------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/dom/bindings/CallbackObject.cpp b/dom/bindings/CallbackObject.cpp index d83039d18bf9..ecdc88a794fd 100644 --- a/dom/bindings/CallbackObject.cpp +++ b/dom/bindings/CallbackObject.cpp @@ -61,6 +61,13 @@ CallbackObject::FinishSlowJSInitIfMoreThanOneOwner(JSContext* aCx) MOZ_ASSERT(mRefCnt.get() > 0); if (mRefCnt.get() > 1) { mozilla::HoldJSObjects(this); + if (JS::ContextOptionsRef(aCx).asyncStack()) { + JS::RootedObject stack(aCx); + if (!JS::CaptureCurrentStack(aCx, &stack)) { + JS_ClearPendingException(aCx); + } + mCreationStack = stack; + } } else { // We can just forget all our stuff. ClearJSReferences(); diff --git a/dom/bindings/CallbackObject.h b/dom/bindings/CallbackObject.h index d5f13ba776d9..aa194df3e32c 100644 --- a/dom/bindings/CallbackObject.h +++ b/dom/bindings/CallbackObject.h @@ -228,21 +228,15 @@ protected: }; // Just like the public version without the FastCallbackConstructor argument, - // except for not calling HoldJSObjects. If you use this, you MUST ensure - // that the object is traced until the HoldJSObjects happens! + // except for not calling HoldJSObjects and not capturing async stacks (on the + // assumption that we will do that last whenever we decide to actually + // HoldJSObjects; see FinishSlowJSInitIfMoreThanOneOwner). If you use this, + // you MUST ensure that the object is traced until the HoldJSObjects happens! CallbackObject(JSContext* aCx, JS::Handle aCallback, nsIGlobalObject* aIncumbentGlobal, const FastCallbackConstructor&) { - if (aCx && JS::ContextOptionsRef(aCx).asyncStack()) { - JS::RootedObject stack(aCx); - if (!JS::CaptureCurrentStack(aCx, &stack)) { - JS_ClearPendingException(aCx); - } - InitNoHold(aCallback, stack, aIncumbentGlobal); - } else { - InitNoHold(aCallback, nullptr, aIncumbentGlobal); - } + InitNoHold(aCallback, nullptr, aIncumbentGlobal); } // mCallback is not unwrapped, so it can be a cross-compartment-wrapper. From 249298d20ca3fce762171a367e5277d4dbbbef14 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 13:19:26 -0800 Subject: [PATCH 055/229] Bug 1326105 part 4. Remove the now-unused JSContext argument of the protected CallbackObject constructor. r=smaug --- dom/bindings/CallbackFunction.h | 4 ++-- dom/bindings/CallbackInterface.h | 4 ++-- dom/bindings/CallbackObject.h | 2 +- dom/bindings/Codegen.py | 7 +++---- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/dom/bindings/CallbackFunction.h b/dom/bindings/CallbackFunction.h index ac2b3e8b3531..648c7dde2207 100644 --- a/dom/bindings/CallbackFunction.h +++ b/dom/bindings/CallbackFunction.h @@ -63,10 +63,10 @@ protected: } // See CallbackObject for an explanation of the arguments. - CallbackFunction(JSContext* aCx, JS::Handle aCallable, + CallbackFunction(JS::Handle aCallable, nsIGlobalObject* aIncumbentGlobal, const FastCallbackConstructor&) - : CallbackObject(aCx, aCallable, aIncumbentGlobal, + : CallbackObject(aCallable, aIncumbentGlobal, FastCallbackConstructor()) { } diff --git a/dom/bindings/CallbackInterface.h b/dom/bindings/CallbackInterface.h index 3ba5182e7e9a..4c64e3605423 100644 --- a/dom/bindings/CallbackInterface.h +++ b/dom/bindings/CallbackInterface.h @@ -44,10 +44,10 @@ protected: JS::MutableHandle aCallable); // See CallbackObject for an explanation of the arguments. - CallbackInterface(JSContext* aCx, JS::Handle aCallable, + CallbackInterface(JS::Handle aCallable, nsIGlobalObject* aIncumbentGlobal, const FastCallbackConstructor&) - : CallbackObject(aCx, aCallable, aIncumbentGlobal, + : CallbackObject(aCallable, aIncumbentGlobal, FastCallbackConstructor()) { } diff --git a/dom/bindings/CallbackObject.h b/dom/bindings/CallbackObject.h index aa194df3e32c..82af426af88d 100644 --- a/dom/bindings/CallbackObject.h +++ b/dom/bindings/CallbackObject.h @@ -232,7 +232,7 @@ protected: // assumption that we will do that last whenever we decide to actually // HoldJSObjects; see FinishSlowJSInitIfMoreThanOneOwner). If you use this, // you MUST ensure that the object is traced until the HoldJSObjects happens! - CallbackObject(JSContext* aCx, JS::Handle aCallback, + CallbackObject(JS::Handle aCallback, nsIGlobalObject* aIncumbentGlobal, const FastCallbackConstructor&) { diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index 6467f5c65cba..f296e76f8663 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -15176,15 +15176,14 @@ class CGCallback(CGClass): ], body=body), ClassConstructor( - [Argument("JSContext*", "aCx"), - Argument("JS::Handle", "aCallback"), + [Argument("JS::Handle", "aCallback"), Argument("nsIGlobalObject*", "aIncumbentGlobal"), Argument("const FastCallbackConstructor&", "")], bodyInHeader=True, visibility="public", explicit=True, baseConstructors=[ - "%s(aCx, aCallback, aIncumbentGlobal, FastCallbackConstructor())" % self.baseName, + "%s(aCallback, aIncumbentGlobal, FastCallbackConstructor())" % self.baseName, ], body=body), ClassConstructor( @@ -15364,7 +15363,7 @@ class CGFastCallback(CGClass): visibility="public", explicit=True, baseConstructors=[ - "%s(aCx, aCallback, aIncumbentGlobal, FastCallbackConstructor())" % + "%s(aCallback, aIncumbentGlobal, FastCallbackConstructor())" % baseName, ], body="") From 3f8b6befb319ab7746094e9001fc77e9a3066f69 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 13:19:26 -0800 Subject: [PATCH 056/229] Bug 1326105 part 5. Move the getting of the incumbent global to the finish-slow-js codepath too, since it's not needed if no one will ever call our callback. r=smaug --- dom/base/nsDocument.cpp | 6 +++--- dom/bindings/CallbackFunction.h | 4 +--- dom/bindings/CallbackInterface.h | 4 +--- dom/bindings/CallbackObject.cpp | 4 ++++ dom/bindings/CallbackObject.h | 3 +-- dom/bindings/Codegen.py | 36 ++++++++++++++++---------------- 6 files changed, 28 insertions(+), 29 deletions(-) diff --git a/dom/base/nsDocument.cpp b/dom/base/nsDocument.cpp index d2199aace111..10a9eadbdec7 100644 --- a/dom/base/nsDocument.cpp +++ b/dom/base/nsDocument.cpp @@ -5957,10 +5957,10 @@ nsDocument::RegisterElement(JSContext* aCx, const nsAString& aType, options.mExtends.Construct(lcName); } - RootedCallback> functionConstructor(aCx); - functionConstructor = new binding_detail::FastFunction(aCx, wrappedConstructor, sgo); + RefPtr functionConstructor = + new Function(aCx, wrappedConstructor, sgo); - registry->Define(lcType, functionConstructor, options, rv); + registry->Define(lcType, *functionConstructor, options, rv); aRetval.set(wrappedConstructor); } diff --git a/dom/bindings/CallbackFunction.h b/dom/bindings/CallbackFunction.h index 648c7dde2207..29122b4182c1 100644 --- a/dom/bindings/CallbackFunction.h +++ b/dom/bindings/CallbackFunction.h @@ -64,10 +64,8 @@ protected: // See CallbackObject for an explanation of the arguments. CallbackFunction(JS::Handle aCallable, - nsIGlobalObject* aIncumbentGlobal, const FastCallbackConstructor&) - : CallbackObject(aCallable, aIncumbentGlobal, - FastCallbackConstructor()) + : CallbackObject(aCallable, FastCallbackConstructor()) { } }; diff --git a/dom/bindings/CallbackInterface.h b/dom/bindings/CallbackInterface.h index 4c64e3605423..6bb645f05f50 100644 --- a/dom/bindings/CallbackInterface.h +++ b/dom/bindings/CallbackInterface.h @@ -45,10 +45,8 @@ protected: // See CallbackObject for an explanation of the arguments. CallbackInterface(JS::Handle aCallable, - nsIGlobalObject* aIncumbentGlobal, const FastCallbackConstructor&) - : CallbackObject(aCallable, aIncumbentGlobal, - FastCallbackConstructor()) + : CallbackObject(aCallable, FastCallbackConstructor()) { } }; diff --git a/dom/bindings/CallbackObject.cpp b/dom/bindings/CallbackObject.cpp index ecdc88a794fd..204cca4c986c 100644 --- a/dom/bindings/CallbackObject.cpp +++ b/dom/bindings/CallbackObject.cpp @@ -68,6 +68,10 @@ CallbackObject::FinishSlowJSInitIfMoreThanOneOwner(JSContext* aCx) } mCreationStack = stack; } + mIncumbentGlobal = GetIncumbentGlobal(); + if (mIncumbentGlobal) { + mIncumbentJSGlobal = mIncumbentGlobal->GetGlobalJSObject(); + } } else { // We can just forget all our stuff. ClearJSReferences(); diff --git a/dom/bindings/CallbackObject.h b/dom/bindings/CallbackObject.h index 82af426af88d..826e78147a81 100644 --- a/dom/bindings/CallbackObject.h +++ b/dom/bindings/CallbackObject.h @@ -233,10 +233,9 @@ protected: // HoldJSObjects; see FinishSlowJSInitIfMoreThanOneOwner). If you use this, // you MUST ensure that the object is traced until the HoldJSObjects happens! CallbackObject(JS::Handle aCallback, - nsIGlobalObject* aIncumbentGlobal, const FastCallbackConstructor&) { - InitNoHold(aCallback, nullptr, aIncumbentGlobal); + InitNoHold(aCallback, nullptr, nullptr); } // mCallback is not unwrapped, so it can be a cross-compartment-wrapper. diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index f296e76f8663..ff2f7ef9fe33 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -4290,17 +4290,6 @@ class FailureFatalCastableObjectUnwrapper(CastableObjectUnwrapper): isCallbackReturnValue) -class CGCallbackTempRoot(CGGeneric): - def __init__(self, name): - define = dedent(""" - { // Scope for tempRoot - JS::Rooted tempRoot(cx, &${val}.toObject()); - ${declName} = new %s(cx, tempRoot, mozilla::dom::GetIncumbentGlobal()); - } - """) % name - CGGeneric.__init__(self, define=define) - - def getCallbackConversionInfo(type, idlObject, isMember, isCallbackReturnValue, isOptional): """ @@ -4316,6 +4305,11 @@ def getCallbackConversionInfo(type, idlObject, isMember, isCallbackReturnValue, not isOptional) if useFastCallback: name = "binding_detail::Fast%s" % name + argsPre = "" + argsPost = "" + else: + argsPre = "cx, " + argsPost = ", GetIncumbentGlobal()" if type.nullable() or isCallbackReturnValue: declType = CGGeneric("RefPtr<%s>" % name) @@ -4328,7 +4322,16 @@ def getCallbackConversionInfo(type, idlObject, isMember, isCallbackReturnValue, else: declArgs = None - conversion = indent(CGCallbackTempRoot(name).define()) + conversion = fill( + """ + { // scope for tempRoot + JS::Rooted tempRoot(cx, &$${val}.toObject()); + $${declName} = new ${name}(${argsPre}tempRoot${argsPost}); + } + """, + name=name, + argsPre=argsPre, + argsPost=argsPost) return (declType, declArgs, conversion) @@ -15177,13 +15180,12 @@ class CGCallback(CGClass): body=body), ClassConstructor( [Argument("JS::Handle", "aCallback"), - Argument("nsIGlobalObject*", "aIncumbentGlobal"), Argument("const FastCallbackConstructor&", "")], bodyInHeader=True, visibility="public", explicit=True, baseConstructors=[ - "%s(aCallback, aIncumbentGlobal, FastCallbackConstructor())" % self.baseName, + "%s(aCallback, FastCallbackConstructor())" % self.baseName, ], body=body), ClassConstructor( @@ -15356,14 +15358,12 @@ class CGFastCallback(CGClass): self._deps = idlObject.getDeps() baseName = idlObject.identifier.name constructor = ClassConstructor( - [Argument("JSContext*", "aCx"), - Argument("JS::Handle", "aCallback"), - Argument("nsIGlobalObject*", "aIncumbentGlobal")], + [Argument("JS::Handle", "aCallback")], bodyInHeader=True, visibility="public", explicit=True, baseConstructors=[ - "%s(aCallback, aIncumbentGlobal, FastCallbackConstructor())" % + "%s(aCallback, FastCallbackConstructor())" % baseName, ], body="") From 5bc2ae127e247e0281e1d3a56342339c5db2c6ac Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 13:19:26 -0800 Subject: [PATCH 057/229] Bug 1326096 part 1. Add a way to set an external string memory runtime callback. r=waldo --- js/src/jsapi.cpp | 6 ++++++ js/src/jsapi.h | 12 ++++++++++++ js/src/vm/Runtime.cpp | 1 + js/src/vm/Runtime.h | 3 +++ 4 files changed, 22 insertions(+) diff --git a/js/src/jsapi.cpp b/js/src/jsapi.cpp index 283d9c0f316c..278953a5f6f8 100644 --- a/js/src/jsapi.cpp +++ b/js/src/jsapi.cpp @@ -697,6 +697,12 @@ JS_SetWrapObjectCallbacks(JSContext* cx, const JSWrapObjectCallbacks* callbacks) cx->wrapObjectCallbacks = callbacks; } +JS_PUBLIC_API(void) +JS_SetExternalStringSizeofCallback(JSContext* cx, JSExternalStringSizeofCallback callback) +{ + cx->externalStringSizeofCallback = callback; +} + JS_PUBLIC_API(JSCompartment*) JS_EnterCompartment(JSContext* cx, JSObject* target) { diff --git a/js/src/jsapi.h b/js/src/jsapi.h index ec970624b182..7c49d1ae8ea7 100644 --- a/js/src/jsapi.h +++ b/js/src/jsapi.h @@ -728,6 +728,15 @@ typedef void (* JSCompartmentNameCallback)(JSContext* cx, JSCompartment* compartment, char* buf, size_t bufsize); +/** + * Callback used by memory reporting to ask the embedder how much memory an + * external string is keeping alive. The embedder is expected to return a value + * that corresponds to the size of the allocation that will be released by the + * JSStringFinalizer passed to JS_NewExternalString for this string. + */ +using JSExternalStringSizeofCallback = + size_t (*)(JSString* str, mozilla::MallocSizeOf mallocSizeOf); + /************************************************************************/ static MOZ_ALWAYS_INLINE JS::Value @@ -1295,6 +1304,9 @@ JS_SetCompartmentNameCallback(JSContext* cx, JSCompartmentNameCallback callback) extern JS_PUBLIC_API(void) JS_SetWrapObjectCallbacks(JSContext* cx, const JSWrapObjectCallbacks* callbacks); +extern JS_PUBLIC_API(void) +JS_SetExternalStringSizeofCallback(JSContext* cx, JSExternalStringSizeofCallback callback); + extern JS_PUBLIC_API(void) JS_SetCompartmentPrivate(JSCompartment* compartment, void* data); diff --git a/js/src/vm/Runtime.cpp b/js/src/vm/Runtime.cpp index fc4bf1f9d177..c059be497357 100644 --- a/js/src/vm/Runtime.cpp +++ b/js/src/vm/Runtime.cpp @@ -179,6 +179,7 @@ JSRuntime::JSRuntime(JSRuntime* parentRuntime) destroyZoneCallback(nullptr), sweepZoneCallback(nullptr), compartmentNameCallback(nullptr), + externalStringSizeofCallback(nullptr), activityCallback(nullptr), activityCallbackArg(nullptr), requestDepth(0), diff --git a/js/src/vm/Runtime.h b/js/src/vm/Runtime.h index a9c2edd54529..4e91e5ac63e4 100644 --- a/js/src/vm/Runtime.h +++ b/js/src/vm/Runtime.h @@ -844,6 +844,9 @@ struct JSRuntime : public JS::shadow::Runtime, /* Call this to get the name of a compartment. */ JSCompartmentNameCallback compartmentNameCallback; + /* Callback for doing memory reporting on external strings. */ + JSExternalStringSizeofCallback externalStringSizeofCallback; + js::ActivityCallback activityCallback; void* activityCallbackArg; void triggerActivityCallback(bool active); From 6600d3cc9028adfdd8f8aa488df717e9ff72a4cf Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 13:19:26 -0800 Subject: [PATCH 058/229] Bug 1326096 part 2. If there is an external string memory runtime callback, call it from memory reporting code. r=waldo --- js/src/vm/String.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/js/src/vm/String.cpp b/js/src/vm/String.cpp index 747396d84d5f..78893eaaa0f7 100644 --- a/js/src/vm/String.cpp +++ b/js/src/vm/String.cpp @@ -53,9 +53,13 @@ JSString::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) : mallocSizeOf(extensible.rawTwoByteChars()); } - // JSExternalString: don't count, the chars could be stored anywhere. - if (isExternal()) + // JSExternalString: Ask the embedding to tell us what's going on. If it + // doesn't want to say, don't count, the chars could be stored anywhere. + if (isExternal()) { + if (auto* cb = runtimeFromMainThread()->externalStringSizeofCallback) + return cb(this, mallocSizeOf); return 0; + } // JSInlineString, JSFatInlineString [JSInlineAtom, JSFatInlineAtom]: the chars are inline. if (isInline()) From fb32765d0e0383a155a4dae5741dee60a9aeeedc Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 13:19:27 -0800 Subject: [PATCH 059/229] Bug 1326096 part 3. Pass a useful external string memory reporter to SpiderMonkey from Gecko code. r=froydnj --- xpcom/base/CycleCollectedJSContext.cpp | 19 +++++++++++++++++++ xpcom/base/CycleCollectedJSContext.h | 6 ++++++ 2 files changed, 25 insertions(+) diff --git a/xpcom/base/CycleCollectedJSContext.cpp b/xpcom/base/CycleCollectedJSContext.cpp index 86bc2559a9a5..3f4c4342a3e4 100644 --- a/xpcom/base/CycleCollectedJSContext.cpp +++ b/xpcom/base/CycleCollectedJSContext.cpp @@ -81,6 +81,7 @@ #include "nsDOMJSUtils.h" #include "nsJSUtils.h" #include "nsWrapperCache.h" +#include "nsStringBuffer.h" #ifdef MOZ_CRASHREPORTER #include "nsExceptionHandler.h" @@ -531,6 +532,7 @@ CycleCollectedJSContext::Initialize(JSContext* aParentContext, JS::SetOutOfMemoryCallback(mJSContext, OutOfMemoryCallback, this); JS::SetLargeAllocationFailureCallback(mJSContext, LargeAllocationFailureCallback, this); + JS_SetExternalStringSizeofCallback(mJSContext, SizeofExternalStringCallback); JS_SetDestroyZoneCallback(mJSContext, XPCStringConvert::FreeZoneCache); JS_SetSweepZoneCallback(mJSContext, XPCStringConvert::ClearZoneCache); JS::SetBuildIdOp(mJSContext, GetBuildId); @@ -917,6 +919,23 @@ CycleCollectedJSContext::LargeAllocationFailureCallback(void* aData) self->OnLargeAllocationFailure(); } +/* static */ size_t +CycleCollectedJSContext::SizeofExternalStringCallback(JSString* aStr, + MallocSizeOf aMallocSizeOf) +{ + if (!XPCStringConvert::IsDOMString(aStr)) { + // Might be a literal or something we don't understand. Just claim 0. + return 0; + } + + const char16_t* chars = JS_GetTwoByteExternalStringChars(aStr); + const nsStringBuffer* buf = nsStringBuffer::FromData((void*)chars); + // We want sizeof including this, because the entire string buffer is owned by + // the external string. But only report here if we're unshared; if we're + // shared then we don't know who really owns this data. + return buf->SizeOfIncludingThisIfUnshared(aMallocSizeOf); +} + class PromiseJobRunnable final : public Runnable { public: diff --git a/xpcom/base/CycleCollectedJSContext.h b/xpcom/base/CycleCollectedJSContext.h index 6557ebdf42a0..90626ec35b74 100644 --- a/xpcom/base/CycleCollectedJSContext.h +++ b/xpcom/base/CycleCollectedJSContext.h @@ -216,6 +216,12 @@ private: JS::gcreason::Reason aReason); static void OutOfMemoryCallback(JSContext* aContext, void* aData); static void LargeAllocationFailureCallback(void* aData); + /** + * Callback for reporting external string memory. + */ + static size_t SizeofExternalStringCallback(JSString* aStr, + mozilla::MallocSizeOf aMallocSizeOf); + static bool ContextCallback(JSContext* aCx, unsigned aOperation, void* aData); static JSObject* GetIncumbentGlobalCallback(JSContext* aCx); From 73757c91bb969b94f1530da4e1c8f8211beb5a76 Mon Sep 17 00:00:00 2001 From: Georg Fritzsche Date: Fri, 23 Dec 2016 14:46:17 +0100 Subject: [PATCH 060/229] Bug 1312806 - Categorical histograms should default to 50 buckets. r=dexter --- toolkit/components/telemetry/Histograms.json | 13 ++++++++ .../components/telemetry/histogram_tools.py | 10 ++++-- .../telemetry/tests/unit/test_nsITelemetry.js | 31 ++++++++++++++++--- 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/toolkit/components/telemetry/Histograms.json b/toolkit/components/telemetry/Histograms.json index 30ba15eb3b91..94613744e6b7 100644 --- a/toolkit/components/telemetry/Histograms.json +++ b/toolkit/components/telemetry/Histograms.json @@ -6072,6 +6072,19 @@ ], "description": "a testing histogram; not meant to be touched" }, + "TELEMETRY_TEST_CATEGORICAL_NVALUES": { + "alert_emails": ["telemetry-client-dev@mozilla.com"], + "bug_numbers": [1188888], + "expires_in_version": "never", + "kind": "categorical", + "n_values": 70, + "labels": [ + "CommonLabel", + "Label7", + "Label8" + ], + "description": "a testing histogram; not meant to be touched" + }, "TELEMETRY_TEST_KEYED_COUNT_INIT_NO_RECORD": { "alert_emails": ["telemetry-client-dev@mozilla.com"], "expires_in_version": "never", diff --git a/toolkit/components/telemetry/histogram_tools.py b/toolkit/components/telemetry/histogram_tools.py index db64be268db2..4b10ded9b136 100644 --- a/toolkit/components/telemetry/histogram_tools.py +++ b/toolkit/components/telemetry/histogram_tools.py @@ -13,6 +13,7 @@ import sys # Constants. MAX_LABEL_LENGTH = 20 MAX_LABEL_COUNT = 100 +MIN_CATEGORICAL_BUCKET_COUNT = 50 # histogram_tools.py is used by scripts from a mozilla-central build tree # and also by outside consumers, such as the telemetry server. We need @@ -223,7 +224,7 @@ associated with the histogram. Returns None if no guarding is necessary.""" 'flag': always_allowed_keys, 'count': always_allowed_keys, 'enumerated': always_allowed_keys + ['n_values'], - 'categorical': always_allowed_keys + ['labels'], + 'categorical': always_allowed_keys + ['labels', 'n_values'], 'linear': general_keys, 'exponential': general_keys, } @@ -407,7 +408,12 @@ associated with the histogram. Returns None if no guarding is necessary.""" @staticmethod def categorical_bucket_parameters(definition): - n_values = len(definition['labels']) + # Categorical histograms default to 50 buckets to make working with them easier. + # Otherwise when adding labels later we run into problems with the pipeline not supporting bucket changes. + # This can be overridden using the n_values field. + n_values = max(len(definition['labels']), + definition.get('n_values', 0), + MIN_CATEGORICAL_BUCKET_COUNT) return (1, n_values, n_values + 1) @staticmethod diff --git a/toolkit/components/telemetry/tests/unit/test_nsITelemetry.js b/toolkit/components/telemetry/tests/unit/test_nsITelemetry.js index e02d2d2adc4c..35476721a4c5 100644 --- a/toolkit/components/telemetry/tests/unit/test_nsITelemetry.js +++ b/toolkit/components/telemetry/tests/unit/test_nsITelemetry.js @@ -212,10 +212,16 @@ add_task(function* test_categorical_histogram() h1.add(s); } + // Categorical histograms default to 50 linear buckets. + let expectedRanges = []; + for (let i = 0; i < 51; ++i) { + expectedRanges.push(i); + } + let snapshot = h1.snapshot(); Assert.equal(snapshot.sum, 6); - Assert.deepEqual(snapshot.ranges, [0, 1, 2, 3]); - Assert.deepEqual(snapshot.counts, [3, 2, 2, 0]); + Assert.deepEqual(snapshot.ranges, expectedRanges); + Assert.deepEqual(snapshot.counts.slice(0, 4), [3, 2, 2, 0]); let h2 = Telemetry.getHistogramById("TELEMETRY_TEST_CATEGORICAL_OPTOUT"); for (let v of ["CommonLabel", "CommonLabel", "Label4", "Label5", "Label6", 0, 1]) { @@ -229,8 +235,25 @@ add_task(function* test_categorical_histogram() snapshot = h2.snapshot(); Assert.equal(snapshot.sum, 7); - Assert.deepEqual(snapshot.ranges, [0, 1, 2, 3, 4]); - Assert.deepEqual(snapshot.counts, [3, 2, 1, 1, 0]); + Assert.deepEqual(snapshot.ranges, expectedRanges); + Assert.deepEqual(snapshot.counts.slice(0, 5), [3, 2, 1, 1, 0]); + + // This histogram overrides the default of 50 values to 70. + let h3 = Telemetry.getHistogramById("TELEMETRY_TEST_CATEGORICAL_NVALUES"); + for (let v of ["CommonLabel", "Label7", "Label8"]) { + h3.add(v); + } + + expectedRanges = []; + for (let i = 0; i < 71; ++i) { + expectedRanges.push(i); + } + + snapshot = h3.snapshot(); + Assert.equal(snapshot.sum, 3); + Assert.equal(snapshot.ranges.length, expectedRanges.length); + Assert.deepEqual(snapshot.ranges, expectedRanges); + Assert.deepEqual(snapshot.counts.slice(0, 4), [1, 1, 1, 0]); }); add_task(function* test_add_error_behaviour() { From ac198725dce95836efc5e5470e21722a199bd6a5 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 14:00:43 -0800 Subject: [PATCH 061/229] Bug 1326096 followup. Suppress the false-positive GC analysis failure due to us doing an indirect call that the static analysis doesn't understand. r=sfink --- js/src/jsapi.h | 2 ++ js/src/vm/String.cpp | 6 +++++- xpcom/base/CycleCollectedJSContext.cpp | 4 ++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/js/src/jsapi.h b/js/src/jsapi.h index 7c49d1ae8ea7..2a82566f189b 100644 --- a/js/src/jsapi.h +++ b/js/src/jsapi.h @@ -733,6 +733,8 @@ typedef void * external string is keeping alive. The embedder is expected to return a value * that corresponds to the size of the allocation that will be released by the * JSStringFinalizer passed to JS_NewExternalString for this string. + * + * Implementations of this callback MUST NOT do anything that can cause GC. */ using JSExternalStringSizeofCallback = size_t (*)(JSString* str, mozilla::MallocSizeOf mallocSizeOf); diff --git a/js/src/vm/String.cpp b/js/src/vm/String.cpp index 78893eaaa0f7..65bd9a240e1b 100644 --- a/js/src/vm/String.cpp +++ b/js/src/vm/String.cpp @@ -16,6 +16,7 @@ #include "gc/Marking.h" #include "js/UbiNode.h" +#include "js/GCAPI.h" #include "vm/SPSProfiler.h" #include "jscntxtinlines.h" @@ -56,8 +57,11 @@ JSString::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) // JSExternalString: Ask the embedding to tell us what's going on. If it // doesn't want to say, don't count, the chars could be stored anywhere. if (isExternal()) { - if (auto* cb = runtimeFromMainThread()->externalStringSizeofCallback) + if (auto* cb = runtimeFromMainThread()->externalStringSizeofCallback) { + // Our callback isn't supposed to cause GC. + AutoSuppressGCAnalysis nogc; return cb(this, mallocSizeOf); + } return 0; } diff --git a/xpcom/base/CycleCollectedJSContext.cpp b/xpcom/base/CycleCollectedJSContext.cpp index 3f4c4342a3e4..37e61a3a88f4 100644 --- a/xpcom/base/CycleCollectedJSContext.cpp +++ b/xpcom/base/CycleCollectedJSContext.cpp @@ -74,6 +74,7 @@ #include "mozilla/dom/ScriptSettings.h" #include "jsprf.h" #include "js/Debug.h" +#include "js/GCAPI.h" #include "nsContentUtils.h" #include "nsCycleCollectionNoteRootCallback.h" #include "nsCycleCollectionParticipant.h" @@ -923,6 +924,9 @@ CycleCollectedJSContext::LargeAllocationFailureCallback(void* aData) CycleCollectedJSContext::SizeofExternalStringCallback(JSString* aStr, MallocSizeOf aMallocSizeOf) { + // We promised the JS engine we would not GC. Enforce that: + JS::AutoCheckCannotGC autoCannotGC; + if (!XPCStringConvert::IsDOMString(aStr)) { // Might be a literal or something we don't understand. Just claim 0. return 0; From ed2c1ef6c37f26684b83b9ade3d795a2ede3d9d3 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 14:24:47 -0800 Subject: [PATCH 062/229] Bug 1326096 another followup: fix build bustage on CLOSED TREE. --- dom/encoding/TextEncoder.cpp | 10 ++++++++++ dom/encoding/TextEncoder.h | 2 ++ dom/webidl/TextEncoder.webidl | 7 +++++++ js/src/vm/String.cpp | 2 +- 4 files changed, 20 insertions(+), 1 deletion(-) diff --git a/dom/encoding/TextEncoder.cpp b/dom/encoding/TextEncoder.cpp index ccd298b38910..7257daba44df 100644 --- a/dom/encoding/TextEncoder.cpp +++ b/dom/encoding/TextEncoder.cpp @@ -77,5 +77,15 @@ TextEncoder::GetEncoding(nsAString& aEncoding) aEncoding.AssignLiteral("utf-8"); } +void +TextEncoder::Foo(const GlobalObject&) +{ + NS_NAMED_LITERAL_STRING(str, "{\"a\":5, \"b\": 7}"); + for (int i = 0; i < 5000; ++i) { + FoopySticks f; + f.Init(str); + } +} + } // namespace dom } // namespace mozilla diff --git a/dom/encoding/TextEncoder.h b/dom/encoding/TextEncoder.h index ed08e4023427..fdaea4927c8a 100644 --- a/dom/encoding/TextEncoder.h +++ b/dom/encoding/TextEncoder.h @@ -44,6 +44,8 @@ public: return TextEncoderBinding::Wrap(aCx, this, aGivenProto, aReflector); } + static void Foo(const GlobalObject& aGlobal); + protected: void Init(); diff --git a/dom/webidl/TextEncoder.webidl b/dom/webidl/TextEncoder.webidl index 9269b572d4a2..8e733f80c175 100644 --- a/dom/webidl/TextEncoder.webidl +++ b/dom/webidl/TextEncoder.webidl @@ -10,6 +10,11 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ +dictionary FoopySticks { + required long x; + required long y; +}; + [Constructor, Exposed=(Window,Worker,System)] interface TextEncoder { @@ -17,4 +22,6 @@ interface TextEncoder { readonly attribute DOMString encoding; [NewObject] Uint8Array encode(optional USVString input = ""); + + static void foo(); }; diff --git a/js/src/vm/String.cpp b/js/src/vm/String.cpp index 65bd9a240e1b..8da16a102a0b 100644 --- a/js/src/vm/String.cpp +++ b/js/src/vm/String.cpp @@ -59,7 +59,7 @@ JSString::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) if (isExternal()) { if (auto* cb = runtimeFromMainThread()->externalStringSizeofCallback) { // Our callback isn't supposed to cause GC. - AutoSuppressGCAnalysis nogc; + JS::AutoSuppressGCAnalysis nogc; return cb(this, mallocSizeOf); } return 0; From 2ff7994e5ddae548e9b4dc0e4eadadd68f9f96e4 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 14:34:37 -0800 Subject: [PATCH 063/229] Back out bits that should not have landed for bug 1326096 on CLOSED TREE. --- dom/encoding/TextEncoder.cpp | 10 ---------- dom/encoding/TextEncoder.h | 2 -- dom/webidl/TextEncoder.webidl | 7 ------- 3 files changed, 19 deletions(-) diff --git a/dom/encoding/TextEncoder.cpp b/dom/encoding/TextEncoder.cpp index 7257daba44df..ccd298b38910 100644 --- a/dom/encoding/TextEncoder.cpp +++ b/dom/encoding/TextEncoder.cpp @@ -77,15 +77,5 @@ TextEncoder::GetEncoding(nsAString& aEncoding) aEncoding.AssignLiteral("utf-8"); } -void -TextEncoder::Foo(const GlobalObject&) -{ - NS_NAMED_LITERAL_STRING(str, "{\"a\":5, \"b\": 7}"); - for (int i = 0; i < 5000; ++i) { - FoopySticks f; - f.Init(str); - } -} - } // namespace dom } // namespace mozilla diff --git a/dom/encoding/TextEncoder.h b/dom/encoding/TextEncoder.h index fdaea4927c8a..ed08e4023427 100644 --- a/dom/encoding/TextEncoder.h +++ b/dom/encoding/TextEncoder.h @@ -44,8 +44,6 @@ public: return TextEncoderBinding::Wrap(aCx, this, aGivenProto, aReflector); } - static void Foo(const GlobalObject& aGlobal); - protected: void Init(); diff --git a/dom/webidl/TextEncoder.webidl b/dom/webidl/TextEncoder.webidl index 8e733f80c175..9269b572d4a2 100644 --- a/dom/webidl/TextEncoder.webidl +++ b/dom/webidl/TextEncoder.webidl @@ -10,11 +10,6 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ -dictionary FoopySticks { - required long x; - required long y; -}; - [Constructor, Exposed=(Window,Worker,System)] interface TextEncoder { @@ -22,6 +17,4 @@ interface TextEncoder { readonly attribute DOMString encoding; [NewObject] Uint8Array encode(optional USVString input = ""); - - static void foo(); }; From bc6e0e2c1ff7a5600ac94b0af47174a7235aa4df Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 14:38:29 -0800 Subject: [PATCH 064/229] Bug 1326096 yet another followup. Silence the opinionated spidermonkey include style checker on CLOSED TREE --- js/src/vm/String.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/src/vm/String.cpp b/js/src/vm/String.cpp index 8da16a102a0b..a87e4f18d743 100644 --- a/js/src/vm/String.cpp +++ b/js/src/vm/String.cpp @@ -15,8 +15,8 @@ #include "mozilla/Unused.h" #include "gc/Marking.h" -#include "js/UbiNode.h" #include "js/GCAPI.h" +#include "js/UbiNode.h" #include "vm/SPSProfiler.h" #include "jscntxtinlines.h" From d41fa7c9410ab349f7bd390733d74638d6032663 Mon Sep 17 00:00:00 2001 From: Bill McCloskey Date: Tue, 27 Dec 2016 13:35:07 -0800 Subject: [PATCH 065/229] Bug 1325919 - Allow EventTargetFor to be used after last window has been destroyed (r=smaug) MozReview-Commit-ID: 7p9dnf8KzIx --- dom/base/TabGroup.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/dom/base/TabGroup.cpp b/dom/base/TabGroup.cpp index d09fe2c6f98d..4e266a8e9106 100644 --- a/dom/base/TabGroup.cpp +++ b/dom/base/TabGroup.cpp @@ -51,6 +51,7 @@ TabGroup::~TabGroup() { MOZ_ASSERT(mDocGroups.IsEmpty()); MOZ_ASSERT(mWindows.IsEmpty()); + MOZ_RELEASE_ASSERT(mLastWindowLeft); } void @@ -149,6 +150,7 @@ TabGroup::Join(nsPIDOMWindowOuter* aWindow, TabGroup* aTabGroup) if (!tabGroup) { tabGroup = new TabGroup(); } + MOZ_RELEASE_ASSERT(!tabGroup->mLastWindowLeft); MOZ_ASSERT(!tabGroup->mWindows.Contains(aWindow)); tabGroup->mWindows.AppendElement(aWindow); return tabGroup.forget(); @@ -258,7 +260,13 @@ TabGroup::EventTargetFor(TaskCategory aCategory) const MOZ_RELEASE_ASSERT(mThrottledQueuesInitialized || this == sChromeTabGroup); } - MOZ_RELEASE_ASSERT(!mLastWindowLeft); + if (NS_WARN_IF(mLastWindowLeft)) { + // Once we've disconnected everything, we still allow people to + // dispatch. We'll just go directly to the main thread. + nsCOMPtr main = do_GetMainThread(); + return main; + } + return mEventTargets[size_t(aCategory)]; } From 2c2be20d6b133169c362f5728be368ec451327f2 Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Tue, 22 Nov 2016 12:32:44 -0800 Subject: [PATCH 066/229] Bug 1296814 - Inline Parser::reportHelper into its callers. r=arai --HG-- extra : rebase_source : 8da3a61cf898d10278b7e7ac639ce3c140a4b1b5 --- js/src/frontend/Parser.cpp | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/js/src/frontend/Parser.cpp b/js/src/frontend/Parser.cpp index 16b2215629d9..76e94ce1c2ef 100644 --- a/js/src/frontend/Parser.cpp +++ b/js/src/frontend/Parser.cpp @@ -600,7 +600,7 @@ Parser::error(unsigned errorNumber, ...) #ifdef DEBUG bool result = #endif - reportHelper(ParseError, false, pos().begin, errorNumber, args); + tokenStream.reportCompileErrorNumberVA(pos().begin, JSREPORT_ERROR, errorNumber, args); MOZ_ASSERT(!result, "reporting an error returned true?"); va_end(args); } @@ -614,7 +614,7 @@ Parser::errorAt(uint32_t offset, unsigned errorNumber, ...) #ifdef DEBUG bool result = #endif - reportHelper(ParseError, false, offset, errorNumber, args); + tokenStream.reportCompileErrorNumberVA(offset, JSREPORT_ERROR, errorNumber, args); MOZ_ASSERT(!result, "reporting an error returned true?"); va_end(args); } @@ -625,7 +625,8 @@ Parser::warning(unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); - bool result = reportHelper(ParseWarning, false, pos().begin, errorNumber, args); + bool result = + tokenStream.reportCompileErrorNumberVA(pos().begin, JSREPORT_WARNING, errorNumber, args); va_end(args); return result; } @@ -636,7 +637,8 @@ Parser::warningAt(uint32_t offset, unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); - bool result = reportHelper(ParseWarning, false, offset, errorNumber, args); + bool result = + tokenStream.reportCompileErrorNumberVA(offset, JSREPORT_WARNING, errorNumber, args); va_end(args); return result; } @@ -647,7 +649,7 @@ Parser::extraWarning(unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); - bool result = reportHelper(ParseExtraWarning, false, pos().begin, errorNumber, args); + bool result = tokenStream.reportStrictWarningErrorNumberVA(pos().begin, errorNumber, args); va_end(args); return result; } @@ -658,7 +660,9 @@ Parser::strictModeError(unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); - bool res = reportHelper(ParseStrictError, pc->sc()->strict(), pos().begin, errorNumber, args); + bool res = + tokenStream.reportStrictModeErrorNumberVA(pos().begin, pc->sc()->strict(), + errorNumber, args); va_end(args); return res; } @@ -669,7 +673,8 @@ Parser::strictModeErrorAt(uint32_t offset, unsigned errorNumber, . { va_list args; va_start(args, errorNumber); - bool res = reportHelper(ParseStrictError, pc->sc()->strict(), offset, errorNumber, args); + bool res = + tokenStream.reportStrictModeErrorNumberVA(offset, pc->sc()->strict(), errorNumber, args); va_end(args); return res; } @@ -680,7 +685,23 @@ Parser::reportNoOffset(ParseReportKind kind, bool strict, unsigned { va_list args; va_start(args, errorNumber); - bool result = reportHelper(kind, strict, TokenStream::NoOffset, errorNumber, args); + bool result = false; + uint32_t offset = TokenStream::NoOffset; + switch (kind) { + case ParseError: + result = tokenStream.reportCompileErrorNumberVA(offset, JSREPORT_ERROR, errorNumber, args); + break; + case ParseWarning: + result = + tokenStream.reportCompileErrorNumberVA(offset, JSREPORT_WARNING, errorNumber, args); + break; + case ParseExtraWarning: + result = tokenStream.reportStrictWarningErrorNumberVA(offset, errorNumber, args); + break; + case ParseStrictError: + result = tokenStream.reportStrictModeErrorNumberVA(offset, strict, errorNumber, args); + break; + } va_end(args); return result; } From 1e55fd2bd6af1a33701231bd4329dd7a55e40d53 Mon Sep 17 00:00:00 2001 From: Gerald Squelart Date: Thu, 24 Nov 2016 15:21:11 +1100 Subject: [PATCH 067/229] Bug 1315089 - Block D3D11 for igd11dxva64.dll 20.19.15.X - r=kentuckyfriedtakahe MozReview-Commit-ID: Ihatn3l2GFJ --HG-- extra : rebase_source : cefe01fe65822085d193b5e09c6fb1f34a97c6fb extra : histedit_source : 46910f48794a4e587d14b3bfd6afd53a64af758a --- modules/libpref/init/all.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js index b65258600c27..66df4939d7f6 100644 --- a/modules/libpref/init/all.js +++ b/modules/libpref/init/all.js @@ -352,7 +352,7 @@ pref("media.wmf.low-latency.enabled", false); pref("media.wmf.skip-blacklist", false); pref("media.wmf.vp9.enabled", true); pref("media.windows-media-foundation.allow-d3d11-dxva", true); -pref("media.wmf.disable-d3d11-for-dlls", "igd10iumd32.dll: 20.19.15.4444, 20.19.15.4424, 20.19.15.4409, 20.19.15.4390, 20.19.15.4380, 20.19.15.4360, 10.18.10.4358, 20.19.15.4331, 20.19.15.4312, 20.19.15.4300, 10.18.15.4281, 10.18.15.4279, 10.18.10.4276, 10.18.15.4268, 10.18.15.4256, 10.18.10.4252, 10.18.15.4248, 10.18.14.4112, 10.18.10.3958, 10.18.10.3496, 10.18.10.3431, 10.18.10.3412, 10.18.10.3355, 9.18.10.3234, 9.18.10.3071, 9.18.10.3055, 9.18.10.3006; igd10umd32.dll: 9.17.10.4229, 9.17.10.3040, 9.17.10.2857, 8.15.10.2274, 8.15.10.2272, 8.15.10.2246, 8.15.10.1840, 8.15.10.1808; igd10umd64.dll: 9.17.10.4229, 9.17.10.2857, 10.18.10.3496; isonyvideoprocessor.dll: 4.1.2247.8090, 4.1.2153.6200; tosqep.dll: 1.2.15.526, 1.1.12.201, 1.0.11.318, 1.0.11.215, 1.0.10.1224; tosqep64.dll: 1.1.12.201, 1.0.11.215; nvwgf2um.dll: 10.18.13.6510, 10.18.13.5891, 10.18.13.5887, 10.18.13.5582, 10.18.13.5382, 9.18.13.4195, 9.18.13.3165; atidxx32.dll: 21.19.151.3, 21.19.137.1, 21.19.134.1, 20.19.0.32837, 20.19.0.32832, 8.17.10.682, 8.17.10.671, 8.17.10.661, 8.17.10.648, 8.17.10.644, 8.17.10.625, 8.17.10.605, 8.17.10.581, 8.17.10.569, 8.17.10.560, 8.17.10.545, 8.17.10.539, 8.17.10.531, 8.17.10.525, 8.17.10.520, 8.17.10.519, 8.17.10.514, 8.17.10.511, 8.17.10.494, 8.17.10.489, 8.17.10.483, 8.17.10.453, 8.17.10.451, 8.17.10.441, 8.17.10.436, 8.17.10.432, 8.17.10.425, 8.17.10.418, 8.17.10.414, 8.17.10.401, 8.17.10.395, 8.17.10.385, 8.17.10.378, 8.17.10.362, 8.17.10.355, 8.17.10.342, 8.17.10.331, 8.17.10.318, 8.17.10.310, 8.17.10.286, 8.17.10.269, 8.17.10.261, 8.17.10.247, 8.17.10.240, 8.15.10.212; atidxx64.dll: 21.19.151.3, 21.19.137.1, 21.19.134.1, 20.19.0.32832, 8.17.10.682, 8.17.10.661, 8.17.10.644, 8.17.10.625; nvumdshim.dll: 10.18.13.6822"); +pref("media.wmf.disable-d3d11-for-dlls", "igd11dxva64.dll: 20.19.15.4463, 20.19.15.4454, 20.19.15.4444, 20.19.15.4416, 20.19.15.4390, 20.19.15.4380, 20.19.15.4377, 20.19.15.4364, 20.19.15.4360, 20.19.15.4352, 20.19.15.4331, 20.19.15.4326, 20.19.15.4300; igd10iumd32.dll: 20.19.15.4444, 20.19.15.4424, 20.19.15.4409, 20.19.15.4390, 20.19.15.4380, 20.19.15.4360, 10.18.10.4358, 20.19.15.4331, 20.19.15.4312, 20.19.15.4300, 10.18.15.4281, 10.18.15.4279, 10.18.10.4276, 10.18.15.4268, 10.18.15.4256, 10.18.10.4252, 10.18.15.4248, 10.18.14.4112, 10.18.10.3958, 10.18.10.3496, 10.18.10.3431, 10.18.10.3412, 10.18.10.3355, 9.18.10.3234, 9.18.10.3071, 9.18.10.3055, 9.18.10.3006; igd10umd32.dll: 9.17.10.4229, 9.17.10.3040, 9.17.10.2857, 8.15.10.2274, 8.15.10.2272, 8.15.10.2246, 8.15.10.1840, 8.15.10.1808; igd10umd64.dll: 9.17.10.4229, 9.17.10.2857, 10.18.10.3496; isonyvideoprocessor.dll: 4.1.2247.8090, 4.1.2153.6200; tosqep.dll: 1.2.15.526, 1.1.12.201, 1.0.11.318, 1.0.11.215, 1.0.10.1224; tosqep64.dll: 1.1.12.201, 1.0.11.215; nvwgf2um.dll: 10.18.13.6510, 10.18.13.5891, 10.18.13.5887, 10.18.13.5582, 10.18.13.5382, 9.18.13.4195, 9.18.13.3165; atidxx32.dll: 21.19.151.3, 21.19.137.1, 21.19.134.1, 20.19.0.32837, 20.19.0.32832, 8.17.10.682, 8.17.10.671, 8.17.10.661, 8.17.10.648, 8.17.10.644, 8.17.10.625, 8.17.10.605, 8.17.10.581, 8.17.10.569, 8.17.10.560, 8.17.10.545, 8.17.10.539, 8.17.10.531, 8.17.10.525, 8.17.10.520, 8.17.10.519, 8.17.10.514, 8.17.10.511, 8.17.10.494, 8.17.10.489, 8.17.10.483, 8.17.10.453, 8.17.10.451, 8.17.10.441, 8.17.10.436, 8.17.10.432, 8.17.10.425, 8.17.10.418, 8.17.10.414, 8.17.10.401, 8.17.10.395, 8.17.10.385, 8.17.10.378, 8.17.10.362, 8.17.10.355, 8.17.10.342, 8.17.10.331, 8.17.10.318, 8.17.10.310, 8.17.10.286, 8.17.10.269, 8.17.10.261, 8.17.10.247, 8.17.10.240, 8.15.10.212; atidxx64.dll: 21.19.151.3, 21.19.137.1, 21.19.134.1, 20.19.0.32832, 8.17.10.682, 8.17.10.661, 8.17.10.644, 8.17.10.625; nvumdshim.dll: 10.18.13.6822"); pref("media.wmf.disable-d3d9-for-dlls", "igdumd64.dll: 8.15.10.2189, 8.15.10.2119, 8.15.10.2104, 8.15.10.2102, 8.771.1.0; atiumd64.dll: 7.14.10.833, 7.14.10.867, 7.14.10.885, 7.14.10.903, 7.14.10.911, 8.14.10.768, 9.14.10.1001, 9.14.10.1017, 9.14.10.1080, 9.14.10.1128, 9.14.10.1162, 9.14.10.1171, 9.14.10.1183, 9.14.10.1197, 9.14.10.945, 9.14.10.972, 9.14.10.984, 9.14.10.996"); #endif #if defined(MOZ_FFMPEG) From af5cee34f2877322b8ad72e277b7cce110c0fb37 Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Fri, 9 Dec 2016 11:15:09 -1000 Subject: [PATCH 068/229] Bug 1296814 - Remove Parser::reportHelper. r=arai --HG-- extra : rebase_source : b9d6576ecdf7edbf7e290c81f4c0996d5adf9d0b --- js/src/frontend/Parser.cpp | 24 ------------------------ js/src/frontend/Parser.h | 3 --- 2 files changed, 27 deletions(-) diff --git a/js/src/frontend/Parser.cpp b/js/src/frontend/Parser.cpp index 76e94ce1c2ef..113247aba180 100644 --- a/js/src/frontend/Parser.cpp +++ b/js/src/frontend/Parser.cpp @@ -567,30 +567,6 @@ FunctionBox::initWithEnclosingScope(Scope* enclosingScope) computeInWith(enclosingScope); } -template -bool -Parser::reportHelper(ParseReportKind kind, bool strict, uint32_t offset, - unsigned errorNumber, va_list args) -{ - bool result = false; - switch (kind) { - case ParseError: - result = tokenStream.reportCompileErrorNumberVA(offset, JSREPORT_ERROR, errorNumber, args); - break; - case ParseWarning: - result = - tokenStream.reportCompileErrorNumberVA(offset, JSREPORT_WARNING, errorNumber, args); - break; - case ParseExtraWarning: - result = tokenStream.reportStrictWarningErrorNumberVA(offset, errorNumber, args); - break; - case ParseStrictError: - result = tokenStream.reportStrictModeErrorNumberVA(offset, strict, errorNumber, args); - break; - } - return result; -} - template void Parser::error(unsigned errorNumber, ...) diff --git a/js/src/frontend/Parser.h b/js/src/frontend/Parser.h index 1f3258cd9d55..0fe735ab1a13 100644 --- a/js/src/frontend/Parser.h +++ b/js/src/frontend/Parser.h @@ -903,9 +903,6 @@ class Parser final : private JS::AutoGCRooter, public StrictModeGetter void prepareNodeForMutation(Node node) { handler.prepareNodeForMutation(node); } void freeTree(Node node) { handler.freeTree(node); } - private: - bool reportHelper(ParseReportKind kind, bool strict, uint32_t offset, - unsigned errorNumber, va_list args); public: bool reportNoOffset(ParseReportKind kind, bool strict, unsigned errorNumber, ...); From 86d91d1baa0d989928368ff4be4ca8dfaa0a2aad Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Fri, 9 Dec 2016 11:16:49 -1000 Subject: [PATCH 069/229] Bug 1296814 - Rename TokenStream::reportStrictWarningErrorNumberVA to TokenStream::reportExtraWarningErrorNumberVA for clarity. r=arai --HG-- extra : rebase_source : db112e454fd7c4c1b3b37d2090ee80585f53be64 --- js/src/frontend/BytecodeEmitter.cpp | 8 ++++---- js/src/frontend/BytecodeEmitter.h | 2 +- js/src/frontend/Parser.cpp | 4 ++-- js/src/frontend/TokenStream.cpp | 2 +- js/src/frontend/TokenStream.h | 3 +-- 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/js/src/frontend/BytecodeEmitter.cpp b/js/src/frontend/BytecodeEmitter.cpp index 9f97b68b7b3d..211dc041ab56 100644 --- a/js/src/frontend/BytecodeEmitter.cpp +++ b/js/src/frontend/BytecodeEmitter.cpp @@ -2902,13 +2902,13 @@ BytecodeEmitter::reportError(ParseNode* pn, unsigned errorNumber, ...) } bool -BytecodeEmitter::reportStrictWarning(ParseNode* pn, unsigned errorNumber, ...) +BytecodeEmitter::reportExtraWarning(ParseNode* pn, unsigned errorNumber, ...) { TokenPos pos = pn ? pn->pn_pos : tokenStream()->currentToken().pos; va_list args; va_start(args, errorNumber); - bool result = tokenStream()->reportStrictWarningErrorNumberVA(pos.begin, errorNumber, args); + bool result = tokenStream()->reportExtraWarningErrorNumberVA(pos.begin, errorNumber, args); va_end(args); return result; } @@ -7918,13 +7918,13 @@ BytecodeEmitter::emitStatement(ParseNode* pn) } if (directive) { - if (!reportStrictWarning(pn2, JSMSG_CONTRARY_NONDIRECTIVE, directive)) + if (!reportExtraWarning(pn2, JSMSG_CONTRARY_NONDIRECTIVE, directive)) return false; } } else { current->currentLine = parser->tokenStream.srcCoords.lineNum(pn2->pn_pos.begin); current->lastColumn = 0; - if (!reportStrictWarning(pn2, JSMSG_USELESS_EXPR)) + if (!reportExtraWarning(pn2, JSMSG_USELESS_EXPR)) return false; } } diff --git a/js/src/frontend/BytecodeEmitter.h b/js/src/frontend/BytecodeEmitter.h index 066c06672943..3d83f47bf985 100644 --- a/js/src/frontend/BytecodeEmitter.h +++ b/js/src/frontend/BytecodeEmitter.h @@ -386,7 +386,7 @@ struct MOZ_STACK_CLASS BytecodeEmitter } bool reportError(ParseNode* pn, unsigned errorNumber, ...); - bool reportStrictWarning(ParseNode* pn, unsigned errorNumber, ...); + bool reportExtraWarning(ParseNode* pn, unsigned errorNumber, ...); bool reportStrictModeError(ParseNode* pn, unsigned errorNumber, ...); // If pn contains a useful expression, return true with *answer set to true. diff --git a/js/src/frontend/Parser.cpp b/js/src/frontend/Parser.cpp index 113247aba180..3d08e237e362 100644 --- a/js/src/frontend/Parser.cpp +++ b/js/src/frontend/Parser.cpp @@ -625,7 +625,7 @@ Parser::extraWarning(unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); - bool result = tokenStream.reportStrictWarningErrorNumberVA(pos().begin, errorNumber, args); + bool result = tokenStream.reportExtraWarningErrorNumberVA(pos().begin, errorNumber, args); va_end(args); return result; } @@ -672,7 +672,7 @@ Parser::reportNoOffset(ParseReportKind kind, bool strict, unsigned tokenStream.reportCompileErrorNumberVA(offset, JSREPORT_WARNING, errorNumber, args); break; case ParseExtraWarning: - result = tokenStream.reportStrictWarningErrorNumberVA(offset, errorNumber, args); + result = tokenStream.reportExtraWarningErrorNumberVA(offset, errorNumber, args); break; case ParseStrictError: result = tokenStream.reportStrictModeErrorNumberVA(offset, strict, errorNumber, args); diff --git a/js/src/frontend/TokenStream.cpp b/js/src/frontend/TokenStream.cpp index 179a7c244725..eeac549821a6 100644 --- a/js/src/frontend/TokenStream.cpp +++ b/js/src/frontend/TokenStream.cpp @@ -780,7 +780,7 @@ TokenStream::reportWarning(unsigned errorNumber, ...) } bool -TokenStream::reportStrictWarningErrorNumberVA(uint32_t offset, unsigned errorNumber, va_list args) +TokenStream::reportExtraWarningErrorNumberVA(uint32_t offset, unsigned errorNumber, va_list args) { if (!options().extraWarningsOption) return true; diff --git a/js/src/frontend/TokenStream.h b/js/src/frontend/TokenStream.h index 03a580072993..6ba9fba5a6dc 100644 --- a/js/src/frontend/TokenStream.h +++ b/js/src/frontend/TokenStream.h @@ -375,8 +375,7 @@ class MOZ_STACK_CLASS TokenStream va_list args); bool reportStrictModeErrorNumberVA(uint32_t offset, bool strictMode, unsigned errorNumber, va_list args); - bool reportStrictWarningErrorNumberVA(uint32_t offset, unsigned errorNumber, - va_list args); + bool reportExtraWarningErrorNumberVA(uint32_t offset, unsigned errorNumber, va_list args); // asm.js reporter void reportAsmJSError(uint32_t offset, unsigned errorNumber, ...); From a96f0e6d3553f2fc219e8f62d57b1ed63c21347d Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Wed, 28 Dec 2016 14:56:51 -0600 Subject: [PATCH 070/229] Bug 1325157 - Implement a ParserBase class that holds functionality that's identical between syntax parsing and full parsing. r=arai --HG-- extra : rebase_source : 0cb984199d57d040c52f05dd3e856329fc8a3095 --- js/src/frontend/Parser.cpp | 119 +++++++++-------- js/src/frontend/Parser.h | 254 +++++++++++++++++++------------------ 2 files changed, 192 insertions(+), 181 deletions(-) diff --git a/js/src/frontend/Parser.cpp b/js/src/frontend/Parser.cpp index 3d08e237e362..35cf8f8744fb 100644 --- a/js/src/frontend/Parser.cpp +++ b/js/src/frontend/Parser.cpp @@ -567,9 +567,8 @@ FunctionBox::initWithEnclosingScope(Scope* enclosingScope) computeInWith(enclosingScope); } -template void -Parser::error(unsigned errorNumber, ...) +ParserBase::error(unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); @@ -581,9 +580,8 @@ Parser::error(unsigned errorNumber, ...) va_end(args); } -template void -Parser::errorAt(uint32_t offset, unsigned errorNumber, ...) +ParserBase::errorAt(uint32_t offset, unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); @@ -595,9 +593,8 @@ Parser::errorAt(uint32_t offset, unsigned errorNumber, ...) va_end(args); } -template bool -Parser::warning(unsigned errorNumber, ...) +ParserBase::warning(unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); @@ -607,9 +604,8 @@ Parser::warning(unsigned errorNumber, ...) return result; } -template bool -Parser::warningAt(uint32_t offset, unsigned errorNumber, ...) +ParserBase::warningAt(uint32_t offset, unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); @@ -619,9 +615,8 @@ Parser::warningAt(uint32_t offset, unsigned errorNumber, ...) return result; } -template bool -Parser::extraWarning(unsigned errorNumber, ...) +ParserBase::extraWarning(unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); @@ -630,9 +625,8 @@ Parser::extraWarning(unsigned errorNumber, ...) return result; } -template bool -Parser::strictModeError(unsigned errorNumber, ...) +ParserBase::strictModeError(unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); @@ -643,9 +637,8 @@ Parser::strictModeError(unsigned errorNumber, ...) return res; } -template bool -Parser::strictModeErrorAt(uint32_t offset, unsigned errorNumber, ...) +ParserBase::strictModeErrorAt(uint32_t offset, unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); @@ -655,9 +648,8 @@ Parser::strictModeErrorAt(uint32_t offset, unsigned errorNumber, . return res; } -template bool -Parser::reportNoOffset(ParseReportKind kind, bool strict, unsigned errorNumber, ...) +ParserBase::reportNoOffset(ParseReportKind kind, bool strict, unsigned errorNumber, ...) { va_list args; va_start(args, errorNumber); @@ -698,16 +690,14 @@ Parser::abortIfSyntaxParser() return false; } -template -Parser::Parser(ExclusiveContext* cx, LifoAlloc& alloc, - const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, - bool foldConstants, - UsedNameTracker& usedNames, - Parser* syntaxParser, - LazyScript* lazyOuterFunction) - : AutoGCRooter(cx, PARSER), - context(cx), +ParserBase::ParserBase(ExclusiveContext* cx, LifoAlloc& alloc, + const ReadOnlyCompileOptions& options, + const char16_t* chars, size_t length, + bool foldConstants, + UsedNameTracker& usedNames, + Parser* syntaxParser, + LazyScript* lazyOuterFunction) + : context(cx), alloc(alloc), tokenStream(cx, options, chars, length, thisForCtor()), traceListHead(nullptr), @@ -721,38 +711,14 @@ Parser::Parser(ExclusiveContext* cx, LifoAlloc& alloc, checkOptionsCalled(false), #endif abortedSyntaxParse(false), - isUnexpectedEOF_(false), - handler(cx, alloc, tokenStream, syntaxParser, lazyOuterFunction) + isUnexpectedEOF_(false) { cx->perThreadData->frontendCollectionPool.addActiveCompilation(); - - // The Mozilla specific JSOPTION_EXTRA_WARNINGS option adds extra warnings - // which are not generated if functions are parsed lazily. Note that the - // standard "use strict" does not inhibit lazy parsing. - if (options.extraWarningsOption) - handler.disableSyntaxParser(); - tempPoolMark = alloc.mark(); } -template -bool -Parser::checkOptions() +ParserBase::~ParserBase() { -#ifdef DEBUG - checkOptionsCalled = true; -#endif - - if (!tokenStream.checkOptions()) - return false; - - return true; -} - -template -Parser::~Parser() -{ - MOZ_ASSERT(checkOptionsCalled); alloc.release(tempPoolMark); /* @@ -765,6 +731,43 @@ Parser::~Parser() context->perThreadData->frontendCollectionPool.removeActiveCompilation(); } +template +Parser::Parser(ExclusiveContext* cx, LifoAlloc& alloc, + const ReadOnlyCompileOptions& options, + const char16_t* chars, size_t length, + bool foldConstants, + UsedNameTracker& usedNames, + Parser* syntaxParser, + LazyScript* lazyOuterFunction) + : ParserBase(cx, alloc, options, chars, length, foldConstants, usedNames, syntaxParser, + lazyOuterFunction), + AutoGCRooter(cx, PARSER), + handler(cx, alloc, tokenStream, syntaxParser, lazyOuterFunction) +{ + // The Mozilla specific JSOPTION_EXTRA_WARNINGS option adds extra warnings + // which are not generated if functions are parsed lazily. Note that the + // standard "use strict" does not inhibit lazy parsing. + if (options.extraWarningsOption) + handler.disableSyntaxParser(); +} + +template +bool +Parser::checkOptions() +{ +#ifdef DEBUG + checkOptionsCalled = true; +#endif + + return tokenStream.checkOptions(); +} + +template +Parser::~Parser() +{ + MOZ_ASSERT(checkOptionsCalled); +} + template ObjectBox* Parser::newObjectBox(JSObject* obj) @@ -891,9 +894,8 @@ Parser::parse() * Strict mode forbids introducing new definitions for 'eval', 'arguments', or * for any strict mode reserved keyword. */ -template bool -Parser::isValidStrictBinding(PropertyName* name) +ParserBase::isValidStrictBinding(PropertyName* name) { return name != context->names().eval && name != context->names().arguments && @@ -9541,9 +9543,8 @@ Parser::exprInParens(InHandling inHandling, YieldHandling yieldHan return expr(inHandling, yieldHandling, tripledotHandling, possibleError, PredictInvoked); } -template void -Parser::addTelemetry(JSCompartment::DeprecatedLanguageExtension e) +ParserBase::addTelemetry(JSCompartment::DeprecatedLanguageExtension e) { JSContext* cx = context->maybeJSContext(); if (!cx) @@ -9551,9 +9552,8 @@ Parser::addTelemetry(JSCompartment::DeprecatedLanguageExtension e) cx->compartment()->addTelemetry(getFilename(), e); } -template bool -Parser::warnOnceAboutExprClosure() +ParserBase::warnOnceAboutExprClosure() { #ifndef RELEASE_OR_BETA JSContext* cx = context->maybeJSContext(); @@ -9569,9 +9569,8 @@ Parser::warnOnceAboutExprClosure() return true; } -template bool -Parser::warnOnceAboutForEach() +ParserBase::warnOnceAboutForEach() { JSContext* cx = context->maybeJSContext(); if (!cx) diff --git a/js/src/frontend/Parser.h b/js/src/frontend/Parser.h index 0fe735ab1a13..0f6f2c77b03a 100644 --- a/js/src/frontend/Parser.h +++ b/js/src/frontend/Parser.h @@ -734,8 +734,140 @@ class UsedNameTracker } }; +class ParserBase : public StrictModeGetter +{ + private: + ParserBase* thisForCtor() { return this; } + + public: + ExclusiveContext* const context; + + LifoAlloc& alloc; + + TokenStream tokenStream; + LifoAlloc::Mark tempPoolMark; + + /* list of parsed objects for GC tracing */ + ObjectBox* traceListHead; + + /* innermost parse context (stack-allocated) */ + ParseContext* pc; + + // For tracking used names in this parsing session. + UsedNameTracker& usedNames; + + /* Compression token for aborting. */ + SourceCompressionTask* sct; + + ScriptSource* ss; + + /* Root atoms and objects allocated for the parsed tree. */ + AutoKeepAtoms keepAtoms; + + /* Perform constant-folding; must be true when interfacing with the emitter. */ + const bool foldConstants:1; + + protected: +#if DEBUG + /* Our fallible 'checkOptions' member function has been called. */ + bool checkOptionsCalled:1; +#endif + + /* + * Not all language constructs can be handled during syntax parsing. If it + * is not known whether the parse succeeds or fails, this bit is set and + * the parse will return false. + */ + bool abortedSyntaxParse:1; + + /* Unexpected end of input, i.e. TOK_EOF not at top-level. */ + bool isUnexpectedEOF_:1; + + public: + ParserBase(ExclusiveContext* cx, LifoAlloc& alloc, const ReadOnlyCompileOptions& options, + const char16_t* chars, size_t length, bool foldConstants, + UsedNameTracker& usedNames, Parser* syntaxParser, + LazyScript* lazyOuterFunction); + ~ParserBase(); + + const char* getFilename() const { return tokenStream.getFilename(); } + JSVersion versionNumber() const { return tokenStream.versionNumber(); } + TokenPos pos() const { return tokenStream.currentToken().pos; } + + // Determine whether |yield| is a valid name in the current context, or + // whether it's prohibited due to strictness, JS version, or occurrence + // inside a star generator. + bool yieldExpressionsSupported() { + return (versionNumber() >= JSVERSION_1_7 || pc->isGenerator()) && !pc->isAsync(); + } + + virtual bool strictMode() { return pc->sc()->strict(); } + bool setLocalStrictMode(bool strict) { + MOZ_ASSERT(tokenStream.debugHasNoLookahead()); + return pc->sc()->setLocalStrictMode(strict); + } + + const ReadOnlyCompileOptions& options() const { + return tokenStream.options(); + } + + bool hadAbortedSyntaxParse() { + return abortedSyntaxParse; + } + void clearAbortedSyntaxParse() { + abortedSyntaxParse = false; + } + + bool isUnexpectedEOF() const { return isUnexpectedEOF_; } + + bool reportNoOffset(ParseReportKind kind, bool strict, unsigned errorNumber, ...); + + /* Report the given error at the current offset. */ + void error(unsigned errorNumber, ...); + + /* Report the given error at the given offset. */ + void errorAt(uint32_t offset, unsigned errorNumber, ...); + + /* + * Handle a strict mode error at the current offset. Report an error if in + * strict mode code, or warn if not, using the given error number and + * arguments. + */ + MOZ_MUST_USE bool strictModeError(unsigned errorNumber, ...); + + /* + * Handle a strict mode error at the given offset. Report an error if in + * strict mode code, or warn if not, using the given error number and + * arguments. + */ + MOZ_MUST_USE bool strictModeErrorAt(uint32_t offset, unsigned errorNumber, ...); + + /* Report the given warning at the current offset. */ + MOZ_MUST_USE bool warning(unsigned errorNumber, ...); + + /* Report the given warning at the given offset. */ + MOZ_MUST_USE bool warningAt(uint32_t offset, unsigned errorNumber, ...); + + /* + * If extra warnings are enabled, report the given warning at the current + * offset. + */ + MOZ_MUST_USE bool extraWarning(unsigned errorNumber, ...); + + bool isValidStrictBinding(PropertyName* name); + + void addTelemetry(JSCompartment::DeprecatedLanguageExtension e); + + bool warnOnceAboutExprClosure(); + bool warnOnceAboutForEach(); + + protected: + enum InvokedPrediction { PredictUninvoked = false, PredictInvoked = true }; + enum ForInitLocation { InForInit, NotInForInit }; +}; + template -class Parser final : private JS::AutoGCRooter, public StrictModeGetter +class Parser final : public ParserBase, private JS::AutoGCRooter { private: using Node = typename ParseHandler::Node; @@ -852,50 +984,6 @@ class Parser final : private JS::AutoGCRooter, public StrictModeGetter void transferErrorsTo(PossibleError* other); }; - public: - ExclusiveContext* const context; - - LifoAlloc& alloc; - - TokenStream tokenStream; - LifoAlloc::Mark tempPoolMark; - - /* list of parsed objects for GC tracing */ - ObjectBox* traceListHead; - - /* innermost parse context (stack-allocated) */ - ParseContext* pc; - - // For tracking used names in this parsing session. - UsedNameTracker& usedNames; - - /* Compression token for aborting. */ - SourceCompressionTask* sct; - - ScriptSource* ss; - - /* Root atoms and objects allocated for the parsed tree. */ - AutoKeepAtoms keepAtoms; - - /* Perform constant-folding; must be true when interfacing with the emitter. */ - const bool foldConstants:1; - - private: -#if DEBUG - /* Our fallible 'checkOptions' member function has been called. */ - bool checkOptionsCalled:1; -#endif - - /* - * Not all language constructs can be handled during syntax parsing. If it - * is not known whether the parse succeeds or fails, this bit is set and - * the parse will return false. - */ - bool abortedSyntaxParse:1; - - /* Unexpected end of input, i.e. TOK_EOF not at top-level. */ - bool isUnexpectedEOF_:1; - public: /* State specific to the kind of parse being performed. */ ParseHandler handler; @@ -904,40 +992,6 @@ class Parser final : private JS::AutoGCRooter, public StrictModeGetter void freeTree(Node node) { handler.freeTree(node); } public: - bool reportNoOffset(ParseReportKind kind, bool strict, unsigned errorNumber, ...); - - /* Report the given error at the current offset. */ - void error(unsigned errorNumber, ...); - - /* Report the given error at the given offset. */ - void errorAt(uint32_t offset, unsigned errorNumber, ...); - - /* - * Handle a strict mode error at the current offset. Report an error if in - * strict mode code, or warn if not, using the given error number and - * arguments. - */ - MOZ_MUST_USE bool strictModeError(unsigned errorNumber, ...); - - /* - * Handle a strict mode error at the given offset. Report an error if in - * strict mode code, or warn if not, using the given error number and - * arguments. - */ - MOZ_MUST_USE bool strictModeErrorAt(uint32_t offset, unsigned errorNumber, ...); - - /* Report the given warning at the current offset. */ - MOZ_MUST_USE bool warning(unsigned errorNumber, ...); - - /* Report the given warning at the given offset. */ - MOZ_MUST_USE bool warningAt(uint32_t offset, unsigned errorNumber, ...); - - /* - * If extra warnings are enabled, report the given warning at the current - * offset. - */ - MOZ_MUST_USE bool extraWarning(unsigned errorNumber, ...); - Parser(ExclusiveContext* cx, LifoAlloc& alloc, const ReadOnlyCompileOptions& options, const char16_t* chars, size_t length, bool foldConstants, UsedNameTracker& usedNames, Parser* syntaxParser, LazyScript* lazyOuterFunction); @@ -967,9 +1021,6 @@ class Parser final : private JS::AutoGCRooter, public StrictModeGetter friend void js::frontend::TraceParser(JSTracer* trc, JS::AutoGCRooter* parser); - const char* getFilename() const { return tokenStream.getFilename(); } - JSVersion versionNumber() const { return tokenStream.versionNumber(); } - /* * Parse a top-level JS script. */ @@ -994,15 +1045,6 @@ class Parser final : private JS::AutoGCRooter, public StrictModeGetter void trace(JSTracer* trc); - bool hadAbortedSyntaxParse() { - return abortedSyntaxParse; - } - void clearAbortedSyntaxParse() { - abortedSyntaxParse = false; - } - - bool isUnexpectedEOF() const { return isUnexpectedEOF_; } - bool checkUnescapedName(); private: @@ -1071,32 +1113,11 @@ class Parser final : private JS::AutoGCRooter, public StrictModeGetter mozilla::Maybe parameterListEnd = mozilla::Nothing(), bool isStandaloneFunction = false); - // Determine whether |yield| is a valid name in the current context, or - // whether it's prohibited due to strictness, JS version, or occurrence - // inside a star generator. - bool yieldExpressionsSupported() { - return (versionNumber() >= JSVERSION_1_7 || pc->isGenerator()) && !pc->isAsync(); - } - // Match the current token against the BindingIdentifier production with // the given Yield parameter. If there is no match, report a syntax // error. PropertyName* bindingIdentifier(YieldHandling yieldHandling); - virtual bool strictMode() { return pc->sc()->strict(); } - bool setLocalStrictMode(bool strict) { - MOZ_ASSERT(tokenStream.debugHasNoLookahead()); - return pc->sc()->setLocalStrictMode(strict); - } - - const ReadOnlyCompileOptions& options() const { - return tokenStream.options(); - } - - private: - enum InvokedPrediction { PredictUninvoked = false, PredictInvoked = true }; - enum ForInitLocation { InForInit, NotInForInit }; - private: /* * JS parsers, from lowest to highest precedence. @@ -1368,8 +1389,6 @@ class Parser final : private JS::AutoGCRooter, public StrictModeGetter bool hasValidSimpleStrictParameterNames(); - bool isValidStrictBinding(PropertyName* name); - void reportRedeclaration(HandlePropertyName name, DeclarationKind kind, TokenPos pos); bool notePositionalFormalParameter(Node fn, HandlePropertyName name, bool disallowDuplicateParams, bool* duplicatedParam); @@ -1425,14 +1444,7 @@ class Parser final : private JS::AutoGCRooter, public StrictModeGetter JSAtom* prefixAccessorName(PropertyType propType, HandleAtom propAtom); - TokenPos pos() const { return tokenStream.currentToken().pos; } - bool asmJS(Node list); - - void addTelemetry(JSCompartment::DeprecatedLanguageExtension e); - - bool warnOnceAboutExprClosure(); - bool warnOnceAboutForEach(); }; } /* namespace frontend */ From d8c066294a88d025a4a42f5f01572a9392e95f5f Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Wed, 28 Dec 2016 15:15:01 -0600 Subject: [PATCH 071/229] Bug 1325674 - Update variable names in InitializeNumberFormat to latest spec, for readability. r=anba --HG-- extra : rebase_source : 5d5ffb813dc385aa464bfbde5332fb2143bfa521 --- js/src/builtin/Intl.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/js/src/builtin/Intl.js b/js/src/builtin/Intl.js index 478547808989..e6aae2194a5c 100644 --- a/js/src/builtin/Intl.js +++ b/js/src/builtin/Intl.js @@ -1786,11 +1786,11 @@ function resolveNumberFormatInternals(lazyNumberFormatData) { // Compute formatting options. // Step 15. - var s = lazyNumberFormatData.style; - internalProps.style = s; + var style = lazyNumberFormatData.style; + internalProps.style = style; // Steps 19, 21. - if (s === "currency") { + if (style === "currency") { internalProps.currency = lazyNumberFormatData.currency; internalProps.currencyDisplay = lazyNumberFormatData.currencyDisplay; } @@ -1954,15 +1954,15 @@ function InitializeNumberFormat(numberFormat, locales, options) { // Compute formatting options. // Step 14. - var s = GetOption(options, "style", "string", ["decimal", "percent", "currency"], "decimal"); - lazyNumberFormatData.style = s; + var style = GetOption(options, "style", "string", ["decimal", "percent", "currency"], "decimal"); + lazyNumberFormatData.style = style; // Steps 16-19. var c = GetOption(options, "currency", "string", undefined, undefined); if (c !== undefined && !IsWellFormedCurrencyCode(c)) ThrowRangeError(JSMSG_INVALID_CURRENCY_CODE, c); var cDigits; - if (s === "currency") { + if (style === "currency") { if (c === undefined) ThrowTypeError(JSMSG_UNDEFINED_CURRENCY); @@ -1974,17 +1974,17 @@ function InitializeNumberFormat(numberFormat, locales, options) { // Step 20. var cd = GetOption(options, "currencyDisplay", "string", ["code", "symbol", "name"], "symbol"); - if (s === "currency") + if (style === "currency") lazyNumberFormatData.currencyDisplay = cd; // Steps 22-24. - SetNumberFormatDigitOptions(lazyNumberFormatData, options, s === "currency" ? cDigits: 0); + SetNumberFormatDigitOptions(lazyNumberFormatData, options, style === "currency" ? cDigits: 0); // Step 25. if (lazyNumberFormatData.maximumFractionDigits === undefined) { - let mxfdDefault = s === "currency" + let mxfdDefault = style === "currency" ? cDigits - : s === "percent" + : style === "percent" ? 0 : 3; lazyNumberFormatData.maximumFractionDigits = From 6532b37f815a1785cac685fad0b4543cb04894ef Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Wed, 28 Dec 2016 15:15:48 -0600 Subject: [PATCH 072/229] Bug 1325675 - Abstract out MozIntl's add-these-functions-to-Intl behavior into a single function usable by all mozIntl functions. r=anba --HG-- extra : rebase_source : 86bb1fbd3ac2b8025ecced5feeb058cce7b31ed2 --- toolkit/components/mozintl/MozIntl.cpp | 37 ++++++++++---------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/toolkit/components/mozintl/MozIntl.cpp b/toolkit/components/mozintl/MozIntl.cpp index 1ab98fd2ad60..d89aa3b33955 100644 --- a/toolkit/components/mozintl/MozIntl.cpp +++ b/toolkit/components/mozintl/MozIntl.cpp @@ -18,8 +18,8 @@ MozIntl::MozIntl() = default; MozIntl::~MozIntl() = default; -NS_IMETHODIMP -MozIntl::AddGetCalendarInfo(JS::Handle val, JSContext* cx) +static nsresult +AddFunctions(JSContext* cx, JS::Handle val, const JSFunctionSpec* funcs) { if (!val.isObject()) { return NS_ERROR_INVALID_ARG; @@ -32,11 +32,6 @@ MozIntl::AddGetCalendarInfo(JS::Handle val, JSContext* cx) JSAutoCompartment ac(cx, realIntlObj); - static const JSFunctionSpec funcs[] = { - JS_SELF_HOSTED_FN("getCalendarInfo", "Intl_getCalendarInfo", 1, 0), - JS_FS_END - }; - if (!JS_DefineFunctions(cx, realIntlObj, funcs)) { return NS_ERROR_FAILURE; } @@ -44,30 +39,26 @@ MozIntl::AddGetCalendarInfo(JS::Handle val, JSContext* cx) return NS_OK; } +NS_IMETHODIMP +MozIntl::AddGetCalendarInfo(JS::Handle val, JSContext* cx) +{ + static const JSFunctionSpec funcs[] = { + JS_SELF_HOSTED_FN("getCalendarInfo", "Intl_getCalendarInfo", 1, 0), + JS_FS_END + }; + + return AddFunctions(cx, val, funcs); +} + NS_IMETHODIMP MozIntl::AddGetDisplayNames(JS::Handle val, JSContext* cx) { - if (!val.isObject()) { - return NS_ERROR_INVALID_ARG; - } - - JS::Rooted realIntlObj(cx, js::CheckedUnwrap(&val.toObject())); - if (!realIntlObj) { - return NS_ERROR_INVALID_ARG; - } - - JSAutoCompartment ac(cx, realIntlObj); - static const JSFunctionSpec funcs[] = { JS_SELF_HOSTED_FN("getDisplayNames", "Intl_getDisplayNames", 2, 0), JS_FS_END }; - if (!JS_DefineFunctions(cx, realIntlObj, funcs)) { - return NS_ERROR_FAILURE; - } - - return NS_OK; + return AddFunctions(cx, val, funcs); } NS_GENERIC_FACTORY_CONSTRUCTOR(MozIntl) From d090fc1e7ce7da95ead8fccfb7de41dd45a307c7 Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Wed, 28 Dec 2016 15:25:27 -0600 Subject: [PATCH 073/229] Bug 1325459 - Expose the PluralRules constructor only by explicit action,, for now. r=anba --HG-- extra : rebase_source : a14878e0281d3ab1302451e41e18e4b9d5b8f5cf --- js/src/builtin/Intl.cpp | 39 +++++++++++++++++-- js/src/builtin/Intl.h | 1 + js/src/jsfriendapi.h | 6 +++ js/src/shell/js.cpp | 7 +++- js/src/tests/Intl/PluralRules/pluralrules.js | 4 +- js/src/tests/Intl/PluralRules/select.js | 4 +- .../Intl/PluralRules/supportedLocalesOf.js | 4 +- js/src/vm/GlobalObject.h | 1 + toolkit/components/mozintl/MozIntl.cpp | 21 ++++++++++ toolkit/components/mozintl/mozIMozIntl.idl | 7 ++++ 10 files changed, 86 insertions(+), 8 deletions(-) diff --git a/js/src/builtin/Intl.cpp b/js/src/builtin/Intl.cpp index 639d54049b42..42d1ea429260 100644 --- a/js/src/builtin/Intl.cpp +++ b/js/src/builtin/Intl.cpp @@ -20,6 +20,7 @@ #include "jsapi.h" #include "jsatom.h" #include "jscntxt.h" +#include "jsfriendapi.h" #include "jsobj.h" #include "jsstr.h" @@ -3706,6 +3707,9 @@ CreatePluralRulesPrototype(JSContext* cx, HandleObject Intl, HandlecreateBlankPrototype(cx, &PluralRulesClass)); if (!proto) return nullptr; + MOZ_ASSERT(proto->getReservedSlot(UPLURAL_RULES_SLOT).isUndefined(), + "improperly creating PluralRules more than once for a single " + "global?"); proto->setReservedSlot(UPLURAL_RULES_SLOT, PrivateValue(nullptr)); if (!LinkConstructorAndPrototype(cx, ctor, proto)) @@ -3734,6 +3738,37 @@ CreatePluralRulesPrototype(JSContext* cx, HandleObject Intl, Handle global = cx->global(); + + { + const HeapSlot& slot = global->getReservedSlotRef(PLURAL_RULES_PROTO); + if (!slot.isUndefined()) { + MOZ_ASSERT(slot.isObject()); + MOZ_ASSERT(slot.toObject().hasClass(&PluralRulesClass)); + JS_ReportErrorASCII(cx, + "the PluralRules constructor can't be added " + "multiple times in the same global"); + return false; + } + } + + JSObject* pluralRulesProto = CreatePluralRulesPrototype(cx, intl, global); + if (!pluralRulesProto) + return false; + + global->setReservedSlot(PLURAL_RULES_PROTO, ObjectValue(*pluralRulesProto)); + return true; +} + +bool +js::AddPluralRulesConstructor(JSContext* cx, JS::Handle intl) +{ + return GlobalObject::addPluralRulesConstructor(cx, intl); +} + bool js::intl_PluralRules_availableLocales(JSContext* cx, unsigned argc, Value* vp) { @@ -4430,9 +4465,6 @@ GlobalObject::initIntlObject(JSContext* cx, Handle global) RootedObject numberFormatProto(cx, CreateNumberFormatPrototype(cx, intl, global)); if (!numberFormatProto) return false; - RootedObject pluralRulesProto(cx, CreatePluralRulesPrototype(cx, intl, global)); - if (!pluralRulesProto) - return false; // The |Intl| object is fully set up now, so define the global property. RootedValue intlValue(cx, ObjectValue(*intl)); @@ -4454,7 +4486,6 @@ GlobalObject::initIntlObject(JSContext* cx, Handle global) global->setReservedSlot(COLLATOR_PROTO, ObjectValue(*collatorProto)); global->setReservedSlot(DATE_TIME_FORMAT_PROTO, ObjectValue(*dateTimeFormatProto)); global->setReservedSlot(NUMBER_FORMAT_PROTO, ObjectValue(*numberFormatProto)); - global->setReservedSlot(PLURAL_RULES_PROTO, ObjectValue(*pluralRulesProto)); // Also cache |Intl| to implement spec language that conditions behavior // based on values being equal to "the standard built-in |Intl| object". diff --git a/js/src/builtin/Intl.h b/js/src/builtin/Intl.h index a7fc61fa6277..f3e6db9ad960 100644 --- a/js/src/builtin/Intl.h +++ b/js/src/builtin/Intl.h @@ -496,6 +496,7 @@ UCharToChar16(const UChar* chars) { return reinterpret_cast(chars); } + #endif // ENABLE_INTL_API } // namespace js diff --git a/js/src/jsfriendapi.h b/js/src/jsfriendapi.h index a37312b0409d..31196f6e99f9 100644 --- a/js/src/jsfriendapi.h +++ b/js/src/jsfriendapi.h @@ -2907,6 +2907,12 @@ ToWindowIfWindowProxy(JSObject* obj); JS_FRIEND_API(bool) AllowGCBarriers(JSContext* cx); +// Create and add the Intl.PluralRules constructor function to the provided +// object. This function throws if called more than once per realm/global +// object. +extern bool +AddPluralRulesConstructor(JSContext* cx, JS::Handle intl); + } /* namespace js */ class NativeProfiler diff --git a/js/src/shell/js.cpp b/js/src/shell/js.cpp index 48a9a5cedba8..f3ee32abedf7 100644 --- a/js/src/shell/js.cpp +++ b/js/src/shell/js.cpp @@ -50,6 +50,7 @@ #include "jsarray.h" #include "jsatom.h" #include "jscntxt.h" +#include "jsfriendapi.h" #include "jsfun.h" #include "jsobj.h" #include "jsprf.h" @@ -912,6 +913,9 @@ AddIntlExtras(JSContext* cx, unsigned argc, Value* vp) if (!JS_DefineFunctions(cx, intl, funcs)) return false; + if (!js::AddPluralRulesConstructor(cx, intl)) + return false; + args.rval().setUndefined(); return true; } @@ -6103,7 +6107,8 @@ static const JSFunctionSpecWithHelp shell_functions[] = { "provided object (this should generally be Intl itself). The added\n" "functions and their behavior are experimental: don't depend upon them\n" "unless you're willing to update your code if these experimental APIs change\n" -"underneath you."), +"underneath you. Calling this function more than once in a realm/global\n" +"will throw."), #endif // ENABLE_INTL_API JS_FS_HELP_END diff --git a/js/src/tests/Intl/PluralRules/pluralrules.js b/js/src/tests/Intl/PluralRules/pluralrules.js index 001ac42e105f..0ce2ce83d76e 100644 --- a/js/src/tests/Intl/PluralRules/pluralrules.js +++ b/js/src/tests/Intl/PluralRules/pluralrules.js @@ -1,4 +1,4 @@ -// |reftest| skip-if(!this.hasOwnProperty("Intl")) +// |reftest| skip-if(!this.hasOwnProperty("Intl")||!this.hasOwnProperty('addIntlExtras')) /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -7,6 +7,8 @@ var pr; +addIntlExtras(Intl); + pr = new Intl.PluralRules("en-us"); assertEq(pr.resolvedOptions().locale, "en-US"); assertEq(pr.resolvedOptions().type, "cardinal"); diff --git a/js/src/tests/Intl/PluralRules/select.js b/js/src/tests/Intl/PluralRules/select.js index f976cbd22bbf..e49ec89b94af 100644 --- a/js/src/tests/Intl/PluralRules/select.js +++ b/js/src/tests/Intl/PluralRules/select.js @@ -1,4 +1,4 @@ -// |reftest| skip-if(!this.hasOwnProperty("Intl")) +// |reftest| skip-if(!this.hasOwnProperty('Intl')||!this.hasOwnProperty('addIntlExtras')) /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -7,6 +7,8 @@ var pr; +addIntlExtras(Intl); + pr = new Intl.PluralRules("en-us"); assertEq(pr.select(0), "other"); assertEq(pr.select(0.5), "other"); diff --git a/js/src/tests/Intl/PluralRules/supportedLocalesOf.js b/js/src/tests/Intl/PluralRules/supportedLocalesOf.js index afc756636e4a..cd9064390050 100644 --- a/js/src/tests/Intl/PluralRules/supportedLocalesOf.js +++ b/js/src/tests/Intl/PluralRules/supportedLocalesOf.js @@ -1,4 +1,4 @@ -// |reftest| skip-if(!this.hasOwnProperty("Intl")||xulRuntime.shell) +// |reftest| skip-if(!this.hasOwnProperty('Intl')||!this.hasOwnProperty('addIntlExtras')||xulRuntime.shell) // -- test in browser only that ICU has locale data for all Mozilla languages /* This Source Code Form is subject to the terms of the Mozilla Public @@ -366,6 +366,8 @@ var locales = [ "zh-Hant-TW", ]; +addIntlExtras(Intl); + const result = Intl.PluralRules.supportedLocalesOf(locales); assertEqArray(locales, result); diff --git a/js/src/vm/GlobalObject.h b/js/src/vm/GlobalObject.h index ff4ec23fbb68..94e43e0bba5d 100644 --- a/js/src/vm/GlobalObject.h +++ b/js/src/vm/GlobalObject.h @@ -765,6 +765,7 @@ class GlobalObject : public NativeObject // Implemented in Intl.cpp. static bool initIntlObject(JSContext* cx, Handle global); + static bool addPluralRulesConstructor(JSContext* cx, HandleObject intl); // Implemented in builtin/ModuleObject.cpp static bool initModuleProto(JSContext* cx, Handle global); diff --git a/toolkit/components/mozintl/MozIntl.cpp b/toolkit/components/mozintl/MozIntl.cpp index d89aa3b33955..432db62b14ba 100644 --- a/toolkit/components/mozintl/MozIntl.cpp +++ b/toolkit/components/mozintl/MozIntl.cpp @@ -61,6 +61,27 @@ MozIntl::AddGetDisplayNames(JS::Handle val, JSContext* cx) return AddFunctions(cx, val, funcs); } +NS_IMETHODIMP +MozIntl::AddPluralRulesConstructor(JS::Handle val, JSContext* cx) +{ + if (!val.isObject()) { + return NS_ERROR_INVALID_ARG; + } + + JS::Rooted realIntlObj(cx, js::CheckedUnwrap(&val.toObject())); + if (!realIntlObj) { + return NS_ERROR_INVALID_ARG; + } + + JSAutoCompartment ac(cx, realIntlObj); + + if (!js::AddPluralRulesConstructor(cx, realIntlObj)) { + return NS_ERROR_FAILURE; + } + + return NS_OK; +} + NS_GENERIC_FACTORY_CONSTRUCTOR(MozIntl) NS_DEFINE_NAMED_CID(MOZ_MOZINTL_CID); diff --git a/toolkit/components/mozintl/mozIMozIntl.idl b/toolkit/components/mozintl/mozIMozIntl.idl index f28824d47bf3..e0d88e12a766 100644 --- a/toolkit/components/mozintl/mozIMozIntl.idl +++ b/toolkit/components/mozintl/mozIMozIntl.idl @@ -10,4 +10,11 @@ interface mozIMozIntl : nsISupports { [implicit_jscontext] void addGetCalendarInfo(in jsval intlObject); [implicit_jscontext] void addGetDisplayNames(in jsval intlObject); + + /** + * Adds a PluralRules constructor to the given object. This function may only + * be called once within a realm/global object: calling it multiple times will + * throw. + */ + [implicit_jscontext] void addPluralRulesConstructor(in jsval intlObject); }; From 1517b40e8244c2434d77900179bdffbb200b4027 Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Thu, 29 Dec 2016 18:30:59 -0600 Subject: [PATCH 074/229] Bug 1325675 - Followup bustage fix for a newly-landed test that needs an update along the same lines as the others this bug just touched. r=sparky --- js/src/tests/Intl/PluralRules/construct-newtarget.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/js/src/tests/Intl/PluralRules/construct-newtarget.js b/js/src/tests/Intl/PluralRules/construct-newtarget.js index 6f81075a819e..d0d2f7fb5e4a 100644 --- a/js/src/tests/Intl/PluralRules/construct-newtarget.js +++ b/js/src/tests/Intl/PluralRules/construct-newtarget.js @@ -1,9 +1,10 @@ -// |reftest| skip-if(!this.hasOwnProperty("Intl")) +// |reftest| skip-if(!this.hasOwnProperty("Intl")||!this.hasOwnProperty("addIntlExtras")) /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +addIntlExtras(Intl); // Test subclassing %Intl.PluralRules% works correctly. class MyPluralRules extends Intl.PluralRules {} From 60877b086dacb824d2cbdcd3eaf660fe038cd291 Mon Sep 17 00:00:00 2001 From: Neil Deakin Date: Thu, 29 Dec 2016 19:53:25 -0500 Subject: [PATCH 075/229] Bug 1272834, flush style after changing it to see if intermittent failure goes away --- browser/base/content/test/general/browser_selectpopup.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/browser/base/content/test/general/browser_selectpopup.js b/browser/base/content/test/general/browser_selectpopup.js index 4d816e5f3b4e..5b517a6f2d9d 100644 --- a/browser/base/content/test/general/browser_selectpopup.js +++ b/browser/base/content/test/general/browser_selectpopup.js @@ -301,6 +301,7 @@ add_task(function*() { }); elem.style = contentStep[1]; + elem.getBoundingClientRect(); }); }); @@ -463,6 +464,7 @@ function* performLargePopupTests(win) yield ContentTask.spawn(browser, position, function*(contentPosition) { let select = content.document.getElementById("one"); select.setAttribute("style", contentPosition); + select.getBoundingClientRect(); }); yield contentPainted; } From a3443d3548e91f2c605dd96471bff31339e644d8 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 18:10:22 -0800 Subject: [PATCH 076/229] Bug 1326163 part 1. The fieldset's border drawing display item shouldn't participate in hit-testing. That's handled by its background item already. r=dbaron --- layout/forms/nsFieldSetFrame.cpp | 12 ---------- .../tests/cssom-view/elementFromPoint.html | 22 +++++++++++++++++++ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/layout/forms/nsFieldSetFrame.cpp b/layout/forms/nsFieldSetFrame.cpp index 673cf565dbbe..b210bae64fa9 100644 --- a/layout/forms/nsFieldSetFrame.cpp +++ b/layout/forms/nsFieldSetFrame.cpp @@ -101,9 +101,6 @@ public: MOZ_COUNT_DTOR(nsDisplayFieldSetBorderBackground); } #endif - virtual void HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect, - HitTestState* aState, - nsTArray *aOutFrames) override; virtual void Paint(nsDisplayListBuilder* aBuilder, nsRenderingContext* aCtx) override; virtual nsDisplayItemGeometry* AllocateGeometry(nsDisplayListBuilder* aBuilder) override; @@ -114,15 +111,6 @@ public: NS_DISPLAY_DECL_NAME("FieldSetBorderBackground", TYPE_FIELDSET_BORDER_BACKGROUND) }; -void nsDisplayFieldSetBorderBackground::HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect, - HitTestState* aState, nsTArray *aOutFrames) -{ - // aPt is guaranteed to be in this item's bounds. We do the hit test based on the - // frame bounds even though our background doesn't cover the whole frame. - // It's not clear whether this is correct. - aOutFrames->AppendElement(mFrame); -} - void nsDisplayFieldSetBorderBackground::Paint(nsDisplayListBuilder* aBuilder, nsRenderingContext* aCtx) diff --git a/testing/web-platform/tests/cssom-view/elementFromPoint.html b/testing/web-platform/tests/cssom-view/elementFromPoint.html index 3ae4a9dbfe05..61d71e30fc22 100644 --- a/testing/web-platform/tests/cssom-view/elementFromPoint.html +++ b/testing/web-platform/tests/cssom-view/elementFromPoint.html @@ -52,6 +52,19 @@ area 1 area 2 area 3 + +
+
+
+
+ + +
+
From 6d33c26700168c11ed7d2602a12e32e6a2ca818f Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 18:10:24 -0800 Subject: [PATCH 077/229] Bug 1326163 part 2. Inherit a fieldset's border-radius down into its content wrapper box, so it doesn't leak out and mess up hit-testing in the corner areas when it has rounded borders. r=dbaron --- layout/style/res/forms.css | 3 +++ .../tests/cssom-view/elementFromPoint.html | 12 +++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/layout/style/res/forms.css b/layout/style/res/forms.css index 0e15ad258b47..7e87e165841a 100644 --- a/layout/style/res/forms.css +++ b/layout/style/res/forms.css @@ -16,6 +16,9 @@ text-overflow: inherit; overflow: inherit; overflow-clip-box: inherit; + /* Need to inherit border-radius too, so when the fieldset has rounded + borders we don't leak out the corners for hit-testing purposes. */ + border-radius: inherit; padding: inherit; block-size: 100%; /* Need this so percentage block-sizes of kids work right */ /* Please keep the Multicol/Flex/Grid/Align sections below in sync with diff --git a/testing/web-platform/tests/cssom-view/elementFromPoint.html b/testing/web-platform/tests/cssom-view/elementFromPoint.html index 61d71e30fc22..9df05d20b5ac 100644 --- a/testing/web-platform/tests/cssom-view/elementFromPoint.html +++ b/testing/web-platform/tests/cssom-view/elementFromPoint.html @@ -59,7 +59,9 @@
-
+
@@ -173,6 +175,14 @@ divRect.top + divRect.height/2), fieldsetDiv, "The fieldset should not cover up the div it doesn't even overlap"); + + var fieldset = document.getElementById("fieldset"); + var rect = fieldset.getBoundingClientRect(); + // A point 5px in from topleft will be outside the rounded border. + assert_not_equals(document.elementFromPoint(rect.left + 5, + rect.top + 5), + fieldset, + "The fieldset should not be hit by hit-tests outside its rounded border"); }, "Fieldsets"); done(); } From 4854d1dba1719c297f7859ec981f9095b2f0033e Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 29 Dec 2016 18:10:26 -0800 Subject: [PATCH 078/229] Bug 1326163 part 3. Rename nsDisplayFieldSetBorderBackground to nsDisplayFieldSetBorder, since that's what it does ever since bug 1227327 was fixed in . r=dbaron --- layout/forms/nsFieldSetFrame.cpp | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/layout/forms/nsFieldSetFrame.cpp b/layout/forms/nsFieldSetFrame.cpp index b210bae64fa9..8ae67b2a9f37 100644 --- a/layout/forms/nsFieldSetFrame.cpp +++ b/layout/forms/nsFieldSetFrame.cpp @@ -89,16 +89,16 @@ nsFieldSetFrame::GetLegend() const return mFrames.FirstChild(); } -class nsDisplayFieldSetBorderBackground : public nsDisplayItem { +class nsDisplayFieldSetBorder : public nsDisplayItem { public: - nsDisplayFieldSetBorderBackground(nsDisplayListBuilder* aBuilder, - nsFieldSetFrame* aFrame) + nsDisplayFieldSetBorder(nsDisplayListBuilder* aBuilder, + nsFieldSetFrame* aFrame) : nsDisplayItem(aBuilder, aFrame) { - MOZ_COUNT_CTOR(nsDisplayFieldSetBorderBackground); + MOZ_COUNT_CTOR(nsDisplayFieldSetBorder); } #ifdef NS_BUILD_REFCNT_LOGGING - virtual ~nsDisplayFieldSetBorderBackground() { - MOZ_COUNT_DTOR(nsDisplayFieldSetBorderBackground); + virtual ~nsDisplayFieldSetBorder() { + MOZ_COUNT_DTOR(nsDisplayFieldSetBorder); } #endif virtual void Paint(nsDisplayListBuilder* aBuilder, @@ -108,12 +108,12 @@ public: const nsDisplayItemGeometry* aGeometry, nsRegion *aInvalidRegion) override; virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) override; - NS_DISPLAY_DECL_NAME("FieldSetBorderBackground", TYPE_FIELDSET_BORDER_BACKGROUND) + NS_DISPLAY_DECL_NAME("FieldSetBorder", TYPE_FIELDSET_BORDER_BACKGROUND) }; void -nsDisplayFieldSetBorderBackground::Paint(nsDisplayListBuilder* aBuilder, - nsRenderingContext* aCtx) +nsDisplayFieldSetBorder::Paint(nsDisplayListBuilder* aBuilder, + nsRenderingContext* aCtx) { DrawResult result = static_cast(mFrame)-> PaintBorder(aBuilder, *aCtx, ToReferenceFrame(), mVisibleRect); @@ -122,15 +122,15 @@ nsDisplayFieldSetBorderBackground::Paint(nsDisplayListBuilder* aBuilder, } nsDisplayItemGeometry* -nsDisplayFieldSetBorderBackground::AllocateGeometry(nsDisplayListBuilder* aBuilder) +nsDisplayFieldSetBorder::AllocateGeometry(nsDisplayListBuilder* aBuilder) { return new nsDisplayItemGenericImageGeometry(this, aBuilder); } void -nsDisplayFieldSetBorderBackground::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder, - const nsDisplayItemGeometry* aGeometry, - nsRegion *aInvalidRegion) +nsDisplayFieldSetBorder::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder, + const nsDisplayItemGeometry* aGeometry, + nsRegion *aInvalidRegion) { auto geometry = static_cast(aGeometry); @@ -145,8 +145,8 @@ nsDisplayFieldSetBorderBackground::ComputeInvalidationRegion(nsDisplayListBuilde } nsRect -nsDisplayFieldSetBorderBackground::GetBounds(nsDisplayListBuilder* aBuilder, - bool* aSnap) +nsDisplayFieldSetBorder::GetBounds(nsDisplayListBuilder* aBuilder, + bool* aSnap) { // Just go ahead and claim our frame's overflow rect as the bounds, because we // may have border-image-outset or other features that cause borders to extend @@ -178,7 +178,7 @@ nsFieldSetFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder, /* aAllowWillPaintBorderOptimization = */ false); aLists.BorderBackground()->AppendNewToTop(new (aBuilder) - nsDisplayFieldSetBorderBackground(aBuilder, this)); + nsDisplayFieldSetBorder(aBuilder, this)); DisplayOutlineUnconditional(aBuilder, aLists); From 442fce9f66037aef28e5fb09645b10ad62fda960 Mon Sep 17 00:00:00 2001 From: Ehsan Akhgari Date: Thu, 29 Dec 2016 22:05:30 -0500 Subject: [PATCH 079/229] Fix a non-unified build bustage, no bug --- build/clang-plugin/CustomTypeAnnotation.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/build/clang-plugin/CustomTypeAnnotation.cpp b/build/clang-plugin/CustomTypeAnnotation.cpp index 4dbed3d0202f..b61538ecc346 100644 --- a/build/clang-plugin/CustomTypeAnnotation.cpp +++ b/build/clang-plugin/CustomTypeAnnotation.cpp @@ -3,6 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "CustomTypeAnnotation.h" +#include "Utils.h" CustomTypeAnnotation StackClass = CustomTypeAnnotation("moz_stack_class", "stack"); From 4f082e21275853dff137e8e179c9f20288970be6 Mon Sep 17 00:00:00 2001 From: Ryan VanderMeulen Date: Thu, 29 Dec 2016 22:08:13 -0500 Subject: [PATCH 080/229] Bug 1326340 - Update pdf.js to version 1.6.418. r=bdahl --HG-- extra : rebase_source : 442aca0851069570ac0b8de6fca30f6a5db5a373 --- browser/extensions/pdfjs/README.mozilla | 2 +- browser/extensions/pdfjs/content/PdfJs.jsm | 1 - .../pdfjs/content/PdfJsTelemetry.jsm | 2 +- .../pdfjs/content/PdfStreamConverter.jsm | 1 - .../pdfjs/content/PdfjsChromeUtils.jsm | 1 - .../pdfjs/content/PdfjsContentUtils.jsm | 1 - browser/extensions/pdfjs/content/build/pdf.js | 52 +++++++++- .../pdfjs/content/build/pdf.worker.js | 94 ++++++++++++++++--- .../pdfjs/content/pdfjschildbootstrap.js | 1 - browser/extensions/pdfjs/content/web/l10n.js | 1 - .../extensions/pdfjs/content/web/viewer.css | 18 +++- .../extensions/pdfjs/content/web/viewer.js | 24 +++-- 12 files changed, 162 insertions(+), 36 deletions(-) diff --git a/browser/extensions/pdfjs/README.mozilla b/browser/extensions/pdfjs/README.mozilla index b849113a5a09..2e82c74f2c6a 100644 --- a/browser/extensions/pdfjs/README.mozilla +++ b/browser/extensions/pdfjs/README.mozilla @@ -1,3 +1,3 @@ This is the pdf.js project output, https://github.com/mozilla/pdf.js -Current extension version is: 1.6.401 +Current extension version is: 1.6.418 diff --git a/browser/extensions/pdfjs/content/PdfJs.jsm b/browser/extensions/pdfjs/content/PdfJs.jsm index c25804cdec48..d67a6c5f8486 100644 --- a/browser/extensions/pdfjs/content/PdfJs.jsm +++ b/browser/extensions/pdfjs/content/PdfJs.jsm @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils, PdfjsChromeUtils, PdfjsContentUtils, PdfStreamConverter */ diff --git a/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm b/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm index 275da9d87b31..0d34cd50e67c 100644 --- a/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm +++ b/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true, maxlen: 100 */ +/* eslint max-len: ["error", 100] */ /* globals Components, Services */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/PdfStreamConverter.jsm b/browser/extensions/pdfjs/content/PdfStreamConverter.jsm index 3b9f9de26788..128d8aad2ab0 100644 --- a/browser/extensions/pdfjs/content/PdfStreamConverter.jsm +++ b/browser/extensions/pdfjs/content/PdfStreamConverter.jsm @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils, NetUtil, PrivateBrowsingUtils, dump, NetworkManager, PdfJsTelemetry, PdfjsContentUtils */ diff --git a/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm b/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm index 57f07af92ccd..2d97206f967e 100644 --- a/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm +++ b/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm b/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm index 3dec5f38902d..4318fbfdf96e 100644 --- a/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm +++ b/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/build/pdf.js b/browser/extensions/pdfjs/content/build/pdf.js index d5b17e9b3359..3183afb10e30 100644 --- a/browser/extensions/pdfjs/content/build/pdf.js +++ b/browser/extensions/pdfjs/content/build/pdf.js @@ -23,8 +23,8 @@ } }(this, function (exports) { 'use strict'; - var pdfjsVersion = '1.6.401'; - var pdfjsBuild = 'b629be05'; + var pdfjsVersion = '1.6.418'; + var pdfjsBuild = '59afb4b9'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { @@ -1808,6 +1808,15 @@ switch (fieldType) { case 'Tx': return new TextWidgetAnnotationElement(parameters); + case 'Btn': + if (parameters.data.radioButton) { + return new RadioButtonWidgetAnnotationElement(parameters); + } else if (parameters.data.checkBox) { + return new CheckboxWidgetAnnotationElement(parameters); + } else { + warn('Unimplemented button widget annotation: pushbutton'); + } + break; case 'Ch': return new ChoiceWidgetAnnotationElement(parameters); } @@ -2075,6 +2084,45 @@ }); return TextWidgetAnnotationElement; }(); + var CheckboxWidgetAnnotationElement = function CheckboxWidgetAnnotationElementClosure() { + function CheckboxWidgetAnnotationElement(parameters) { + WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); + } + Util.inherit(CheckboxWidgetAnnotationElement, WidgetAnnotationElement, { + render: function CheckboxWidgetAnnotationElement_render() { + this.container.className = 'buttonWidgetAnnotation checkBox'; + var element = document.createElement('input'); + element.disabled = this.data.readOnly; + element.type = 'checkbox'; + if (this.data.fieldValue && this.data.fieldValue !== 'Off') { + element.setAttribute('checked', true); + } + this.container.appendChild(element); + return this.container; + } + }); + return CheckboxWidgetAnnotationElement; + }(); + var RadioButtonWidgetAnnotationElement = function RadioButtonWidgetAnnotationElementClosure() { + function RadioButtonWidgetAnnotationElement(parameters) { + WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); + } + Util.inherit(RadioButtonWidgetAnnotationElement, WidgetAnnotationElement, { + render: function RadioButtonWidgetAnnotationElement_render() { + this.container.className = 'buttonWidgetAnnotation radioButton'; + var element = document.createElement('input'); + element.disabled = this.data.readOnly; + element.type = 'radio'; + element.name = this.data.fieldName; + if (this.data.fieldValue === this.data.buttonValue) { + element.setAttribute('checked', true); + } + this.container.appendChild(element); + return this.container; + } + }); + return RadioButtonWidgetAnnotationElement; + }(); var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() { function ChoiceWidgetAnnotationElement(parameters) { WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); diff --git a/browser/extensions/pdfjs/content/build/pdf.worker.js b/browser/extensions/pdfjs/content/build/pdf.worker.js index 14746010d357..53587e11b279 100644 --- a/browser/extensions/pdfjs/content/build/pdf.worker.js +++ b/browser/extensions/pdfjs/content/build/pdf.worker.js @@ -23,8 +23,8 @@ } }(this, function (exports) { 'use strict'; - var pdfjsVersion = '1.6.401'; - var pdfjsBuild = 'b629be05'; + var pdfjsVersion = '1.6.418'; + var pdfjsBuild = '59afb4b9'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { @@ -45245,10 +45245,10 @@ } if (!font.vertical) { textChunk.lastAdvanceWidth = width; - textChunk.width += width * textChunk.textAdvanceScale; + textChunk.width += width; } else { textChunk.lastAdvanceHeight = height; - textChunk.height += Math.abs(height * textChunk.textAdvanceScale); + textChunk.height += Math.abs(height); } return textChunk; } @@ -45269,6 +45269,8 @@ if (!textContentItem.initialized) { return; } + textContentItem.width *= textContentItem.textAdvanceScale; + textContentItem.height *= textContentItem.textAdvanceScale; textContent.items.push(runBidiTransform(textContentItem)); textContentItem.initialized = false; textContentItem.str.length = 0; @@ -45381,16 +45383,16 @@ advance = items[j] * textState.fontSize / 1000; var breakTextRun = false; if (textState.font.vertical) { - offset = advance * (textState.textHScale * textState.textMatrix[2] + textState.textMatrix[3]); - textState.translateTextMatrix(0, advance); + offset = advance; + textState.translateTextMatrix(0, offset); breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax; if (!breakTextRun) { textContentItem.height += offset; } } else { advance = -advance; - offset = advance * (textState.textHScale * textState.textMatrix[0] + textState.textMatrix[1]); - textState.translateTextMatrix(advance, 0); + offset = advance * textState.textHScale; + textState.translateTextMatrix(offset, 0); breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax; if (!breakTextRun) { textContentItem.width += offset; @@ -45884,7 +45886,16 @@ } else if (isRef(entry)) { hash.update(entry.toString()); } else if (isArray(entry)) { - hash.update(entry.length.toString()); + var diffLength = entry.length, diffBuf = new Array(diffLength); + for (var j = 0; j < diffLength; j++) { + var diffEntry = entry[j]; + if (isName(diffEntry)) { + diffBuf[j] = diffEntry.name; + } else if (isNum(diffEntry) || isRef(diffEntry)) { + diffBuf[j] = diffEntry.toString(); + } + } + hash.update(diffBuf.join()); } } } @@ -47160,6 +47171,8 @@ switch (fieldType) { case 'Tx': return new TextWidgetAnnotation(parameters); + case 'Btn': + return new ButtonWidgetAnnotation(parameters); case 'Ch': return new ChoiceWidgetAnnotation(parameters); } @@ -47587,17 +47600,72 @@ }); return TextWidgetAnnotation; }(); + var ButtonWidgetAnnotation = function ButtonWidgetAnnotationClosure() { + function ButtonWidgetAnnotation(params) { + WidgetAnnotation.call(this, params); + this.data.checkBox = !this.hasFieldFlag(AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); + if (this.data.checkBox) { + if (!isName(this.data.fieldValue)) { + return; + } + this.data.fieldValue = this.data.fieldValue.name; + } + this.data.radioButton = this.hasFieldFlag(AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); + if (this.data.radioButton) { + this.data.fieldValue = this.data.buttonValue = null; + var fieldParent = params.dict.get('Parent'); + if (!isDict(fieldParent) || !fieldParent.has('V')) { + return; + } + var fieldParentValue = fieldParent.get('V'); + if (!isName(fieldParentValue)) { + return; + } + this.data.fieldValue = fieldParentValue.name; + var appearanceStates = params.dict.get('AP'); + if (!isDict(appearanceStates)) { + return; + } + var normalAppearanceState = appearanceStates.get('N'); + if (!isDict(normalAppearanceState)) { + return; + } + var keys = normalAppearanceState.getKeys(); + for (var i = 0, ii = keys.length; i < ii; i++) { + if (keys[i] !== 'Off') { + this.data.buttonValue = keys[i]; + break; + } + } + } + } + Util.inherit(ButtonWidgetAnnotation, WidgetAnnotation, { + getOperatorList: function ButtonWidgetAnnotation_getOperatorList(evaluator, task, renderForms) { + var operatorList = new OperatorList(); + if (renderForms) { + return Promise.resolve(operatorList); + } + if (this.appearance) { + return Annotation.prototype.getOperatorList.call(this, evaluator, task, renderForms); + } + return Promise.resolve(operatorList); + } + }); + return ButtonWidgetAnnotation; + }(); var ChoiceWidgetAnnotation = function ChoiceWidgetAnnotationClosure() { function ChoiceWidgetAnnotation(params) { WidgetAnnotation.call(this, params); this.data.options = []; - var options = params.dict.getArray('Opt'); + var options = params.dict.get('Opt'); if (isArray(options)) { + var xref = params.xref; for (var i = 0, ii = options.length; i < ii; i++) { - var option = options[i]; + var option = xref.fetchIfRef(options[i]); + var isOptionArray = isArray(option); this.data.options[i] = { - exportValue: isArray(option) ? option[0] : option, - displayValue: isArray(option) ? option[1] : option + exportValue: isOptionArray ? xref.fetchIfRef(option[0]) : option, + displayValue: isOptionArray ? xref.fetchIfRef(option[1]) : option }; } } diff --git a/browser/extensions/pdfjs/content/pdfjschildbootstrap.js b/browser/extensions/pdfjs/content/pdfjschildbootstrap.js index 1f44b9c2e8d8..2051e3055d56 100644 --- a/browser/extensions/pdfjs/content/pdfjschildbootstrap.js +++ b/browser/extensions/pdfjs/content/pdfjschildbootstrap.js @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, PdfjsContentUtils, PdfJs, Services */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/web/l10n.js b/browser/extensions/pdfjs/content/web/l10n.js index 04346ee1d650..e45cf200a5b9 100644 --- a/browser/extensions/pdfjs/content/web/l10n.js +++ b/browser/extensions/pdfjs/content/web/l10n.js @@ -1,4 +1,3 @@ - 'use strict'; // Small subset of the webL10n API by Fabien Cazenave for pdf.js extension. diff --git a/browser/extensions/pdfjs/content/web/viewer.css b/browser/extensions/pdfjs/content/web/viewer.css index cafa90738577..158842ac69fe 100644 --- a/browser/extensions/pdfjs/content/web/viewer.css +++ b/browser/extensions/pdfjs/content/web/viewer.css @@ -103,7 +103,9 @@ .annotationLayer .textWidgetAnnotation input, .annotationLayer .textWidgetAnnotation textarea, -.annotationLayer .choiceWidgetAnnotation select { +.annotationLayer .choiceWidgetAnnotation select, +.annotationLayer .buttonWidgetAnnotation.checkBox input, +.annotationLayer .buttonWidgetAnnotation.radioButton input { background-color: rgba(0, 54, 255, 0.13); border: 1px solid transparent; box-sizing: border-box; @@ -122,7 +124,9 @@ .annotationLayer .textWidgetAnnotation input[disabled], .annotationLayer .textWidgetAnnotation textarea[disabled], -.annotationLayer .choiceWidgetAnnotation select[disabled] { +.annotationLayer .choiceWidgetAnnotation select[disabled], +.annotationLayer .buttonWidgetAnnotation.checkBox input[disabled], +.annotationLayer .buttonWidgetAnnotation.radioButton input[disabled] { background: none; border: 1px solid transparent; cursor: not-allowed; @@ -130,7 +134,9 @@ .annotationLayer .textWidgetAnnotation input:hover, .annotationLayer .textWidgetAnnotation textarea:hover, -.annotationLayer .choiceWidgetAnnotation select:hover { +.annotationLayer .choiceWidgetAnnotation select:hover, +.annotationLayer .buttonWidgetAnnotation.checkBox input:hover, +.annotationLayer .buttonWidgetAnnotation.radioButton input:hover { border: 1px solid #000; } @@ -157,6 +163,12 @@ width: 115%; } +.annotationLayer .buttonWidgetAnnotation.checkBox input, +.annotationLayer .buttonWidgetAnnotation.radioButton input { + -moz-appearance: none; + appearance: none; +} + .annotationLayer .popupWrapper { position: absolute; width: 20em; diff --git a/browser/extensions/pdfjs/content/web/viewer.js b/browser/extensions/pdfjs/content/web/viewer.js index f853da16b7b9..1ee979322a8a 100644 --- a/browser/extensions/pdfjs/content/web/viewer.js +++ b/browser/extensions/pdfjs/content/web/viewer.js @@ -4119,7 +4119,7 @@ var pdfjsWebLibs; } if (error === 'cancelled') { self.error = null; - return; + return Promise.resolve(undefined); } self.renderingState = RenderingStates.FINISHED; if (self.loadingIconDiv) { @@ -4145,21 +4145,25 @@ var pdfjsWebLibs; pageNumber: self.id, cssTransform: false }); + if (error) { + return Promise.reject(error); + } + return Promise.resolve(undefined); }; var paintTask = this.renderer === RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper); paintTask.onRenderContinue = renderContinueCallback; this.paintTask = paintTask; var resultPromise = paintTask.promise.then(function () { - finishPaintTask(null); - if (textLayer) { - pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) { - textLayer.setTextContent(textContent); - textLayer.render(TEXT_LAYER_RENDER_DELAY); - }); - } + return finishPaintTask(null).then(function () { + if (textLayer) { + pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) { + textLayer.setTextContent(textContent); + textLayer.render(TEXT_LAYER_RENDER_DELAY); + }); + } + }); }, function (reason) { - finishPaintTask(reason); - throw reason; + return finishPaintTask(reason); }); if (this.annotationLayerFactory) { if (!this.annotationLayer) { From 7e29e33ae31fd9aa9cd62f4a32270f0f3b7c6574 Mon Sep 17 00:00:00 2001 From: Jeff Walden Date: Tue, 6 Dec 2016 17:21:05 -1000 Subject: [PATCH 081/229] Bug 1285833 - Update code comments to latest spec steps. r=sfink --- js/src/vm/TypedArrayObject.cpp | 38 +++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/js/src/vm/TypedArrayObject.cpp b/js/src/vm/TypedArrayObject.cpp index ebb61c1e59d9..29db529dc555 100644 --- a/js/src/vm/TypedArrayObject.cpp +++ b/js/src/vm/TypedArrayObject.cpp @@ -3004,36 +3004,50 @@ js::DefineTypedArrayElement(JSContext* cx, HandleObject obj, uint64_t index, { MOZ_ASSERT(obj->is()); - // These are all substeps of 3.c. - // Steps i-vi. + // These are all substeps of 3.b. + + // Steps i-iii are handled by the caller. + + // Steps iv-v. // We (wrongly) ignore out of range defines with a value. - if (index >= obj->as().length()) + uint32_t length = obj->as().length(); + if (index >= length) return result.succeed(); - // Step vii. + // Step vi. if (desc.isAccessorDescriptor()) return result.fail(JSMSG_CANT_REDEFINE_PROP); - // Step viii. + // Step vii. if (desc.hasConfigurable() && desc.configurable()) return result.fail(JSMSG_CANT_REDEFINE_PROP); - // Step ix. + // Step viii. if (desc.hasEnumerable() && !desc.enumerable()) return result.fail(JSMSG_CANT_REDEFINE_PROP); - // Step x. + // Step ix. if (desc.hasWritable() && !desc.writable()) return result.fail(JSMSG_CANT_REDEFINE_PROP); - // Step xi. + // Step x. if (desc.hasValue()) { - double d; - if (!ToNumber(cx, desc.value(), &d)) + // The following step numbers refer to 9.4.5.9 + // IntegerIndexedElementSet. + + // Steps 1-2 are enforced by the caller. + + // Step 3. + double numValue; + if (!ToNumber(cx, desc.value(), &numValue)) return false; - if (obj->is()) - TypedArrayObject::setElement(obj->as(), index, d); + // Steps 4-5, 8-9. + if (obj->as().hasDetachedBuffer()) + return result.fail(JSMSG_TYPED_ARRAY_DETACHED); + + // Steps 10-16. + TypedArrayObject::setElement(obj->as(), index, numValue); } // Step xii. From 9a301276cec489412857e723a2335fa7e51cc7c3 Mon Sep 17 00:00:00 2001 From: Henrik Skupin Date: Thu, 29 Dec 2016 20:02:57 +0100 Subject: [PATCH 082/229] Bug 1326236 - Use get_property() to retrieve the selectedIndex of decks and wizards. r=maja_zf Fix for a regression as introduced by bug 1277090. get_attribute() no longer returns values of Element properties. For the latter get_property() has to be used now. MozReview-Commit-ID: K45rcHDM6YC --HG-- extra : rebase_source : 8ca27167b364832a99c29eb9cf1f16181493d950 --- testing/firefox-ui/tests/puppeteer/test_about_window.py | 4 ++++ testing/firefox-ui/tests/puppeteer/test_update_wizard.py | 4 ++++ .../firefox/firefox_puppeteer/ui/about_window/deck.py | 2 +- .../firefox/firefox_puppeteer/ui/update_wizard/wizard.py | 2 +- 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/testing/firefox-ui/tests/puppeteer/test_about_window.py b/testing/firefox-ui/tests/puppeteer/test_about_window.py index c8cf2036d413..d37f3e1646a9 100644 --- a/testing/firefox-ui/tests/puppeteer/test_about_window.py +++ b/testing/firefox-ui/tests/puppeteer/test_about_window.py @@ -53,6 +53,10 @@ class TestAboutWindow(PuppeteerMixin, MarionetteTestCase): # downloading panel self.assertEqual(self.deck.downloading.element.get_property('localName'), 'hbox') + # check deck attributes + self.assertIsInstance(self.deck.selected_index, int) + self.assertEqual(self.deck.selected_panel, self.deck.check_for_updates) + def test_open_window(self): """Test various opening strategies.""" def opener(win): diff --git a/testing/firefox-ui/tests/puppeteer/test_update_wizard.py b/testing/firefox-ui/tests/puppeteer/test_update_wizard.py index af4f1c969c95..5cdb6291a2df 100644 --- a/testing/firefox-ui/tests/puppeteer/test_update_wizard.py +++ b/testing/firefox-ui/tests/puppeteer/test_update_wizard.py @@ -60,3 +60,7 @@ class TestUpdateWizard(PuppeteerMixin, MarionetteTestCase): # elements of the downloading panel self.assertEqual(self.wizard.downloading.progress.get_property('localName'), 'progressmeter') + + # check wizard attributes + self.assertIsInstance(self.wizard.selected_index, int) + self.assertEqual(self.wizard.selected_panel, self.wizard.checking) diff --git a/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/about_window/deck.py b/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/about_window/deck.py index 53c25355dad0..9d8d90603c13 100644 --- a/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/about_window/deck.py +++ b/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/about_window/deck.py @@ -114,7 +114,7 @@ class Deck(UIBaseLib): :return: Index of the selected panel. """ - return int(self.element.get_attribute('selectedIndex')) + return int(self.element.get_property('selectedIndex')) @property def selected_panel(self): diff --git a/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/update_wizard/wizard.py b/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/update_wizard/wizard.py index 95ac9cad9bfb..9687ac917812 100644 --- a/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/update_wizard/wizard.py +++ b/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/update_wizard/wizard.py @@ -207,7 +207,7 @@ class Wizard(UIBaseLib): :return: Index of the selected panel. """ - return int(self.element.get_attribute('pageIndex')) + return int(self.element.get_property('pageIndex')) @property def selected_panel(self): From 4ea759de85403834b1849f9b4952f2ff5cd702dc Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Thu, 29 Dec 2016 12:46:05 -0800 Subject: [PATCH 083/229] Backed out changeset 25505bf601f6 (bug 1326236) for test_update_wizard.py failures a=backout --- testing/firefox-ui/tests/puppeteer/test_about_window.py | 4 ---- testing/firefox-ui/tests/puppeteer/test_update_wizard.py | 4 ---- .../firefox/firefox_puppeteer/ui/about_window/deck.py | 2 +- .../firefox/firefox_puppeteer/ui/update_wizard/wizard.py | 2 +- 4 files changed, 2 insertions(+), 10 deletions(-) diff --git a/testing/firefox-ui/tests/puppeteer/test_about_window.py b/testing/firefox-ui/tests/puppeteer/test_about_window.py index d37f3e1646a9..c8cf2036d413 100644 --- a/testing/firefox-ui/tests/puppeteer/test_about_window.py +++ b/testing/firefox-ui/tests/puppeteer/test_about_window.py @@ -53,10 +53,6 @@ class TestAboutWindow(PuppeteerMixin, MarionetteTestCase): # downloading panel self.assertEqual(self.deck.downloading.element.get_property('localName'), 'hbox') - # check deck attributes - self.assertIsInstance(self.deck.selected_index, int) - self.assertEqual(self.deck.selected_panel, self.deck.check_for_updates) - def test_open_window(self): """Test various opening strategies.""" def opener(win): diff --git a/testing/firefox-ui/tests/puppeteer/test_update_wizard.py b/testing/firefox-ui/tests/puppeteer/test_update_wizard.py index 5cdb6291a2df..af4f1c969c95 100644 --- a/testing/firefox-ui/tests/puppeteer/test_update_wizard.py +++ b/testing/firefox-ui/tests/puppeteer/test_update_wizard.py @@ -60,7 +60,3 @@ class TestUpdateWizard(PuppeteerMixin, MarionetteTestCase): # elements of the downloading panel self.assertEqual(self.wizard.downloading.progress.get_property('localName'), 'progressmeter') - - # check wizard attributes - self.assertIsInstance(self.wizard.selected_index, int) - self.assertEqual(self.wizard.selected_panel, self.wizard.checking) diff --git a/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/about_window/deck.py b/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/about_window/deck.py index 9d8d90603c13..53c25355dad0 100644 --- a/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/about_window/deck.py +++ b/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/about_window/deck.py @@ -114,7 +114,7 @@ class Deck(UIBaseLib): :return: Index of the selected panel. """ - return int(self.element.get_property('selectedIndex')) + return int(self.element.get_attribute('selectedIndex')) @property def selected_panel(self): diff --git a/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/update_wizard/wizard.py b/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/update_wizard/wizard.py index 9687ac917812..95ac9cad9bfb 100644 --- a/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/update_wizard/wizard.py +++ b/testing/marionette/puppeteer/firefox/firefox_puppeteer/ui/update_wizard/wizard.py @@ -207,7 +207,7 @@ class Wizard(UIBaseLib): :return: Index of the selected panel. """ - return int(self.element.get_property('pageIndex')) + return int(self.element.get_attribute('pageIndex')) @property def selected_panel(self): From 4fead6b39ffdb21d2d88329978ea8046780dd6ce Mon Sep 17 00:00:00 2001 From: Henrik Skupin Date: Thu, 29 Dec 2016 14:04:16 +0100 Subject: [PATCH 084/229] Bug 1326174 - For unsupported commands in chrome context throw UnsupportedOperationError r=ato Commands which are not (yet) supported in chrome context have to throw an UnsupportedOperationError to indicate that they cannot be used instead of silently eating failures. MozReview-Commit-ID: 2eFYAfKaQpD --HG-- extra : rebase_source : cbf8ded1ad5ea0b0e902f74831416bc3b7921856 --- testing/marionette/assert.js | 28 +++- testing/marionette/driver.js | 135 ++++++++++-------- .../tests/unit/test_cookies.py | 12 ++ .../tests/unit/test_navigation.py | 8 +- .../tests/unit/test_shadow_dom.py | 8 +- 5 files changed, 127 insertions(+), 64 deletions(-) diff --git a/testing/marionette/assert.js b/testing/marionette/assert.js index 9705105466fb..b9bf6ae0eb76 100644 --- a/testing/marionette/assert.js +++ b/testing/marionette/assert.js @@ -8,6 +8,7 @@ const {classes: Cc, interfaces: Ci, utils: Cu} = Components; Cu.import("resource://gre/modules/AppConstants.jsm"); Cu.import("resource://gre/modules/Preferences.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); Cu.import("chrome://marionette/content/error.js"); @@ -30,7 +31,7 @@ this.assert = {}; * If current browser is not Firefox. */ assert.firefox = function (msg = "") { - msg = msg || "Expected Firefox"; + msg = msg || "Only supported in Firefox"; assert.that(isFirefox, msg, UnsupportedOperationError)(); }; @@ -44,7 +45,7 @@ assert.firefox = function (msg = "") { * If current browser is not Fennec. */ assert.fennec = function (msg = "") { - msg = msg || "Expected Fennec"; + msg = msg || "Only supported in Fennec"; assert.that(isFennec, msg, UnsupportedOperationError)(); }; @@ -58,10 +59,29 @@ assert.fennec = function (msg = "") { * If the current browser is not B2G. */ assert.b2g = function (msg = "") { - msg = msg || "Expected B2G" + msg = msg || "Only supported in B2G"; assert.that(isB2G, msg, UnsupportedOperationError)(); }; +/** + * Asserts that the current |context| is content. + * + * @param {string} context + * Context to test. + * @param {string=} msg + * Custom error message. + * + * @return {string} + * |context| is returned unaltered. + * + * @throws {UnsupportedOperationError} + * If |context| is not content. + */ +assert.content = function (context, msg = "") { + msg = msg || "Only supported in content context"; + assert.that(c => c.toString() == "content", msg, UnsupportedOperationError)(context); +} + /** * Asserts that the current browser is a mobile browser, that is either * B2G or Fennec. @@ -73,7 +93,7 @@ assert.b2g = function (msg = "") { * If the current browser is not B2G or Fennec. */ assert.mobile = function (msg = "") { - msg = msg || "Expected Fennec or B2G"; + msg = msg || "Only supported in Fennec or B2G"; assert.that(() => isFennec() || isB2G(), msg, UnsupportedOperationError)(); }; diff --git a/testing/marionette/driver.js b/testing/marionette/driver.js index 4db4ccb8e90f..b6341f642f0b 100644 --- a/testing/marionette/driver.js +++ b/testing/marionette/driver.js @@ -1015,32 +1015,26 @@ GeckoDriver.prototype.executeJSScript = function* (cmd, resp) { * URL to navigate to. */ GeckoDriver.prototype.get = function*(cmd, resp) { + assert.content(this.context); + let url = cmd.parameters.url; - switch (this.context) { - case Context.CONTENT: - let get = this.listener.get({url: url, pageTimeout: this.pageTimeout}); - // TODO(ato): Bug 1242595 - let id = this.listener.activeMessageId; + let get = this.listener.get({url: url, pageTimeout: this.pageTimeout}); + // TODO(ato): Bug 1242595 + let id = this.listener.activeMessageId; - // If a remoteness update interrupts our page load, this will never return - // We need to re-issue this request to correctly poll for readyState and - // send errors. - this.curBrowser.pendingCommands.push(() => { - cmd.parameters.command_id = id; - cmd.parameters.pageTimeout = this.pageTimeout; - this.mm.broadcastAsyncMessage( - "Marionette:pollForReadyState" + this.curBrowser.curFrameId, - cmd.parameters); - }); + // If a remoteness update interrupts our page load, this will never return + // We need to re-issue this request to correctly poll for readyState and + // send errors. + this.curBrowser.pendingCommands.push(() => { + cmd.parameters.command_id = id; + cmd.parameters.pageTimeout = this.pageTimeout; + this.mm.broadcastAsyncMessage( + "Marionette:pollForReadyState" + this.curBrowser.curFrameId, + cmd.parameters); + }); - yield get; - break; - - case Context.CHROME: - throw new UnsupportedOperationError("Cannot navigate in chrome context"); - break; - } + yield get; }; /** @@ -1101,16 +1095,22 @@ GeckoDriver.prototype.getPageSource = function* (cmd, resp) { /** Go back in history. */ GeckoDriver.prototype.goBack = function*(cmd, resp) { + assert.content(this.context); + yield this.listener.goBack(); }; /** Go forward in history. */ GeckoDriver.prototype.goForward = function*(cmd, resp) { + assert.content(this.context); + yield this.listener.goForward(); }; /** Refresh the page. */ GeckoDriver.prototype.refresh = function*(cmd, resp) { + assert.content(this.context); + yield this.listener.refresh(); }; @@ -1270,9 +1270,7 @@ GeckoDriver.prototype.getWindowPosition = function (cmd, resp) { * Object with |x| and |y| coordinates. */ GeckoDriver.prototype.setWindowPosition = function (cmd, resp) { - if (this.appName != "Firefox") { - throw new UnsupportedOperationError("Unable to set the window position on mobile"); - } + assert.firefox() let {x, y} = cmd.parameters; assert.positiveInteger(x); @@ -1618,7 +1616,8 @@ GeckoDriver.prototype.singleTap = function*(cmd, resp) { switch (this.context) { case Context.CHROME: - throw new WebDriverError("Command 'singleTap' is not available in chrome context"); + throw new UnsupportedOperationError( + "Command 'singleTap' is not yet available in chrome context"); case Context.CONTENT: this.addFrameCloseListener("tap"); @@ -1640,7 +1639,8 @@ GeckoDriver.prototype.performActions = function(cmd, resp) { switch (this.context) { case Context.CHROME: throw new UnsupportedOperationError( - "Command 'performActions' is not available in chrome context"); + "Command 'performActions' is not yet available in chrome context"); + case Context.CONTENT: return this.listener.performActions({"actions": cmd.parameters.actions}); } @@ -1650,7 +1650,14 @@ GeckoDriver.prototype.performActions = function(cmd, resp) { * Release all the keys and pointer buttons that are currently depressed. */ GeckoDriver.prototype.releaseActions = function(cmd, resp) { - return this.listener.releaseActions(); + switch (this.context) { + case Context.CHROME: + throw new UnsupportedOperationError( + "Command 'releaseActions' is not yet available in chrome context"); + + case Context.CONTENT: + return this.listener.releaseActions(); + } }; /** @@ -1668,12 +1675,9 @@ GeckoDriver.prototype.actionChain = function*(cmd, resp) { switch (this.context) { case Context.CHROME: - if (this.appName != "Firefox") { - // be conservative until this has a use case and is established - // to work as expected on b2g/fennec - throw new WebDriverError( - "Command 'actionChain' is not available in chrome context"); - } + // be conservative until this has a use case and is established + // to work as expected in Fennec + assert.firefox() let win = this.getCurrentWindow(); resp.body.value = yield this.legacyactions.dispatchActions( @@ -1698,7 +1702,8 @@ GeckoDriver.prototype.actionChain = function*(cmd, resp) { GeckoDriver.prototype.multiAction = function*(cmd, resp) { switch (this.context) { case Context.CHROME: - throw new WebDriverError("Command 'multiAction' is not available in chrome context"); + throw new UnsupportedOperationError( + "Command 'multiAction' is not yet available in chrome context"); case Context.CONTENT: this.addFrameCloseListener("multi action chain"); @@ -1795,7 +1800,15 @@ GeckoDriver.prototype.findElements = function*(cmd, resp) { /** Return the active element on the page. */ GeckoDriver.prototype.getActiveElement = function*(cmd, resp) { - resp.body.value = yield this.listener.getActiveElement(); + switch (this.context) { + case Context.CHROME: + throw new UnsupportedOperationError( + "Command 'getActiveElement' is not yet available in chrome context"); + + case Context.CONTENT: + resp.body.value = yield this.listener.getActiveElement(); + break; + } }; /** @@ -2112,6 +2125,8 @@ GeckoDriver.prototype.clearElement = function*(cmd, resp) { * @param {string} id element id. */ GeckoDriver.prototype.switchToShadowRoot = function*(cmd, resp) { + assert.content(this.context) + let id; if (cmd.parameters) { id = cmd.parameters.id; } yield this.listener.switchToShadowRoot(id); @@ -2119,6 +2134,8 @@ GeckoDriver.prototype.switchToShadowRoot = function*(cmd, resp) { /** Add a cookie to the document. */ GeckoDriver.prototype.addCookie = function*(cmd, resp) { + assert.content(this.context) + let cb = msg => { this.mm.removeMessageListener("Marionette:addCookie", cb); let cookie = msg.json; @@ -2134,6 +2151,7 @@ GeckoDriver.prototype.addCookie = function*(cmd, resp) { {}); // originAttributes return true; }; + this.mm.addMessageListener("Marionette:addCookie", cb); yield this.listener.addCookie(cmd.parameters.cookie); }; @@ -2145,11 +2163,15 @@ GeckoDriver.prototype.addCookie = function*(cmd, resp) { * the result. */ GeckoDriver.prototype.getCookies = function*(cmd, resp) { + assert.content(this.context) + resp.body = yield this.listener.getCookies(); }; /** Delete all cookies that are visible to a document. */ GeckoDriver.prototype.deleteAllCookies = function*(cmd, resp) { + assert.content(this.context) + let cb = msg => { let cookie = msg.json; cookieManager.remove( @@ -2160,6 +2182,7 @@ GeckoDriver.prototype.deleteAllCookies = function*(cmd, resp) { cookie.originAttributes); return true; }; + this.mm.addMessageListener("Marionette:deleteCookie", cb); yield this.listener.deleteAllCookies(); this.mm.removeMessageListener("Marionette:deleteCookie", cb); @@ -2167,6 +2190,8 @@ GeckoDriver.prototype.deleteAllCookies = function*(cmd, resp) { /** Delete a cookie by name. */ GeckoDriver.prototype.deleteCookie = function*(cmd, resp) { + assert.content(this.context) + let cb = msg => { this.mm.removeMessageListener("Marionette:deleteCookie", cb); let cookie = msg.json; @@ -2178,6 +2203,7 @@ GeckoDriver.prototype.deleteCookie = function*(cmd, resp) { cookie.originAttributes); return true; }; + this.mm.addMessageListener("Marionette:deleteCookie", cb); yield this.listener.deleteCookie(cmd.parameters.name); }; @@ -2347,7 +2373,15 @@ GeckoDriver.prototype.deleteSession = function (cmd, resp) { /** Returns the current status of the Application Cache. */ GeckoDriver.prototype.getAppCacheStatus = function* (cmd, resp) { - resp.body.value = yield this.listener.getAppCacheStatus(); + switch (this.context) { + case Context.CHROME: + throw new UnsupportedOperationError( + "Command 'getAppCacheStatus' is not yet available in chrome context"); + + case Context.CONTENT: + resp.body.value = yield this.listener.getAppCacheStatus(); + break; + } }; /** @@ -2465,9 +2499,8 @@ GeckoDriver.prototype.takeScreenshot = function (cmd, resp) { * landscape-secondary. */ GeckoDriver.prototype.getScreenOrientation = function (cmd, resp) { - if (this.appName == "Firefox") { - throw new UnsupportedOperationError(); - } + assert.fennec(); + resp.body.value = this.getCurrentWindow().screen.mozOrientation; }; @@ -2494,7 +2527,7 @@ GeckoDriver.prototype.setScreenOrientation = function (cmd, resp) { let or = String(cmd.parameters.orientation); assert.string(or); let mozOr = or.toLowerCase(); - if (!ors.include(mozOr)) { + if (!ors.includes(mozOr)) { throw new InvalidArgumentError(`Unknown screen orientation: ${or}`); } @@ -2525,9 +2558,7 @@ GeckoDriver.prototype.getWindowSize = function (cmd, resp) { * bars, title bars, etc. */ GeckoDriver.prototype.setWindowSize = function (cmd, resp) { - if (this.appName != "Firefox") { - throw new UnsupportedOperationError(); - } + assert.firefox() let {width, height} = cmd.parameters; let win = this.getCurrentWindow(); @@ -2542,9 +2573,7 @@ GeckoDriver.prototype.setWindowSize = function (cmd, resp) { * Not Supported on B2G or Fennec. */ GeckoDriver.prototype.maximizeWindow = function (cmd, resp) { - if (this.appName != "Firefox") { - throw new UnsupportedOperationError(); - } + assert.firefox() let win = this.getCurrentWindow(); win.maximize() @@ -2641,9 +2670,7 @@ GeckoDriver.prototype.acceptConnections = function (cmd, resp) { * session. */ GeckoDriver.prototype.quitApplication = function (cmd, resp) { - if (this.appName != "Firefox") { - throw new WebDriverError("In app initiated quit only supported in Firefox"); - } + assert.firefox() let flags = Ci.nsIAppStartup.eAttemptQuit; for (let k of cmd.parameters.flags || []) { @@ -2658,9 +2685,7 @@ GeckoDriver.prototype.quitApplication = function (cmd, resp) { }; GeckoDriver.prototype.installAddon = function (cmd, resp) { - if (this.appName != "Firefox") { - throw new UnsupportedOperationError(); - } + assert.firefox() let path = cmd.parameters.path; let temp = cmd.parameters.temporary || false; @@ -2673,9 +2698,7 @@ GeckoDriver.prototype.installAddon = function (cmd, resp) { }; GeckoDriver.prototype.uninstallAddon = function (cmd, resp) { - if (this.appName != "Firefox") { - throw new UnsupportedOperationError(); - } + assert.firefox() let id = cmd.parameters.id; if (typeof id == "undefined" || typeof id != "string") { diff --git a/testing/marionette/harness/marionette_harness/tests/unit/test_cookies.py b/testing/marionette/harness/marionette_harness/tests/unit/test_cookies.py index e2b7a6fc2c4e..f7841c73e099 100644 --- a/testing/marionette/harness/marionette_harness/tests/unit/test_cookies.py +++ b/testing/marionette/harness/marionette_harness/tests/unit/test_cookies.py @@ -6,6 +6,7 @@ import calendar import random import time +from marionette_driver.errors import UnsupportedOperationException from marionette_harness import MarionetteTestCase @@ -36,6 +37,17 @@ class CookieTest(MarionetteTestCase): cookies = self.marionette.get_cookies() self.assertEquals(0, len(cookies)) + def test_chrome_error(self): + with self.marionette.using_context("chrome"): + self.assertRaises(UnsupportedOperationException, + self.marionette.add_cookie, self.COOKIE_A) + self.assertRaises(UnsupportedOperationException, + self.marionette.delete_cookie, self.COOKIE_A) + self.assertRaises(UnsupportedOperationException, + self.marionette.delete_all_cookies) + self.assertRaises(UnsupportedOperationException, + self.marionette.get_cookies) + def test_delete_all_cookie(self): self.marionette.add_cookie(self.COOKIE_A) cookie_returned = str(self.marionette.execute_script("return document.cookie")) diff --git a/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py b/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py index 75276c4a99f8..9e3b26a1c5d4 100644 --- a/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py +++ b/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py @@ -51,9 +51,11 @@ class TestNavigate(WindowManagerMixin, MarionetteTestCase): def test_navigate_chrome_error(self): with self.marionette.using_context("chrome"): - self.assertRaisesRegexp( - errors.UnsupportedOperationException, "Cannot navigate in chrome context", - self.marionette.navigate, "about:blank") + self.assertRaises(errors.UnsupportedOperationException, + self.marionette.navigate, "about:blank") + self.assertRaises(errors.UnsupportedOperationException, self.marionette.go_back) + self.assertRaises(errors.UnsupportedOperationException, self.marionette.go_forward) + self.assertRaises(errors.UnsupportedOperationException, self.marionette.refresh) def test_get_current_url_returns_top_level_browsing_context_url(self): self.marionette.navigate(self.iframe_doc) diff --git a/testing/marionette/harness/marionette_harness/tests/unit/test_shadow_dom.py b/testing/marionette/harness/marionette_harness/tests/unit/test_shadow_dom.py index be530101e510..9750d8cdd728 100644 --- a/testing/marionette/harness/marionette_harness/tests/unit/test_shadow_dom.py +++ b/testing/marionette/harness/marionette_harness/tests/unit/test_shadow_dom.py @@ -5,7 +5,8 @@ from marionette_driver.by import By from marionette_driver.errors import ( NoSuchElementException, - StaleElementException + StaleElementException, + UnsupportedOperationException, ) from marionette_harness import MarionetteTestCase @@ -22,6 +23,11 @@ class TestShadowDom(MarionetteTestCase): self.marionette.switch_to_shadow_root(self.host) self.button = self.marionette.find_element(By.ID, "button") + def test_chrome_error(self): + with self.marionette.using_context("chrome"): + self.assertRaises(UnsupportedOperationException, + self.marionette.switch_to_shadow_root) + def test_shadow_dom(self): # Button in shadow root should be actionable self.button.click() From bf8b1f5ab994b65035c1a3de6a7e85817b1ef9ff Mon Sep 17 00:00:00 2001 From: "Nils Ohlmeier [:drno]" Date: Tue, 20 Dec 2016 23:20:01 -0800 Subject: [PATCH 085/229] Bug 1324995: only free AdapterAddresses if needed. r=bwc,jesup MozReview-Commit-ID: 8C4yPsGGPoV --HG-- extra : rebase_source : 96364e7469b92f3ce1a2e8b56b886b4581287d89 --- media/mtransport/third_party/nICEr/src/stun/addrs.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/media/mtransport/third_party/nICEr/src/stun/addrs.c b/media/mtransport/third_party/nICEr/src/stun/addrs.c index 6c7bc7a4bb91..f881acc06b14 100644 --- a/media/mtransport/third_party/nICEr/src/stun/addrs.c +++ b/media/mtransport/third_party/nICEr/src/stun/addrs.c @@ -243,7 +243,9 @@ stun_get_win32_addrs(nr_local_addr addrs[], int maxaddrs, int *count) _status = 0; abort: - RFREE(AdapterAddresses); + if (AdapterAddresses) { + RFREE(AdapterAddresses); + } return _status; } From ac17ce81ae71ef067094d60860b61d4c6ff665e1 Mon Sep 17 00:00:00 2001 From: Jared Wein Date: Thu, 22 Dec 2016 15:57:40 -0500 Subject: [PATCH 086/229] Bug 1325464 - Use ES6 method syntax for preferences. r=MattN MozReview-Commit-ID: k3Bkm39TtT --HG-- extra : rebase_source : a3e78734613429ec157e56cf9ef5a087f3f4da61 --- .../preferences/in-content/advanced.js | 72 +++++------ .../preferences/in-content/applications.js | 102 +++++++-------- .../preferences/in-content/content.js | 24 ++-- .../components/preferences/in-content/main.js | 40 +++--- .../preferences/in-content/preferences.js | 2 +- .../preferences/in-content/privacy.js | 48 ++++---- .../preferences/in-content/search.js | 116 +++++++++--------- .../preferences/in-content/security.js | 20 +-- .../preferences/in-content/subdialogs.js | 36 +++--- .../components/preferences/in-content/sync.js | 62 +++++----- 10 files changed, 261 insertions(+), 261 deletions(-) diff --git a/browser/components/preferences/in-content/advanced.js b/browser/components/preferences/in-content/advanced.js index 992b805ce103..68cef05b8d60 100644 --- a/browser/components/preferences/in-content/advanced.js +++ b/browser/components/preferences/in-content/advanced.js @@ -18,7 +18,7 @@ var gAdvancedPane = { /** * Brings the appropriate tab to the front and initializes various bits of UI. */ - init: function() + init() { function setEventListener(aId, aEventType, aCallback) { @@ -120,7 +120,7 @@ var gAdvancedPane = { * Stores the identity of the current tab in preferences so that the selected * tab can be persisted between openings of the preferences window. */ - tabSelectionChanged: function() + tabSelectionChanged() { if (!this._inited) return; @@ -182,7 +182,7 @@ var gAdvancedPane = { * the current value to enable proper pref restoration if the checkbox is * never changed. */ - readCheckSpelling: function() + readCheckSpelling() { var pref = document.getElementById("layout.spellcheckDefault"); this._storedSpellCheck = pref.value; @@ -195,7 +195,7 @@ var gAdvancedPane = { * preserving the preference's "hidden" value if the preference is * unchanged and represents a value not strictly allowed in UI. */ - writeCheckSpelling: function() + writeCheckSpelling() { var checkbox = document.getElementById("checkSpelling"); if (checkbox.checked) { @@ -211,7 +211,7 @@ var gAdvancedPane = { * security.OCSP.enabled is an integer value for legacy reasons. * A value of 1 means OCSP is enabled. Any other value means it is disabled. */ - readEnableOCSP: function() + readEnableOCSP() { var preference = document.getElementById("security.OCSP.enabled"); // This is the case if the preference is the default value. @@ -224,7 +224,7 @@ var gAdvancedPane = { /** * See documentation for readEnableOCSP. */ - writeEnableOCSP: function() + writeEnableOCSP() { var checkbox = document.getElementById("enableOCSP"); return checkbox.checked ? 1 : 0; @@ -234,7 +234,7 @@ var gAdvancedPane = { * When the user toggles the layers.acceleration.disabled pref, * sync its new value to the gfx.direct2d.disabled pref too. */ - updateHardwareAcceleration: function() + updateHardwareAcceleration() { if (AppConstants.platform = "win") { var fromPref = document.getElementById("layers.acceleration.disabled"); @@ -248,7 +248,7 @@ var gAdvancedPane = { /** * Set up or hide the Learn More links for various data collection options */ - _setupLearnMoreLink: function(pref, element) { + _setupLearnMoreLink(pref, element) { // set up the Learn More link with the correct URL let url = Services.prefs.getCharPref(pref); let el = document.getElementById(element); @@ -263,7 +263,7 @@ var gAdvancedPane = { /** * */ - initSubmitCrashes: function() + initSubmitCrashes() { this._setupLearnMoreLink("toolkit.crashreporter.infoURL", "crashReporterLearnMore"); @@ -274,7 +274,7 @@ var gAdvancedPane = { * * In all cases, set up the Learn More link sanely. */ - initTelemetry: function() + initTelemetry() { if (AppConstants.MOZ_TELEMETRY_REPORTING) { this._setupLearnMoreLink("toolkit.telemetry.infoURL", "telemetryLearnMore"); @@ -285,7 +285,7 @@ var gAdvancedPane = { * Set the status of the telemetry controls based on the input argument. * @param {Boolean} aEnabled False disables the controls, true enables them. */ - setTelemetrySectionEnabled: function(aEnabled) + setTelemetrySectionEnabled(aEnabled) { if (AppConstants.MOZ_TELEMETRY_REPORTING) { // If FHR is disabled, additional data sharing should be disabled as well. @@ -302,7 +302,7 @@ var gAdvancedPane = { /** * Initialize the health report service reference and checkbox. */ - initSubmitHealthReport: function() { + initSubmitHealthReport() { if (AppConstants.MOZ_TELEMETRY_REPORTING) { this._setupLearnMoreLink("datareporting.healthreport.infoURL", "FHRLearnMore"); @@ -321,7 +321,7 @@ var gAdvancedPane = { /** * Update the health report preference with state from checkbox. */ - updateSubmitHealthReport: function() { + updateSubmitHealthReport() { if (AppConstants.MOZ_TELEMETRY_REPORTING) { let checkbox = document.getElementById("submitHealthReportBox"); Services.prefs.setBoolPref(PREF_UPLOAD_ENABLED, checkbox.checked); @@ -351,16 +351,16 @@ var gAdvancedPane = { /** * Displays a dialog in which proxy settings may be changed. */ - showConnections: function() + showConnections() { gSubDialog.open("chrome://browser/content/preferences/connection.xul"); }, - showSiteDataSettings: function() { + showSiteDataSettings() { gSubDialog.open("chrome://browser/content/preferences/siteDataSettings.xul"); }, - updateTotalSiteDataSize: function() { + updateTotalSiteDataSize() { SiteDataManager.getTotalUsage() .then(usage => { let size = DownloadUtils.convertByteUnits(usage); @@ -373,14 +373,14 @@ var gAdvancedPane = { }, // Retrieves the amount of space currently used by disk cache - updateActualCacheSize: function() + updateActualCacheSize() { var actualSizeLabel = document.getElementById("actualDiskCacheSize"); var prefStrBundle = document.getElementById("bundlePreferences"); // Needs to root the observer since cache service keeps only a weak reference. this.observer = { - onNetworkCacheDiskConsumption: function(consumption) { + onNetworkCacheDiskConsumption(consumption) { var size = DownloadUtils.convertByteUnits(consumption); // The XBL binding for the string bundle may have been destroyed if // the page was closed before this callback was executed. @@ -407,10 +407,10 @@ var gAdvancedPane = { }, // Retrieves the amount of space currently used by offline cache - updateActualAppCacheSize: function() + updateActualAppCacheSize() { var visitor = { - onCacheStorageInfo: function(aEntryCount, aConsumption, aCapacity, aDiskDirectory) + onCacheStorageInfo(aEntryCount, aConsumption, aCapacity, aDiskDirectory) { var actualSizeLabel = document.getElementById("actualAppCacheSize"); var sizeStrings = DownloadUtils.convertByteUnits(aConsumption); @@ -434,14 +434,14 @@ var gAdvancedPane = { } catch (e) {} }, - updateCacheSizeUI: function(smartSizeEnabled) + updateCacheSizeUI(smartSizeEnabled) { document.getElementById("useCacheBefore").disabled = smartSizeEnabled; document.getElementById("cacheSize").disabled = smartSizeEnabled; document.getElementById("useCacheAfter").disabled = smartSizeEnabled; }, - readSmartSizeEnabled: function() + readSmartSizeEnabled() { // The smart_size.enabled preference element is inverted="true", so its // value is the opposite of the actual pref value @@ -480,7 +480,7 @@ var gAdvancedPane = { /** * Clears the cache. */ - clearCache: function() + clearCache() { try { var cache = Components.classes["@mozilla.org/netwerk/cache-storage-service;1"] @@ -493,7 +493,7 @@ var gAdvancedPane = { /** * Clears the application cache. */ - clearOfflineAppCache: function() + clearOfflineAppCache() { Components.utils.import("resource:///modules/offlineAppCache.jsm"); OfflineAppCacheHelper.clear(); @@ -502,7 +502,7 @@ var gAdvancedPane = { this.updateOfflineApps(); }, - clearSiteData: function() { + clearSiteData() { let flags = Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_0 + Services.prompt.BUTTON_TITLE_CANCEL * Services.prompt.BUTTON_POS_1 + @@ -519,7 +519,7 @@ var gAdvancedPane = { } }, - readOfflineNotify: function() + readOfflineNotify() { var pref = document.getElementById("browser.offline-apps.notify"); var button = document.getElementById("offlineNotifyExceptions"); @@ -527,7 +527,7 @@ var gAdvancedPane = { return pref.value; }, - showOfflineExceptions: function() + showOfflineExceptions() { var bundlePreferences = document.getElementById("bundlePreferences"); var params = { blockVisible : false, @@ -569,7 +569,7 @@ var gAdvancedPane = { /** * Updates the list of offline applications */ - updateOfflineApps: function() + updateOfflineApps() { var pm = Components.classes["@mozilla.org/permissionmanager;1"] .getService(Components.interfaces.nsIPermissionManager); @@ -610,7 +610,7 @@ var gAdvancedPane = { } }, - offlineAppSelected: function() + offlineAppSelected() { var removeButton = document.getElementById("offlineAppsListRemove"); var list = document.getElementById("offlineAppsList"); @@ -621,7 +621,7 @@ var gAdvancedPane = { } }, - removeOfflineApp: function() + removeOfflineApp() { var list = document.getElementById("offlineAppsList"); var item = list.selectedItem; @@ -702,7 +702,7 @@ var gAdvancedPane = { * ii t/f f false * ii t/f *t* *true* */ - updateReadPrefs: function() + updateReadPrefs() { if (AppConstants.MOZ_UPDATER) { var enabledPref = document.getElementById("app.update.enabled"); @@ -748,7 +748,7 @@ var gAdvancedPane = { /** * Sets the pref values based on the selected item of the radiogroup. */ - updateWritePrefs: function() + updateWritePrefs() { if (AppConstants.MOZ_UPDATER) { var enabledPref = document.getElementById("app.update.enabled"); @@ -773,7 +773,7 @@ var gAdvancedPane = { /** * Displays the history of installed updates. */ - showUpdates: function() + showUpdates() { gSubDialog.open("chrome://mozapps/content/update/history.xul"); }, @@ -795,7 +795,7 @@ var gAdvancedPane = { /** * Displays the user's certificates and associated options. */ - showCertificates: function() + showCertificates() { gSubDialog.open("chrome://pippki/content/certManager.xul"); }, @@ -803,12 +803,12 @@ var gAdvancedPane = { /** * Displays a dialog from which the user can manage his security devices. */ - showSecurityDevices: function() + showSecurityDevices() { gSubDialog.open("chrome://pippki/content/device_manager.xul"); }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (AppConstants.MOZ_UPDATER) { switch (aTopic) { case "nsPref:changed": diff --git a/browser/components/preferences/in-content/applications.js b/browser/components/preferences/in-content/applications.js index 30d87dacf96e..67879b025e44 100644 --- a/browser/components/preferences/in-content/applications.js +++ b/browser/components/preferences/in-content/applications.js @@ -119,11 +119,11 @@ function ArrayEnumerator(aItems) { ArrayEnumerator.prototype = { _index: 0, - hasMoreElements: function() { + hasMoreElements() { return this._index < this._contents.length; }, - getNext: function() { + getNext() { return this._contents[this._index++]; } }; @@ -172,7 +172,7 @@ HandlerInfoWrapper.prototype = { _categoryMgr: Cc["@mozilla.org/categorymanager;1"]. getService(Ci.nsICategoryManager), - element: function(aID) { + element(aID) { return document.getElementById(aID); }, @@ -214,7 +214,7 @@ HandlerInfoWrapper.prototype = { return this.wrappedHandlerInfo.possibleApplicationHandlers; }, - addPossibleApplicationHandler: function(aNewHandler) { + addPossibleApplicationHandler(aNewHandler) { var possibleApps = this.possibleApplicationHandlers.enumerate(); while (possibleApps.hasMoreElements()) { if (possibleApps.getNext().equals(aNewHandler)) @@ -223,7 +223,7 @@ HandlerInfoWrapper.prototype = { this.possibleApplicationHandlers.appendElement(aNewHandler, false); }, - removePossibleApplicationHandler: function(aHandler) { + removePossibleApplicationHandler(aHandler) { var defaultApp = this.preferredApplicationHandler; if (defaultApp && aHandler.equals(defaultApp)) { // If the app we remove was the default app, we must make sure @@ -362,7 +362,7 @@ HandlerInfoWrapper.prototype = { return this._getDisabledPluginTypes().indexOf(this.type) != -1; }, - _getDisabledPluginTypes: function() { + _getDisabledPluginTypes() { var types = ""; if (this._prefSvc.prefHasUserValue(PREF_DISABLED_PLUGIN_TYPES)) @@ -376,7 +376,7 @@ HandlerInfoWrapper.prototype = { return []; }, - disablePluginType: function() { + disablePluginType() { var disabledPluginTypes = this._getDisabledPluginTypes(); if (disabledPluginTypes.indexOf(this.type) == -1) @@ -391,7 +391,7 @@ HandlerInfoWrapper.prototype = { false); }, - enablePluginType: function() { + enablePluginType() { var disabledPluginTypes = this._getDisabledPluginTypes(); var type = this.type; @@ -412,7 +412,7 @@ HandlerInfoWrapper.prototype = { // Storage - store: function() { + store() { this._handlerSvc.store(this.wrappedHandlerInfo); }, @@ -423,7 +423,7 @@ HandlerInfoWrapper.prototype = { return this._getIcon(16); }, - _getIcon: function(aSize) { + _getIcon(aSize) { if (this.primaryExtension) return "moz-icon://goat." + this.primaryExtension + "?size=" + aSize; @@ -529,7 +529,7 @@ FeedHandlerInfo.prototype = { _inner: [], _removed: [], - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (aIID.equals(Ci.nsIMutableArray) || aIID.equals(Ci.nsIArray) || aIID.equals(Ci.nsISupports)) @@ -542,20 +542,20 @@ FeedHandlerInfo.prototype = { return this._inner.length; }, - enumerate: function() { + enumerate() { return new ArrayEnumerator(this._inner); }, - appendElement: function(aHandlerApp, aWeak) { + appendElement(aHandlerApp, aWeak) { this._inner.push(aHandlerApp); }, - removeElementAt: function(aIndex) { + removeElementAt(aIndex) { this._removed.push(this._inner[aIndex]); this._inner.splice(aIndex, 1); }, - queryElementAt: function(aIndex, aInterface) { + queryElementAt(aIndex, aInterface) { return this._inner[aIndex].QueryInterface(aInterface); } }; @@ -725,7 +725,7 @@ FeedHandlerInfo.prototype = { // so we when the controller calls store() after modifying the handlers, // the only thing we need to store is the removal of possible handlers // XXX Should we hold off on making the changes until this method gets called? - store: function() { + store() { for (let app of this._possibleApplicationHandlers._removed) { if (app instanceof Ci.nsILocalHandlerApp) { let pref = this.element(PREF_FEED_SELECTED_APP); @@ -800,7 +800,7 @@ InternalHandlerInfoWrapper.prototype = { // Override store so we so we can notify any code listening for registration // or unregistration of this handler. - store: function() { + store() { HandlerInfoWrapper.prototype.store.call(this); Services.obs.notifyObservers(null, this._handlerChanged, null); }, @@ -873,7 +873,7 @@ var gApplicationsPane = { // Initialization & Destruction - init: function() { + init() { function setEventListener(aId, aEventType, aCallback) { document.getElementById(aId) @@ -952,7 +952,7 @@ var gApplicationsPane = { setTimeout(_delayedPaneLoad, 0, this); }, - destroy: function() { + destroy() { window.removeEventListener("unload", this, false); this._prefSvc.removeObserver(PREF_SHOW_PLUGINS_IN_LIST, this); this._prefSvc.removeObserver(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS, this); @@ -975,7 +975,7 @@ var gApplicationsPane = { // nsISupports - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (aIID.equals(Ci.nsIObserver) || aIID.equals(Ci.nsIDOMEventListener || aIID.equals(Ci.nsISupports))) @@ -987,7 +987,7 @@ var gApplicationsPane = { // nsIObserver - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { // Rebuild the list when there are changes to preferences that influence // whether or not to show certain entries in the list. if (aTopic == "nsPref:changed" && !this._storingAction) { @@ -1008,7 +1008,7 @@ var gApplicationsPane = { // nsIDOMEventListener - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (aEvent.type == "unload") { this.destroy(); } @@ -1017,14 +1017,14 @@ var gApplicationsPane = { // Composed Model Construction - _loadData: function() { + _loadData() { this._loadFeedHandler(); this._loadInternalHandlers(); this._loadPluginHandlers(); this._loadApplicationHandlers(); }, - _loadFeedHandler: function() { + _loadFeedHandler() { this._handledTypes[TYPE_MAYBE_FEED] = feedHandlerInfo; feedHandlerInfo.handledOnlyByPlugin = false; @@ -1039,7 +1039,7 @@ var gApplicationsPane = { * Load higher level internal handlers so they can be turned on/off in the * applications menu. */ - _loadInternalHandlers: function() { + _loadInternalHandlers() { var internalHandlers = [pdfHandlerInfo]; for (let internalHandler of internalHandlers) { if (internalHandler.enabled) { @@ -1066,7 +1066,7 @@ var gApplicationsPane = { * enabledPlugin to get the plugin that would be used, we'd still need to * check the pref ourselves to find out if it's enabled. */ - _loadPluginHandlers: function() { + _loadPluginHandlers() { "use strict"; let mimeTypes = navigator.mimeTypes; @@ -1089,7 +1089,7 @@ var gApplicationsPane = { /** * Load the set of handlers defined by the application datastore. */ - _loadApplicationHandlers: function() { + _loadApplicationHandlers() { var wrappedHandlerInfos = this._handlerSvc.enumerate(); while (wrappedHandlerInfos.hasMoreElements()) { let wrappedHandlerInfo = @@ -1111,7 +1111,7 @@ var gApplicationsPane = { // View Construction - _rebuildVisibleTypes: function() { + _rebuildVisibleTypes() { // Reset the list of visible types and the visible type description counts. this._visibleTypes = []; this._visibleTypeDescriptionCount = {}; @@ -1150,7 +1150,7 @@ var gApplicationsPane = { } }, - _rebuildView: function() { + _rebuildView() { // Clear the list of entries. while (this._list.childNodes.length > 1) this._list.removeChild(this._list.lastChild); @@ -1181,7 +1181,7 @@ var gApplicationsPane = { this._selectLastSelectedType(); }, - _matchesFilter: function(aType) { + _matchesFilter(aType) { var filterValue = this._filter.value.toLowerCase(); return this._describeType(aType).toLowerCase().indexOf(filterValue) != -1 || this._describePreferredAction(aType).toLowerCase().indexOf(filterValue) != -1; @@ -1197,7 +1197,7 @@ var gApplicationsPane = { * @param aHandlerInfo {nsIHandlerInfo} the type being described * @returns {string} a description of the type */ - _describeType: function(aHandlerInfo) { + _describeType(aHandlerInfo) { if (this._visibleTypeDescriptionCount[aHandlerInfo.description] > 1) return this._prefsBundle.getFormattedString("typeDescriptionWithType", [aHandlerInfo.description, @@ -1218,7 +1218,7 @@ var gApplicationsPane = { * is being described * @returns {string} a description of the action */ - _describePreferredAction: function(aHandlerInfo) { + _describePreferredAction(aHandlerInfo) { // alwaysAskBeforeHandling overrides the preferred action, so if that flag // is set, then describe that behavior instead. For most types, this is // the "alwaysAsk" string, but for the feed type we show something special. @@ -1280,7 +1280,7 @@ var gApplicationsPane = { } }, - _selectLastSelectedType: function() { + _selectLastSelectedType() { // If the list is disabled by the pref.downloads.disable_button.edit_actions // preference being locked, then don't select the type, as that would cause // it to appear selected, with a different background and an actions menu @@ -1306,7 +1306,7 @@ var gApplicationsPane = { * * @returns {boolean} whether or not it's valid */ - isValidHandlerApp: function(aHandlerApp) { + isValidHandlerApp(aHandlerApp) { if (!aHandlerApp) return false; @@ -1322,7 +1322,7 @@ var gApplicationsPane = { return false; }, - _isValidHandlerExecutable: function(aExecutable) { + _isValidHandlerExecutable(aExecutable) { let leafName; if (AppConstants.platform == "win") { leafName = `${AppConstants.MOZ_APP_NAME}.exe`; @@ -1344,7 +1344,7 @@ var gApplicationsPane = { * Rebuild the actions menu for the selected entry. Gets called by * the richlistitem constructor when an entry in the list gets selected. */ - rebuildActionsMenu: function() { + rebuildActionsMenu() { var typeItem = this._list.selectedItem; var handlerInfo = this._handledTypes[typeItem.type]; var menu = @@ -1539,7 +1539,7 @@ var gApplicationsPane = { /** * Sort the list when the user clicks on a column header. */ - sort: function(event) { + sort(event) { var column = event.target; // If the user clicked on a new sort column, remove the direction indicator @@ -1562,7 +1562,7 @@ var gApplicationsPane = { /** * Sort the list of visible types by the current sort column/direction. */ - _sortVisibleTypes: function() { + _sortVisibleTypes() { if (!this._sortColumn) return; @@ -1594,11 +1594,11 @@ var gApplicationsPane = { /** * Filter the list when the user enters a filter term into the filter field. */ - filter: function() { + filter() { this._rebuildView(); }, - focusFilterBox: function() { + focusFilterBox() { this._filter.focus(); this._filter.select(); }, @@ -1606,7 +1606,7 @@ var gApplicationsPane = { // Changes - onSelectAction: function(aActionItem) { + onSelectAction(aActionItem) { this._storingAction = true; try { @@ -1617,7 +1617,7 @@ var gApplicationsPane = { } }, - _storeAction: function(aActionItem) { + _storeAction(aActionItem) { var typeItem = this._list.selectedItem; var handlerInfo = this._handledTypes[typeItem.type]; @@ -1662,7 +1662,7 @@ var gApplicationsPane = { } }, - manageApp: function(aEvent) { + manageApp(aEvent) { // Don't let the normal "on select action" handler get this event, // as we handle it specially ourselves. aEvent.stopPropagation(); @@ -1689,7 +1689,7 @@ var gApplicationsPane = { }, - chooseApp: function(aEvent) { + chooseApp(aEvent) { // Don't let the normal "on select action" handler get this event, // as we handle it specially ourselves. aEvent.stopPropagation(); @@ -1777,13 +1777,13 @@ var gApplicationsPane = { // Mark which item in the list was last selected so we can reselect it // when we rebuild the list or when the user returns to the prefpane. - onSelectionChanged: function() { + onSelectionChanged() { if (this._list.selectedItem) this._list.setAttribute("lastSelectedType", this._list.selectedItem.getAttribute("type")); }, - _setIconClassForPreferredAction: function(aHandlerInfo, aElement) { + _setIconClassForPreferredAction(aHandlerInfo, aElement) { // If this returns true, the attribute that CSS sniffs for was set to something // so you shouldn't manually set an icon URI. // This removes the existing actionIcon attribute if any, even if returning false. @@ -1817,7 +1817,7 @@ var gApplicationsPane = { return false; }, - _getIconURLForPreferredAction: function(aHandlerInfo) { + _getIconURLForPreferredAction(aHandlerInfo) { switch (aHandlerInfo.preferredAction) { case Ci.nsIHandlerInfo.useSystemDefault: return this._getIconURLForSystemDefault(aHandlerInfo); @@ -1835,7 +1835,7 @@ var gApplicationsPane = { } }, - _getIconURLForHandlerApp: function(aHandlerApp) { + _getIconURLForHandlerApp(aHandlerApp) { if (aHandlerApp instanceof Ci.nsILocalHandlerApp) return this._getIconURLForFile(aHandlerApp.executable); @@ -1849,7 +1849,7 @@ var gApplicationsPane = { return ""; }, - _getIconURLForFile: function(aFile) { + _getIconURLForFile(aFile) { var fph = this._ioSvc.getProtocolHandler("file"). QueryInterface(Ci.nsIFileProtocolHandler); var urlSpec = fph.getURLSpecFromFile(aFile); @@ -1857,7 +1857,7 @@ var gApplicationsPane = { return "moz-icon://" + urlSpec + "?size=16"; }, - _getIconURLForWebApp: function(aWebAppURITemplate) { + _getIconURLForWebApp(aWebAppURITemplate) { var uri = this._ioSvc.newURI(aWebAppURITemplate, null, null); // Unfortunately we can't use the favicon service to get the favicon, @@ -1873,7 +1873,7 @@ var gApplicationsPane = { return ""; }, - _getIconURLForSystemDefault: function(aHandlerInfo) { + _getIconURLForSystemDefault(aHandlerInfo) { // Handler info objects for MIME types on some OSes implement a property bag // interface from which we can get an icon for the default app, so if we're // dealing with a MIME type on one of those OSes, then try to get the icon. diff --git a/browser/components/preferences/in-content/content.js b/browser/components/preferences/in-content/content.js index 890a8be9c914..588e54f84876 100644 --- a/browser/components/preferences/in-content/content.js +++ b/browser/components/preferences/in-content/content.js @@ -16,7 +16,7 @@ XPCOMUtils.defineLazyGetter(this, "AlertsServiceDND", function() { }); var gContentPane = { - init: function() + init() { function setEventListener(aId, aEventType, aCallback) { @@ -99,7 +99,7 @@ var gContentPane = { * Utility function to enable/disable the button specified by aButtonID based * on the value of the Boolean preference specified by aPreferenceID. */ - updateButtons: function(aButtonID, aPreferenceID) + updateButtons(aButtonID, aPreferenceID) { var button = document.getElementById(aButtonID); var preference = document.getElementById(aPreferenceID); @@ -145,7 +145,7 @@ var gContentPane = { * Displays the popup exceptions dialog where specific site popup preferences * can be set. */ - showPopupExceptions: function() + showPopupExceptions() { var bundlePreferences = document.getElementById("bundlePreferences"); var params = { blockVisible: false, sessionVisible: false, allowVisible: true, @@ -162,7 +162,7 @@ var gContentPane = { /** * Populates the default font list in UI. */ - _rebuildFonts: function() + _rebuildFonts() { var preferences = document.getElementById("contentPreferences"); // Ensure preferences are "visible" to ensure bindings work. @@ -177,7 +177,7 @@ var gContentPane = { /** * */ - _selectDefaultLanguageGroup: function(aLanguageGroup, aIsSerif) + _selectDefaultLanguageGroup(aLanguageGroup, aIsSerif) { const kFontNameFmtSerif = "font.name.serif.%LANG%"; const kFontNameFmtSansSerif = "font.name.sans-serif.%LANG%"; @@ -228,7 +228,7 @@ var gContentPane = { * Returns the type of the current default font for the language denoted by * aLanguageGroup. */ - _readDefaultFontTypeForLanguage: function(aLanguageGroup) + _readDefaultFontTypeForLanguage(aLanguageGroup) { const kDefaultFontType = "font.default.%LANG%"; var defaultFontTypePref = kDefaultFontType.replace(/%LANG%/, aLanguageGroup); @@ -248,7 +248,7 @@ var gContentPane = { * Displays the fonts dialog, where web page font names and sizes can be * configured. */ - configureFonts: function() + configureFonts() { gSubDialog.open("chrome://browser/content/preferences/fonts.xul", "resizable=no"); }, @@ -257,7 +257,7 @@ var gContentPane = { * Displays the colors dialog, where default web page/link/etc. colors can be * configured. */ - configureColors: function() + configureColors() { gSubDialog.open("chrome://browser/content/preferences/colors.xul", "resizable=no"); }, @@ -267,7 +267,7 @@ var gContentPane = { /** * Shows a dialog in which the preferred language for web content may be set. */ - showLanguages: function() + showLanguages() { gSubDialog.open("chrome://browser/content/preferences/languages.xul"); }, @@ -276,18 +276,18 @@ var gContentPane = { * Displays the translation exceptions dialog where specific site and language * translation preferences can be set. */ - showTranslationExceptions: function() + showTranslationExceptions() { gSubDialog.open("chrome://browser/content/preferences/translation.xul"); }, - openTranslationProviderAttribution: function() + openTranslationProviderAttribution() { Components.utils.import("resource:///modules/translation/Translation.jsm"); Translation.openProviderAttribution(); }, - toggleDoNotDisturbNotifications: function(event) + toggleDoNotDisturbNotifications(event) { AlertsServiceDND.manualDoNotDisturb = event.target.checked; }, diff --git a/browser/components/preferences/in-content/main.js b/browser/components/preferences/in-content/main.js index 7f4687da3702..543fe2fd809d 100644 --- a/browser/components/preferences/in-content/main.js +++ b/browser/components/preferences/in-content/main.js @@ -20,7 +20,7 @@ var gMainPane = { /** * Initialization of this. */ - init: function() + init() { function setEventListener(aId, aEventType, aCallback) { @@ -121,7 +121,7 @@ var gMainPane = { .notifyObservers(window, "main-pane-loaded", null); }, - enableE10SChange: function() + enableE10SChange() { if (AppConstants.E10S_TESTING_ONLY) { let e10sCheckbox = document.getElementById("e10sAutoStart"); @@ -155,7 +155,7 @@ var gMainPane = { } }, - separateProfileModeChange: function() + separateProfileModeChange() { if (AppConstants.MOZ_DEV_EDITION) { function quitApp() { @@ -206,7 +206,7 @@ var gMainPane = { } }, - onGetStarted: function(aEvent) { + onGetStarted(aEvent) { if (AppConstants.MOZ_DEV_EDITION) { const Cc = Components.classes, Ci = Components.interfaces; let wm = Cc["@mozilla.org/appshell/window-mediator;1"] @@ -241,7 +241,7 @@ var gMainPane = { * option is preserved. */ - syncFromHomePref: function() + syncFromHomePref() { let homePref = document.getElementById("browser.startup.homepage"); @@ -267,7 +267,7 @@ var gMainPane = { return undefined; }, - syncToHomePref: function(value) + syncToHomePref(value) { // If the value is "", use about:home. if (value == "") @@ -282,7 +282,7 @@ var gMainPane = { * most recent browser window contains multiple tabs), updating preference * window UI to reflect this. */ - setHomePageToCurrent: function() + setHomePageToCurrent() { let homePage = document.getElementById("browser.startup.homepage"); let tabs = this._getTabsForHomePage(); @@ -300,7 +300,7 @@ var gMainPane = { * page. If the user selects a bookmark, that bookmark's name is displayed in * UI and the bookmark's address is stored to the home page preference. */ - setHomePageToBookmark: function() + setHomePageToBookmark() { var rv = { urls: null, names: null }; gSubDialog.open("chrome://browser/content/preferences/selectBookmark.xul", @@ -308,7 +308,7 @@ var gMainPane = { this._setHomePageToBookmarkClosed.bind(this, rv)); }, - _setHomePageToBookmarkClosed: function(rv, aEvent) { + _setHomePageToBookmarkClosed(rv, aEvent) { if (aEvent.detail.button != "accept") return; if (rv.urls && rv.names) { @@ -323,7 +323,7 @@ var gMainPane = { * Switches the "Use Current Page" button between its singular and plural * forms. */ - _updateUseCurrentButton: function() { + _updateUseCurrentButton() { let useCurrent = document.getElementById("useCurrent"); @@ -342,7 +342,7 @@ var gMainPane = { useCurrent.disabled = !tabs.length }, - _getTabsForHomePage: function() + _getTabsForHomePage() { var win; var tabs = []; @@ -366,7 +366,7 @@ var gMainPane = { /** * Check to see if a tab is not about:preferences */ - isNotAboutPreferences: function(aElement, aIndex, aArray) + isNotAboutPreferences(aElement, aIndex, aArray) { return !aElement.linkedBrowser.currentURI.spec.startsWith("about:preferences"); }, @@ -374,7 +374,7 @@ var gMainPane = { /** * Restores the default home page as the user's home page. */ - restoreDefaultHomePage: function() + restoreDefaultHomePage() { var homePage = document.getElementById("browser.startup.homepage"); homePage.value = homePage.defaultValue; @@ -416,7 +416,7 @@ var gMainPane = { * Enables/disables the folder field and Browse button based on whether a * default download directory is being used. */ - readUseDownloadDir: function() + readUseDownloadDir() { var downloadFolder = document.getElementById("downloadFolder"); var chooseFolder = document.getElementById("chooseFolder"); @@ -529,7 +529,7 @@ var gMainPane = { /** * Returns the textual path of a folder in readable form. */ - _getDisplayNameOfFile: function(aFolder) + _getDisplayNameOfFile(aFolder) { // TODO: would like to add support for 'Downloads on Macintosh HD' // for OS X users. @@ -603,7 +603,7 @@ var gMainPane = { * Hide/show the "Show my windows and tabs from last time" option based * on the value of the browser.privatebrowsing.autostart pref. */ - updateBrowserStartupLastSession: function() + updateBrowserStartupLastSession() { let pbAutoStartPref = document.getElementById("browser.privatebrowsing.autostart"); let startupPref = document.getElementById("browser.startup.page"); @@ -650,7 +650,7 @@ var gMainPane = { * * @returns |true| if such links should be opened in new tabs */ - readLinkTarget: function() { + readLinkTarget() { var openNewWindow = document.getElementById("browser.link.open_newwindow"); return openNewWindow.value != 2; }, @@ -661,7 +661,7 @@ var gMainPane = { * @returns 2 if such links should be opened in new windows, * 3 if such links should be opened in new tabs */ - writeLinkTarget: function() { + writeLinkTarget() { var linkTargeting = document.getElementById("linkTargeting"); return linkTargeting.checked ? 3 : 2; }, @@ -677,7 +677,7 @@ var gMainPane = { * Show button for setting browser as default browser or information that * browser is already the default browser. */ - updateSetDefaultBrowser: function() + updateSetDefaultBrowser() { if (AppConstants.HAVE_SHELL_SERVICE) { let shellSvc = getShellService(); @@ -698,7 +698,7 @@ var gMainPane = { /** * Set browser as the operating system default browser. */ - setDefaultBrowser: function() + setDefaultBrowser() { if (AppConstants.HAVE_SHELL_SERVICE) { let alwaysCheckPref = document.getElementById("browser.shell.checkDefaultBrowser"); diff --git a/browser/components/preferences/in-content/preferences.js b/browser/components/preferences/in-content/preferences.js index 68de4840598d..baf3f406a799 100644 --- a/browser/components/preferences/in-content/preferences.js +++ b/browser/components/preferences/in-content/preferences.js @@ -42,7 +42,7 @@ function init_category_if_required(category) { function register_module(categoryName, categoryObject) { gCategoryInits.set(categoryName, { inited: false, - init: function() { + init() { categoryObject.init(); this.inited = true; } diff --git a/browser/components/preferences/in-content/privacy.js b/browser/components/preferences/in-content/privacy.js index 8098132e203f..54beef47c4b6 100644 --- a/browser/components/preferences/in-content/privacy.js +++ b/browser/components/preferences/in-content/privacy.js @@ -26,7 +26,7 @@ var gPrivacyPane = { * Show the Tracking Protection UI depending on the * privacy.trackingprotection.ui.enabled pref, and linkify its Learn More link */ - _initTrackingProtection: function() { + _initTrackingProtection() { if (!Services.prefs.getBoolPref("privacy.trackingprotection.ui.enabled")) { return; } @@ -45,7 +45,7 @@ var gPrivacyPane = { * Linkify the Learn More link of the Private Browsing Mode Tracking * Protection UI. */ - _initTrackingProtectionPBM: function() { + _initTrackingProtectionPBM() { let link = document.getElementById("trackingProtectionPBMLearnMore"); let url = Services.urlFormatter.formatURLPref("app.support.baseURL") + "tracking-protection-pbm"; link.setAttribute("href", url); @@ -54,7 +54,7 @@ var gPrivacyPane = { /** * Initialize autocomplete to ensure prefs are in sync. */ - _initAutocomplete: function() { + _initAutocomplete() { Components.classes["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"] .getService(Components.interfaces.mozIPlacesAutoComplete); }, @@ -62,7 +62,7 @@ var gPrivacyPane = { /** * Show the Containers UI depending on the privacy.userContext.ui.enabled pref. */ - _initBrowserContainers: function() { + _initBrowserContainers() { if (!Services.prefs.getBoolPref("privacy.userContext.ui.enabled")) { return; } @@ -76,7 +76,7 @@ var gPrivacyPane = { Services.prefs.getBoolPref("privacy.userContext.enabled"); }, - _checkBrowserContainers: function(event) { + _checkBrowserContainers(event) { let checkbox = document.getElementById("browserContainersCheckbox"); if (checkbox.checked) { Services.prefs.setBoolPref("privacy.userContext.enabled", true); @@ -116,7 +116,7 @@ var gPrivacyPane = { * Sets up the UI for the number of days of history to keep, and updates the * label of the "Clear Now..." button. */ - init: function() + init() { function setEventListener(aId, aEventType, aCallback) { @@ -271,7 +271,7 @@ var gPrivacyPane = { * @returns boolean true if all of the prefs are set to keep history, * false otherwise */ - _checkHistoryValues: function(aPrefs) { + _checkHistoryValues(aPrefs) { for (let pref of Object.keys(aPrefs)) { if (document.getElementById(pref).value != aPrefs[pref]) return false; @@ -282,7 +282,7 @@ var gPrivacyPane = { /** * Initialize the history mode menulist based on the privacy preferences */ - initializeHistoryMode: function PPP_initializeHistoryMode() + initializeHistoryMode() { let mode; let getVal = aPref => document.getElementById(aPref).value; @@ -304,7 +304,7 @@ var gPrivacyPane = { /** * Update the selected pane based on the history mode menulist */ - updateHistoryModePane: function PPP_updateHistoryModePane() + updateHistoryModePane() { let selectedIndex = -1; switch (document.getElementById("historyMode").value) { @@ -326,7 +326,7 @@ var gPrivacyPane = { * Update the private browsing auto-start pref and the history mode * micro-management prefs based on the history mode menulist */ - updateHistoryModePrefs: function PPP_updateHistoryModePrefs() + updateHistoryModePrefs() { let pref = document.getElementById("browser.privatebrowsing.autostart"); switch (document.getElementById("historyMode").value) { @@ -361,7 +361,7 @@ var gPrivacyPane = { * Update the privacy micro-management controls based on the * value of the private browsing auto-start checkbox. */ - updatePrivacyMicroControls: function PPP_updatePrivacyMicroControls() + updatePrivacyMicroControls() { if (document.getElementById("historyMode").value == "custom") { let disabled = this._autoStartPrivateBrowsing = @@ -413,7 +413,7 @@ var gPrivacyPane = { /** * Initialize the starting state for the auto-start private browsing mode pref reverter. */ - initAutoStartPrivateBrowsingReverter: function PPP_initAutoStartPrivateBrowsingReverter() + initAutoStartPrivateBrowsingReverter() { let mode = document.getElementById("historyMode"); let autoStart = document.getElementById("privateBrowsingAutoStart"); @@ -423,7 +423,7 @@ var gPrivacyPane = { _lastMode: null, _lastCheckState: null, - updateAutostart: function PPP_updateAutostart() { + updateAutostart() { let mode = document.getElementById("historyMode"); let autoStart = document.getElementById("privateBrowsingAutoStart"); let pref = document.getElementById("browser.privatebrowsing.autostart"); @@ -490,7 +490,7 @@ var gPrivacyPane = { /** * Displays the available block lists for tracking protection. */ - showBlockLists: function() + showBlockLists() { var bundlePreferences = document.getElementById("bundlePreferences"); let brandName = document.getElementById("bundleBrand") @@ -545,7 +545,7 @@ var gPrivacyPane = { * enables/disables the rest of the cookie UI accordingly, returning true * if cookies are enabled. */ - readAcceptCookies: function() + readAcceptCookies() { var pref = document.getElementById("network.cookie.cookieBehavior"); var acceptThirdPartyLabel = document.getElementById("acceptThirdPartyLabel"); @@ -566,7 +566,7 @@ var gPrivacyPane = { * Enables/disables the "keep until" label and menulist in response to the * "accept cookies" checkbox being checked or unchecked. */ - writeAcceptCookies: function() + writeAcceptCookies() { var accept = document.getElementById("acceptCookies"); var acceptThirdPartyMenu = document.getElementById("acceptThirdPartyMenu"); @@ -581,7 +581,7 @@ var gPrivacyPane = { /** * Converts between network.cookie.cookieBehavior and the third-party cookie UI */ - readAcceptThirdPartyCookies: function() + readAcceptThirdPartyCookies() { var pref = document.getElementById("network.cookie.cookieBehavior"); switch (pref.value) @@ -599,7 +599,7 @@ var gPrivacyPane = { } }, - writeAcceptThirdPartyCookies: function() + writeAcceptThirdPartyCookies() { var accept = document.getElementById("acceptThirdPartyMenu").selectedItem; switch (accept.value) @@ -618,7 +618,7 @@ var gPrivacyPane = { /** * Displays fine-grained, per-site preferences for cookies. */ - showCookieExceptions: function() + showCookieExceptions() { var bundlePreferences = document.getElementById("bundlePreferences"); var params = { blockVisible : true, @@ -635,7 +635,7 @@ var gPrivacyPane = { /** * Displays all the user's cookies in a dialog. */ - showCookies: function(aCategory) + showCookies(aCategory) { gSubDialog.open("chrome://browser/content/preferences/cookies.xul"); }, @@ -653,7 +653,7 @@ var gPrivacyPane = { /** * Displays the Clear Private Data settings dialog. */ - showClearPrivateDataSettings: function() + showClearPrivateDataSettings() { gSubDialog.open("chrome://browser/content/preferences/sanitize.xul", "resizable=no"); }, @@ -663,7 +663,7 @@ var gPrivacyPane = { * Displays a dialog from which individual parts of private data may be * cleared. */ - clearPrivateDataNow: function(aClearEverything) { + clearPrivateDataNow(aClearEverything) { var ts = document.getElementById("privacy.sanitize.timeSpan"); var timeSpanOrig = ts.value; @@ -685,7 +685,7 @@ var gPrivacyPane = { * Enables or disables the "Settings..." button depending * on the privacy.sanitize.sanitizeOnShutdown preference value */ - _updateSanitizeSettingsButton: function() { + _updateSanitizeSettingsButton() { var settingsButton = document.getElementById("clearDataSettings"); var sanitizeOnShutdownPref = document.getElementById("privacy.sanitize.sanitizeOnShutdown"); @@ -704,7 +704,7 @@ var gPrivacyPane = { /** * Enables/disables the Settings button used to configure containers */ - readBrowserContainersCheckbox: function() + readBrowserContainersCheckbox() { var pref = document.getElementById("privacy.userContext.enabled"); var settings = document.getElementById("browserContainersSettings"); diff --git a/browser/components/preferences/in-content/search.js b/browser/components/preferences/in-content/search.js index 7cf77de75507..063944e7cd9e 100644 --- a/browser/components/preferences/in-content/search.js +++ b/browser/components/preferences/in-content/search.js @@ -17,12 +17,12 @@ var gSearchPane = { /** * Initialize autocomplete to ensure prefs are in sync. */ - _initAutocomplete: function() { + _initAutocomplete() { Components.classes["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"] .getService(Components.interfaces.mozIPlacesAutoComplete); }, - init: function() + init() { gEngineView = new EngineView(new EngineStore()); document.getElementById("engineList").view = gEngineView; @@ -75,7 +75,7 @@ var gSearchPane = { permanentPBLabel.hidden = urlbarSuggests.hidden || !permanentPB; }, - buildDefaultEngineDropDown: function() { + buildDefaultEngineDropDown() { // This is called each time something affects the list of engines. let list = document.getElementById("defaultEngine"); // Set selection to the current default engine. @@ -100,7 +100,7 @@ var gSearchPane = { }); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "click": if (aEvent.target.id != "engineChildren" && @@ -162,7 +162,7 @@ var gSearchPane = { } }, - observe: function(aEngine, aTopic, aVerb) { + observe(aEngine, aTopic, aVerb) { if (aTopic == "browser-search-engine-modified") { aEngine.QueryInterface(Components.interfaces.nsISearchEngine); switch (aVerb) { @@ -194,7 +194,7 @@ var gSearchPane = { } }, - onInputBlur: function(aEvent) { + onInputBlur(aEvent) { let tree = document.getElementById("engineList"); if (!tree.hasAttribute("editing")) return; @@ -204,12 +204,12 @@ var gSearchPane = { tree.stopEditing(accept); }, - onTreeSelect: function() { + onTreeSelect() { document.getElementById("removeEngineButton").disabled = !gEngineView.isEngineSelectedAndRemovable(); }, - onTreeKeyPress: function(aEvent) { + onTreeKeyPress(aEvent) { let index = gEngineView.selectedIndex; let tree = document.getElementById("engineList"); if (tree.hasAttribute("editing")) @@ -238,17 +238,17 @@ var gSearchPane = { } }, - onRestoreDefaults: function() { + onRestoreDefaults() { let num = gEngineView._engineStore.restoreDefaultEngines(); gEngineView.rowCountChanged(0, num); gEngineView.invalidate(); }, - showRestoreDefaults: function(aEnable) { + showRestoreDefaults(aEnable) { document.getElementById("restoreDefaultSearchEngines").disabled = !aEnable; }, - remove: function(aEngine) { + remove(aEngine) { let index = gEngineView._engineStore.removeEngine(aEngine); gEngineView.rowCountChanged(index, -1); gEngineView.invalidate(); @@ -294,7 +294,7 @@ var gSearchPane = { return true; }), - saveOneClickEnginesList: function() { + saveOneClickEnginesList() { let hiddenList = []; for (let engine of gEngineView._engineStore.engines) { if (!engine.shown) @@ -304,7 +304,7 @@ var gSearchPane = { hiddenList.join(","); }, - setDefaultEngine: function() { + setDefaultEngine() { Services.search.currentEngine = document.getElementById("defaultEngine").selectedItem.engine; } @@ -345,15 +345,15 @@ EngineStore.prototype = { return val; }, - _getIndexForEngine: function ES_getIndexForEngine(aEngine) { + _getIndexForEngine(aEngine) { return this._engines.indexOf(aEngine); }, - _getEngineByName: function ES_getEngineByName(aName) { + _getEngineByName(aName) { return this._engines.find(engine => engine.name == aName); }, - _cloneEngine: function ES_cloneEngine(aEngine) { + _cloneEngine(aEngine) { var clonedObj = {}; for (var i in aEngine) clonedObj[i] = aEngine[i]; @@ -363,15 +363,15 @@ EngineStore.prototype = { }, // Callback for Array's some(). A thisObj must be passed to some() - _isSameEngine: function ES_isSameEngine(aEngineClone) { + _isSameEngine(aEngineClone) { return aEngineClone.originalEngine == this.originalEngine; }, - addEngine: function ES_addEngine(aEngine) { + addEngine(aEngine) { this._engines.push(this._cloneEngine(aEngine)); }, - moveEngine: function ES_moveEngine(aEngine, aNewIndex) { + moveEngine(aEngine, aNewIndex) { if (aNewIndex < 0 || aNewIndex > this._engines.length - 1) throw new Error("ES_moveEngine: invalid aNewIndex!"); var index = this._getIndexForEngine(aEngine); @@ -388,7 +388,7 @@ EngineStore.prototype = { Services.search.moveEngine(aEngine.originalEngine, aNewIndex); }, - removeEngine: function ES_removeEngine(aEngine) { + removeEngine(aEngine) { if (this._engines.length == 1) { throw new Error("Cannot remove last engine!"); } @@ -407,7 +407,7 @@ EngineStore.prototype = { return index; }, - restoreDefaultEngines: function ES_restoreDefaultEngines() { + restoreDefaultEngines() { var added = 0; for (var i = 0; i < this._defaultEngines.length; ++i) { @@ -436,7 +436,7 @@ EngineStore.prototype = { return added; }, - changeEngine: function ES_changeEngine(aEngine, aProp, aNewValue) { + changeEngine(aEngine, aProp, aNewValue) { var index = this._getIndexForEngine(aEngine); if (index == -1) throw new Error("invalid engine?"); @@ -445,7 +445,7 @@ EngineStore.prototype = { aEngine.originalEngine[aProp] = aNewValue; }, - reloadIcons: function ES_reloadIcons() { + reloadIcons() { this._engines.forEach(function(e) { e.uri = e.originalEngine.uri; }); @@ -476,27 +476,27 @@ EngineView.prototype = { }, // Helpers - rowCountChanged: function(index, count) { + rowCountChanged(index, count) { this.tree.rowCountChanged(index, count); }, - invalidate: function() { + invalidate() { this.tree.invalidate(); }, - ensureRowIsVisible: function(index) { + ensureRowIsVisible(index) { this.tree.ensureRowIsVisible(index); }, - getSourceIndexFromDrag: function(dataTransfer) { + getSourceIndexFromDrag(dataTransfer) { return parseInt(dataTransfer.getData(ENGINE_FLAVOR)); }, - isCheckBox: function(index, column) { + isCheckBox(index, column) { return column.id == "engineShown"; }, - isEngineSelectedAndRemovable: function() { + isEngineSelectedAndRemovable() { return this.selectedIndex != -1 && this.lastIndex != 0; }, @@ -505,7 +505,7 @@ EngineView.prototype = { return this._engineStore.engines.length; }, - getImageSrc: function(index, column) { + getImageSrc(index, column) { if (column.id == "engineName") { if (this._engineStore.engines[index].iconURI) return this._engineStore.engines[index].iconURI.spec; @@ -518,7 +518,7 @@ EngineView.prototype = { return ""; }, - getCellText: function(index, column) { + getCellText(index, column) { if (column.id == "engineName") return this._engineStore.engines[index].name; else if (column.id == "engineKeyword") @@ -526,18 +526,18 @@ EngineView.prototype = { return ""; }, - setTree: function(tree) { + setTree(tree) { this.tree = tree; }, - canDrop: function(targetIndex, orientation, dataTransfer) { + canDrop(targetIndex, orientation, dataTransfer) { var sourceIndex = this.getSourceIndexFromDrag(dataTransfer); return (sourceIndex != -1 && sourceIndex != targetIndex && sourceIndex != targetIndex + orientation); }, - drop: function(dropIndex, orientation, dataTransfer) { + drop(dropIndex, orientation, dataTransfer) { var sourceIndex = this.getSourceIndexFromDrag(dataTransfer); var sourceEngine = this._engineStore.engines[sourceIndex]; @@ -559,37 +559,37 @@ EngineView.prototype = { }, selection: null, - getRowProperties: function(index) { return ""; }, - getCellProperties: function(index, column) { return ""; }, - getColumnProperties: function(column) { return ""; }, - isContainer: function(index) { return false; }, - isContainerOpen: function(index) { return false; }, - isContainerEmpty: function(index) { return false; }, - isSeparator: function(index) { return false; }, - isSorted: function(index) { return false; }, - getParentIndex: function(index) { return -1; }, - hasNextSibling: function(parentIndex, index) { return false; }, - getLevel: function(index) { return 0; }, - getProgressMode: function(index, column) { }, - getCellValue: function(index, column) { + getRowProperties(index) { return ""; }, + getCellProperties(index, column) { return ""; }, + getColumnProperties(column) { return ""; }, + isContainer(index) { return false; }, + isContainerOpen(index) { return false; }, + isContainerEmpty(index) { return false; }, + isSeparator(index) { return false; }, + isSorted(index) { return false; }, + getParentIndex(index) { return -1; }, + hasNextSibling(parentIndex, index) { return false; }, + getLevel(index) { return 0; }, + getProgressMode(index, column) { }, + getCellValue(index, column) { if (column.id == "engineShown") return this._engineStore.engines[index].shown; return undefined; }, - toggleOpenState: function(index) { }, - cycleHeader: function(column) { }, - selectionChanged: function() { }, - cycleCell: function(row, column) { }, - isEditable: function(index, column) { return column.id != "engineName"; }, - isSelectable: function(index, column) { return false; }, - setCellValue: function(index, column, value) { + toggleOpenState(index) { }, + cycleHeader(column) { }, + selectionChanged() { }, + cycleCell(row, column) { }, + isEditable(index, column) { return column.id != "engineName"; }, + isSelectable(index, column) { return false; }, + setCellValue(index, column, value) { if (column.id == "engineShown") { this._engineStore.engines[index].shown = value == "true"; gEngineView.invalidate(); gSearchPane.saveOneClickEnginesList(); } }, - setCellText: function(index, column, value) { + setCellText(index, column, value) { if (column.id == "engineKeyword") { gSearchPane.editKeyword(this._engineStore.engines[index], value) .then(valid => { @@ -598,7 +598,7 @@ EngineView.prototype = { }); } }, - performAction: function(action) { }, - performActionOnRow: function(action, index) { }, - performActionOnCell: function(action, index, column) { } + performAction(action) { }, + performActionOnRow(action, index) { }, + performActionOnCell(action, index, column) { } }; diff --git a/browser/components/preferences/in-content/security.js b/browser/components/preferences/in-content/security.js index a468100a1cd4..47f2fce33a4b 100644 --- a/browser/components/preferences/in-content/security.js +++ b/browser/components/preferences/in-content/security.js @@ -13,7 +13,7 @@ var gSecurityPane = { /** * Initializes master password UI. */ - init: function() + init() { function setEventListener(aId, aEventType, aCallback) { @@ -52,7 +52,7 @@ var gSecurityPane = { * Enables/disables the add-ons Exceptions button depending on whether * or not add-on installation warnings are displayed. */ - readWarnAddonInstall: function() + readWarnAddonInstall() { var warn = document.getElementById("xpinstall.whitelist.required"); var exceptions = document.getElementById("addonExceptions"); @@ -66,7 +66,7 @@ var gSecurityPane = { /** * Displays the exceptions lists for add-on installation warnings. */ - showAddonExceptions: function() + showAddonExceptions() { var bundlePrefs = document.getElementById("bundlePreferences"); @@ -106,7 +106,7 @@ var gSecurityPane = { * passwords are never saved. When browser is set to start in Private * Browsing mode, the "Remember passwords" UI is useless, so we disable it. */ - readSavePasswords: function() + readSavePasswords() { var pref = document.getElementById("signon.rememberSignons"); var excepts = document.getElementById("passwordExceptions"); @@ -125,7 +125,7 @@ var gSecurityPane = { * Displays a dialog in which the user can view and modify the list of sites * where passwords are never saved. */ - showPasswordExceptions: function() + showPasswordExceptions() { var bundlePrefs = document.getElementById("bundlePreferences"); var params = { @@ -149,7 +149,7 @@ var gSecurityPane = { * The master password is controlled by various bits of NSS functionality, so * the UI for it can't be controlled by the normal preference bindings. */ - _initMasterPasswordUI: function() + _initMasterPasswordUI() { var noMP = !LoginHelper.isMasterPasswordSet(); @@ -238,7 +238,7 @@ var gSecurityPane = { * "use master password" checkbox, and prompts for master password removal if * one is set. */ - updateMasterPasswordButton: function() + updateMasterPasswordButton() { var checkbox = document.getElementById("useMasterPassword"); var button = document.getElementById("changeMasterPassword"); @@ -262,7 +262,7 @@ var gSecurityPane = { * the current master password. When the dialog is dismissed, master password * UI is automatically updated. */ - _removeMasterPassword: function() + _removeMasterPassword() { var secmodDB = Cc["@mozilla.org/security/pkcs11moduledb;1"]. getService(Ci.nsIPKCS11ModuleDB); @@ -284,7 +284,7 @@ var gSecurityPane = { /** * Displays a dialog in which the master password may be changed. */ - changeMasterPassword: function() + changeMasterPassword() { gSubDialog.open("chrome://mozapps/content/preferences/changemp.xul", "resizable=no", null, this._initMasterPasswordUI.bind(this)); @@ -294,7 +294,7 @@ var gSecurityPane = { * Shows the sites where the user has saved passwords and the associated login * information. */ - showPasswords: function() + showPasswords() { gSubDialog.open("chrome://passwordmgr/content/passwordManager.xul"); } diff --git a/browser/components/preferences/in-content/subdialogs.js b/browser/components/preferences/in-content/subdialogs.js index bb8d0048f24e..9a21e383a5e3 100644 --- a/browser/components/preferences/in-content/subdialogs.js +++ b/browser/components/preferences/in-content/subdialogs.js @@ -19,20 +19,20 @@ var gSubDialog = { ], _resizeObserver: null, - init: function() { + init() { this._frame = document.getElementById("dialogFrame"); this._overlay = document.getElementById("dialogOverlay"); this._box = document.getElementById("dialogBox"); this._closeButton = document.getElementById("dialogClose"); }, - updateTitle: function(aEvent) { + updateTitle(aEvent) { if (aEvent.target != gSubDialog._frame.contentDocument) return; document.getElementById("dialogTitle").textContent = gSubDialog._frame.contentDocument.title; }, - injectXMLStylesheet: function(aStylesheetURL) { + injectXMLStylesheet(aStylesheetURL) { let contentStylesheet = this._frame.contentDocument.createProcessingInstruction( 'xml-stylesheet', 'href="' + aStylesheetURL + '" type="text/css"' @@ -41,7 +41,7 @@ var gSubDialog = { this._frame.contentDocument.documentElement); }, - open: function(aURL, aFeatures = null, aParams = null, aClosingCallback = null) { + open(aURL, aFeatures = null, aParams = null, aClosingCallback = null) { // If we're already open/opening on this URL, do nothing. if (this._openedURL == aURL && !this._isClosing) { return; @@ -76,7 +76,7 @@ var gSubDialog = { featureParams.get("resizable") != "0"); }, - close: function(aEvent = null) { + close(aEvent = null) { if (this._isClosing) { return; } @@ -122,7 +122,7 @@ var gSubDialog = { }, 0); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "command": this._frame.contentWindow.close(); @@ -153,13 +153,13 @@ var gSubDialog = { /* Private methods */ - _onUnload: function(aEvent) { + _onUnload(aEvent) { if (aEvent.target.location.href == this._openedURL) { this._frame.contentWindow.close(); } }, - _onContentLoaded: function(aEvent) { + _onContentLoaded(aEvent) { if (aEvent.target != this._frame || aEvent.target.contentWindow.location == "about:blank") { return; } @@ -209,7 +209,7 @@ var gSubDialog = { this._overlay.style.opacity = "0.01"; }, - _onLoad: function(aEvent) { + _onLoad(aEvent) { if (aEvent.target.contentWindow.location == "about:blank") { return; } @@ -293,7 +293,7 @@ var gSubDialog = { this._trapFocus(); }, - _onResize: function(mutations) { + _onResize(mutations) { let frame = gSubDialog._frame; // The width and height styles are needed for the initial // layout of the frame, but afterward they need to be removed @@ -319,12 +319,12 @@ var gSubDialog = { } }, - _onDialogClosing: function(aEvent) { + _onDialogClosing(aEvent) { this._frame.contentWindow.removeEventListener("dialogclosing", this); this._closingEvent = aEvent; }, - _onKeyDown: function(aEvent) { + _onKeyDown(aEvent) { if (aEvent.currentTarget == window && aEvent.keyCode == aEvent.DOM_VK_ESCAPE && !aEvent.defaultPrevented) { this.close(aEvent); @@ -362,7 +362,7 @@ var gSubDialog = { } }, - _onParentWinFocus: function(aEvent) { + _onParentWinFocus(aEvent) { // Explicitly check for the focus target of |window| to avoid triggering this when the window // is refocused if (aEvent.target != this._closeButton && aEvent.target != window) { @@ -370,7 +370,7 @@ var gSubDialog = { } }, - _addDialogEventListeners: function() { + _addDialogEventListeners() { // Make the close button work. this._closeButton.addEventListener("command", this); @@ -392,7 +392,7 @@ var gSubDialog = { window.addEventListener("keydown", this, true); }, - _removeDialogEventListeners: function() { + _removeDialogEventListeners() { let chromeBrowser = this._getBrowser(); chromeBrowser.removeEventListener("DOMTitleChanged", this, true); chromeBrowser.removeEventListener("unload", this, true); @@ -410,7 +410,7 @@ var gSubDialog = { this._untrapFocus(); }, - _trapFocus: function() { + _trapFocus() { let fm = Services.focus; fm.moveFocus(this._frame.contentWindow, null, fm.MOVEFOCUS_FIRST, 0); this._frame.contentDocument.addEventListener("keydown", this, true); @@ -419,13 +419,13 @@ var gSubDialog = { window.addEventListener("focus", this, true); }, - _untrapFocus: function() { + _untrapFocus() { this._frame.contentDocument.removeEventListener("keydown", this, true); this._closeButton.removeEventListener("keydown", this); window.removeEventListener("focus", this); }, - _getBrowser: function() { + _getBrowser() { return window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShell) diff --git a/browser/components/preferences/in-content/sync.js b/browser/components/preferences/in-content/sync.js index ca3175513dcf..32c5c934a292 100644 --- a/browser/components/preferences/in-content/sync.js +++ b/browser/components/preferences/in-content/sync.js @@ -42,14 +42,14 @@ var gSyncPane = { return Weave.Svc.Prefs.isSet("serverURL"); }, - needsUpdate: function() { + needsUpdate() { this.page = PAGE_NEEDS_UPDATE; let label = document.getElementById("loginError"); label.textContent = Weave.Utils.getErrorString(Weave.Status.login); label.className = "error"; }, - init: function() { + init() { this._setupEventListeners(); // If the Service hasn't finished initializing, wait for it. @@ -85,7 +85,7 @@ var gSyncPane = { xps.ensureLoaded(); }, - _showLoadPage: function(xps) { + _showLoadPage(xps) { let username; try { username = Services.prefs.getCharPref("services.sync.username"); @@ -109,7 +109,7 @@ var gSyncPane = { } }, - _init: function() { + _init() { let topics = ["weave:service:login:error", "weave:service:login:finish", "weave:service:start-over:finish", @@ -161,7 +161,7 @@ var gSyncPane = { this._initProfileImageUI(); }, - _toggleComputerNameControls: function(editMode) { + _toggleComputerNameControls(editMode) { let textbox = document.getElementById("fxaSyncComputerName"); textbox.disabled = !editMode; document.getElementById("fxaChangeDeviceName").hidden = editMode; @@ -169,25 +169,25 @@ var gSyncPane = { document.getElementById("fxaSaveChangeDeviceName").hidden = !editMode; }, - _focusComputerNameTextbox: function() { + _focusComputerNameTextbox() { let textbox = document.getElementById("fxaSyncComputerName"); let valLength = textbox.value.length; textbox.focus(); textbox.setSelectionRange(valLength, valLength); }, - _blurComputerNameTextbox: function() { + _blurComputerNameTextbox() { document.getElementById("fxaSyncComputerName").blur(); }, - _focusAfterComputerNameTextbox: function() { + _focusAfterComputerNameTextbox() { // Focus the most appropriate element that's *not* the "computer name" box. Services.focus.moveFocus(window, document.getElementById("fxaSyncComputerName"), Services.focus.MOVEFOCUS_FORWARD, 0); }, - _updateComputerNameValue: function(save) { + _updateComputerNameValue(save) { if (save) { let textbox = document.getElementById("fxaSyncComputerName"); Weave.Service.clientsEngine.localName = textbox.value; @@ -195,7 +195,7 @@ var gSyncPane = { this._populateComputerName(Weave.Service.clientsEngine.localName); }, - _setupEventListeners: function() { + _setupEventListeners() { function setEventListener(aId, aEventType, aCallback) { document.getElementById(aId) @@ -294,7 +294,7 @@ var gSyncPane = { }); }, - _initProfileImageUI: function() { + _initProfileImageUI() { try { if (Services.prefs.getBoolPref("identity.fxaccounts.profile_image.enabled")) { document.getElementById("fxaProfileImage").hidden = false; @@ -302,7 +302,7 @@ var gSyncPane = { } catch (e) { } }, - updateWeavePrefs: function() { + updateWeavePrefs() { let service = Components.classes["@mozilla.org/weave/service;1"] .getService(Components.interfaces.nsISupports) .wrappedJSObject; @@ -427,7 +427,7 @@ var gSyncPane = { } }, - startOver: function(showDialog) { + startOver(showDialog) { if (showDialog) { let flags = Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING + Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL + @@ -449,26 +449,26 @@ var gSyncPane = { this.updateWeavePrefs(); }, - updatePass: function() { + updatePass() { if (Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED) gSyncUtils.changePassword(); else gSyncUtils.updatePassphrase(); }, - resetPass: function() { + resetPass() { if (Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED) gSyncUtils.resetPassword(); else gSyncUtils.resetPassphrase(); }, - _getEntryPoint: function() { + _getEntryPoint() { let params = new URLSearchParams(document.URL.split("#")[0].split("?")[1] || ""); return params.get("entrypoint") || "preferences"; }, - _openAboutAccounts: function(action) { + _openAboutAccounts(action) { let entryPoint = this._getEntryPoint(); let params = new URLSearchParams(); if (action) { @@ -488,7 +488,7 @@ var gSyncPane = { * "pair" -- pair a device first * "reset" -- reset sync */ - openSetup: function(wizardType) { + openSetup(wizardType) { let service = Components.classes["@mozilla.org/weave/service;1"] .getService(Components.interfaces.nsISupports) .wrappedJSObject; @@ -507,7 +507,7 @@ var gSyncPane = { } }, - openContentInBrowser: function(url, options) { + openContentInBrowser(url, options) { let win = Services.wm.getMostRecentWindow("navigator:browser"); if (!win) { // no window to use, so use _openLink to create a new one. We don't @@ -530,20 +530,20 @@ var gSyncPane = { browser.loadURI(url); }, - signUp: function() { + signUp() { this._openAboutAccounts("signup"); }, - signIn: function() { + signIn() { this._openAboutAccounts("signin"); }, - reSignIn: function() { + reSignIn() { this._openAboutAccounts("reauth"); }, - clickOrSpaceOrEnterPressed: function(event) { + clickOrSpaceOrEnterPressed(event) { // Note: charCode is deprecated, but 'char' not yet implemented. // Replace charCode with char when implemented, see Bug 680830 return ((event.type == "click" && event.button == 0) || @@ -551,7 +551,7 @@ var gSyncPane = { (event.charCode == KeyEvent.DOM_VK_SPACE || event.keyCode == KeyEvent.DOM_VK_RETURN))); }, - openChangeProfileImage: function(event) { + openChangeProfileImage(event) { if (this.clickOrSpaceOrEnterPressed(event)) { fxAccounts.promiseAccountsChangeProfileURI(this._getEntryPoint(), "avatar") .then(url => { @@ -564,7 +564,7 @@ var gSyncPane = { } }, - openManageFirefoxAccount: function(event) { + openManageFirefoxAccount(event) { if (this.clickOrSpaceOrEnterPressed(event)) { this.manageFirefoxAccount(); // Prevent page from scrolling on the space key. @@ -572,7 +572,7 @@ var gSyncPane = { } }, - manageFirefoxAccount: function() { + manageFirefoxAccount() { fxAccounts.promiseAccountsManageURI(this._getEntryPoint()) .then(url => { this.openContentInBrowser(url, { @@ -581,7 +581,7 @@ var gSyncPane = { }); }, - verifyFirefoxAccount: function() { + verifyFirefoxAccount() { let showVerifyNotification = (data) => { let isError = !data; let maybeNot = isError ? "Not" : ""; @@ -609,12 +609,12 @@ var gSyncPane = { .then(onSuccess, onError); }, - openOldSyncSupportPage: function() { + openOldSyncSupportPage() { let url = Services.urlFormatter.formatURLPref("app.support.baseURL") + "old-sync"; this.openContentInBrowser(url); }, - unlinkFirefoxAccount: function(confirm) { + unlinkFirefoxAccount(confirm) { if (confirm) { // We use a string bundle shared with aboutAccounts. let sb = Services.strings.createBundle("chrome://browser/locale/syncSetup.properties"); @@ -646,7 +646,7 @@ var gSyncPane = { }); }, - openAddDevice: function() { + openAddDevice() { if (!Weave.Utils.ensureMPUnlocked()) return; @@ -658,7 +658,7 @@ var gSyncPane = { "syncAddDevice", "centerscreen,chrome,resizable=no"); }, - resetSync: function() { + resetSync() { this.openSetup("reset"); }, From 7255df4e9ac461c32b74615ed722403f4a6d6623 Mon Sep 17 00:00:00 2001 From: Jared Wein Date: Thu, 29 Dec 2016 15:20:47 -0500 Subject: [PATCH 087/229] Bug 1325464 - Enable object-shorthand rule and run 'mach eslint --fix' with the rule enabled. r=MattN MozReview-Commit-ID: 8WoGr8i6oCR --HG-- extra : rebase_source : da7172285d43b820421557ed3b05887e091ff939 --- .../base/content/aboutDialog-appUpdater.js | 28 +- .../content/aboutaccounts/aboutaccounts.js | 32 +- .../content/abouthealthreport/abouthealth.js | 34 +- browser/base/content/abouthome/aboutHome.js | 6 +- browser/base/content/browser-addons.js | 54 +-- browser/base/content/browser-ctrlTab.js | 14 +- browser/base/content/browser-customization.js | 10 +- .../browser-data-submission-info-bar.js | 10 +- browser/base/content/browser-devedition.js | 18 +- .../browser-fullScreenAndPointerLock.js | 72 +-- browser/base/content/browser-fullZoom.js | 10 +- browser/base/content/browser-fxaccounts.js | 30 +- .../base/content/browser-gestureSupport.js | 14 +- browser/base/content/browser-media.js | 16 +- browser/base/content/browser-places.js | 42 +- browser/base/content/browser-plugins.js | 44 +- .../base/content/browser-refreshblocker.js | 4 +- browser/base/content/browser-safebrowsing.js | 4 +- browser/base/content/browser-sidebar.js | 4 +- browser/base/content/browser-syncui.js | 16 +- .../content/browser-tabsintitlebar-stub.js | 6 +- .../base/content/browser-tabsintitlebar.js | 18 +- browser/base/content/browser.js | 356 +++++++------- browser/base/content/content.js | 98 ++-- browser/base/content/contentSearchUI.js | 86 ++-- browser/base/content/pageinfo/pageInfo.js | 78 +-- browser/base/content/pageinfo/permissions.js | 2 +- browser/base/content/pageinfo/security.js | 32 +- browser/base/content/sanitize.js | 8 +- browser/base/content/social-content.js | 2 +- browser/base/content/sync/aboutSyncTabs.js | 38 +- browser/base/content/sync/genericChange.js | 6 +- browser/base/content/sync/setup.js | 78 +-- browser/base/content/sync/utils.js | 22 +- browser/base/content/tab-content.js | 90 ++-- .../test/general/browser_aboutAccounts.js | 46 +- .../test/general/browser_aboutHealthReport.js | 2 +- .../content/test/general/browser_aboutHome.js | 6 +- .../test/general/browser_alltabslistener.js | 18 +- .../content/test/general/browser_blockHPKP.js | 2 +- .../content/test/general/browser_bug321000.js | 2 +- .../content/test/general/browser_bug356571.js | 6 +- .../content/test/general/browser_bug424101.js | 2 +- .../content/test/general/browser_bug553455.js | 10 +- .../content/test/general/browser_bug561636.js | 2 +- .../content/test/general/browser_bug592338.js | 2 +- .../content/test/general/browser_bug676619.js | 8 +- .../content/test/general/browser_bug734076.js | 18 +- .../test/general/browser_contentAltClick.js | 4 +- .../test/general/browser_contentAreaClick.js | 46 +- .../test/general/browser_contentSearchUI.js | 56 +-- .../test/general/browser_contextmenu.js | 8 +- .../test/general/browser_devedition.js | 2 +- .../general/browser_documentnavigation.js | 2 +- .../browser_domFullscreen_fullscreenMode.js | 2 +- .../general/browser_e10s_about_process.js | 10 +- .../general/browser_fullscreen-window-open.js | 32 +- .../content/test/general/browser_fxa_oauth.js | 12 +- .../test/general/browser_fxa_web_channel.js | 26 +- .../test/general/browser_fxaccounts.js | 6 +- .../test/general/browser_getshortcutoruri.js | 2 +- .../content/test/general/browser_homeDrop.js | 4 +- .../test/general/browser_keywordSearch.js | 2 +- .../test/general/browser_plainTextLinks.js | 2 +- .../test/general/browser_restore_isAppTab.js | 2 +- .../general/browser_sanitize-timespans.js | 14 +- .../test/general/browser_sanitizeDialog.js | 44 +- ...browser_save_link_when_window_navigates.js | 4 +- .../browser_save_private_link_perwindowpb.js | 6 +- .../content/test/general/browser_tabfocus.js | 6 +- .../test/general/browser_tabopen_reflows.js | 4 +- .../test/general/browser_trackingUI_4.js | 2 +- .../test/general/browser_trackingUI_6.js | 2 +- .../browser_viewSourceInTabOnViewSource.js | 2 +- .../test/general/browser_web_channel.js | 34 +- .../test/general/browser_windowactivation.js | 6 +- .../general/browser_windowopen_reflows.js | 4 +- .../content/test/general/contentSearchUI.js | 30 +- browser/base/content/test/general/head.js | 32 +- .../content/test/general/offlineByDefault.js | 4 +- .../test/general/parsingTestHelpers.jsm | 2 +- .../test/newtab/browser_newtab_bug722273.js | 6 +- .../test/newtab/browser_newtab_bug725996.js | 2 +- .../test/newtab/browser_newtab_bug991210.js | 4 +- .../test/newtab/browser_newtab_drag_drop.js | 2 +- .../test/newtab/browser_newtab_search.js | 4 +- browser/base/content/test/newtab/head.js | 4 +- .../content/test/plugins/blocklist_proxy.js | 20 +- .../content/test/plugins/browser_bug797677.js | 2 +- ...browser_pluginCrashReportNonDeterminism.js | 4 +- .../browser_popupNotification.js | 70 +-- .../browser_popupNotification_2.js | 50 +- .../browser_popupNotification_3.js | 48 +- .../browser_popupNotification_4.js | 42 +- .../browser_popupNotification_5.js | 48 +- .../browser_popupNotification_checkbox.js | 38 +- .../browser_popupNotification_no_anchors.js | 20 +- .../social/browser_aboutHome_activation.js | 2 +- .../content/test/social/browser_addons.js | 38 +- .../content/test/social/browser_blocklist.js | 18 +- .../base/content/test/social/browser_share.js | 12 +- .../test/social/browser_social_activation.js | 10 +- .../social/social_crash_content_helper.js | 4 +- browser/base/content/test/urlbar/Panel.jsm | 4 +- .../urlbar/browser_autocomplete_no_title.js | 2 +- ...rowser_autocomplete_tag_star_visibility.js | 2 +- .../content/test/urlbar/browser_bug556061.js | 16 +- .../content/test/urlbar/browser_bug623155.js | 4 +- .../test/urlbar/browser_search_favicon.js | 2 +- .../urlbar/browser_tabMatchesInAwesomebar.js | 10 +- .../test/urlbar/browser_urlbarAddonIframe.js | 14 +- .../test/urlbar/browser_urlbarCopying.js | 2 +- .../urlbar/browser_urlbarSearchTelemetry.js | 2 +- browser/base/content/test/urlbar/head.js | 6 +- .../content/test/urlbar/urlbarAddonIframe.js | 2 +- browser/base/content/utilityOverlay.js | 2 +- browser/base/content/web-panels.js | 12 +- browser/base/content/webrtcIndicator.js | 6 +- .../test/browser/browser_forgetaboutsite.js | 8 +- .../test/browser/browser_serviceworkers.js | 6 +- .../customizableui/CustomizableUI.jsm | 278 +++++------ .../customizableui/CustomizableWidgets.jsm | 82 ++-- .../customizableui/CustomizeMode.jsm | 160 +++---- .../customizableui/DragPositionManager.jsm | 34 +- .../customizableui/PanelWideWidgetTracker.jsm | 22 +- .../customizableui/ScrollbarSampler.jsm | 6 +- .../customizableui/content/panelUI.js | 46 +- .../browser_1003588_no_specials_in_panel.js | 2 +- .../test/browser_877006_missing_view.js | 2 +- ..._942581_unregisterArea_keeps_placements.js | 2 +- .../browser_947914_button_newPrivateWindow.js | 2 +- .../test/browser_947914_button_newWindow.js | 2 +- .../test/browser_973641_button_addon.js | 2 +- .../test/browser_976792_insertNodeInWindow.js | 24 +- .../browser_980155_add_overflow_toolbar.js | 2 +- ...r_981418-widget-onbeforecreated-handler.js | 4 +- .../test/browser_987492_window_api.js | 4 +- ...5164_registerArea_during_customize_mode.js | 8 +- .../migration/360seProfileMigrator.js | 2 +- .../migration/ChromeProfileMigrator.js | 8 +- browser/components/migration/ESEDBReader.jsm | 2 +- .../migration/EdgeProfileMigrator.js | 8 +- .../migration/FirefoxProfileMigrator.js | 6 +- .../components/migration/IEProfileMigrator.js | 16 +- .../components/migration/MSMigrationUtils.jsm | 2 +- .../components/migration/MigrationUtils.jsm | 1 - .../migration/SafariProfileMigrator.js | 8 +- .../components/migration/content/migration.js | 36 +- .../tests/unit/test_automigration.js | 20 +- browser/components/newtab/NewTabURL.jsm | 6 +- .../components/newtab/NewTabWebChannel.jsm | 2 +- browser/components/newtab/PlacesProvider.jsm | 2 +- browser/components/nsBrowserGlue.js | 74 +-- .../test/browser/browser_cache.js | 8 +- browser/components/places/PlacesUIUtils.jsm | 14 +- .../places/content/bookmarkProperties.js | 2 +- .../places/content/browserPlacesViews.js | 18 +- .../components/places/content/controller.js | 14 +- .../places/content/editBookmarkOverlay.js | 2 +- .../places/content/moveBookmarks.js | 2 +- browser/components/places/content/places.js | 6 +- browser/components/places/content/treeView.js | 22 +- .../places/tests/browser/browser_423515.js | 20 +- .../browser/browser_bookmarklet_windowOpen.js | 6 +- .../browser/browser_bookmarksProperties.js | 34 +- .../browser_drag_bookmarks_on_toolbar.js | 4 +- .../browser/browser_library_batch_delete.js | 6 +- .../browser/browser_library_downloads.js | 6 +- .../tests/browser/browser_library_infoBox.js | 2 +- .../browser_library_left_pane_fixnames.js | 2 +- .../browser/browser_library_middleclick.js | 22 +- .../browser_library_views_liveupdate.js | 12 +- .../browser/browser_sidebarpanels_click.js | 18 +- .../tests/browser/browser_views_liveupdate.js | 12 +- .../components/places/tests/browser/head.js | 6 +- .../places/tests/unit/test_421483.js | 2 +- .../tests/unit/test_PUIU_makeTransaction.js | 2 +- .../tests/unit/test_clearHistory_shutdown.js | 6 +- .../preferences/SiteDataManager.jsm | 10 +- browser/components/preferences/blocklists.js | 44 +- browser/components/preferences/connection.js | 26 +- browser/components/preferences/cookies.js | 122 ++--- browser/components/preferences/fonts.js | 10 +- .../tests/browser_advanced_siteData.js | 6 +- .../tests/browser_advanced_update.js | 8 +- .../tests/browser_basic_rebuild_fonts_test.js | 8 +- ...g1020245_openPreferences_to_paneContent.js | 2 +- .../tests/browser_cookies_exceptions.js | 36 +- .../preferences/in-content/tests/head.js | 2 +- browser/components/preferences/languages.js | 26 +- browser/components/preferences/permissions.js | 74 +-- browser/components/preferences/sanitize.js | 4 +- browser/components/preferences/translation.js | 56 +-- .../components/search/test/browser_426329.js | 8 +- .../search/test/browser_aboutSearchReset.js | 8 +- .../search/test/browser_abouthome_behavior.js | 8 +- .../search/test/browser_addEngine.js | 8 +- .../search/test/browser_amazon_behavior.js | 10 +- .../search/test/browser_bing_behavior.js | 10 +- .../search/test/browser_google_behavior.js | 10 +- .../test/browser_hiddenOneOffs_cleanup.js | 6 +- .../browser_searchbar_keyboard_navigation.js | 6 +- .../test/browser_searchbar_openpopup.js | 6 +- ...earchbar_smallpanel_keyboard_navigation.js | 6 +- .../components/search/test/browser_webapi.js | 2 +- .../search/test/browser_yahoo_behavior.js | 10 +- browser/components/search/test/head.js | 6 +- .../selfsupport/SelfSupportService.js | 16 +- .../shell/content/setDesktopBackground.js | 8 +- .../syncedtabs/SyncedTabsDeckComponent.js | 2 +- .../syncedtabs/SyncedTabsDeckStore.js | 2 +- .../syncedtabs/test/xpcshell/head.js | 6 +- .../tests/browser/browser_bug538331.js | 10 +- .../tests/unit/test_distribution.js | 2 +- .../components/translation/BingTranslator.jsm | 28 +- .../translation/LanguageDetector.jsm | 2 +- .../components/translation/Translation.jsm | 44 +- .../translation/TranslationContentHandler.jsm | 14 +- .../translation/TranslationDocument.jsm | 22 +- .../translation/YandexTranslator.jsm | 16 +- .../test/browser_translation_infobar.js | 8 +- .../test/browser_translation_telemetry.js | 8 +- browser/components/uitour/UITour-lib.js | 52 +- browser/components/uitour/UITour.jsm | 92 ++-- browser/components/uitour/content-UITour.js | 12 +- .../test/browser_UITour_defaultBrowser.js | 10 +- .../uitour/test/browser_UITour_heartbeat.js | 2 +- .../uitour/test/browser_UITour_modalDialog.js | 4 +- .../components/uitour/test/browser_no_tabs.js | 2 +- browser/experiments/Experiments.jsm | 118 ++--- browser/experiments/ExperimentsService.js | 6 +- .../test/xpcshell/test_activate.js | 2 +- browser/extensions/pocket/bootstrap.js | 38 +- .../extensions/pocket/content/AboutPocket.jsm | 10 +- browser/extensions/pocket/content/main.js | 56 +-- .../pocket/content/panels/js/messages.js | 10 +- .../pocket/content/panels/js/saved.js | 26 +- .../pocket/content/panels/js/signup.js | 10 +- browser/extensions/pocket/content/pktApi.jsm | 34 +- browser/extensions/pocket/test/head.js | 2 +- browser/extensions/presentation/bootstrap.js | 12 +- .../content/PresentationDevicePrompt.jsm | 6 +- browser/modules/AboutHome.jsm | 6 +- browser/modules/AboutNewTab.jsm | 6 +- browser/modules/BrowserUITelemetry.jsm | 72 +-- browser/modules/CastingApps.jsm | 32 +- browser/modules/ContentClick.jsm | 6 +- browser/modules/ContentCrashHandlers.jsm | 12 +- browser/modules/ContentLinkHandler.jsm | 8 +- browser/modules/ContentSearch.jsm | 56 +-- browser/modules/ContentWebRTC.jsm | 24 +- browser/modules/DirectoryLinksProvider.jsm | 24 +- browser/modules/E10SUtils.jsm | 12 +- browser/modules/Feeds.jsm | 2 +- browser/modules/FormSubmitObserver.jsm | 20 +- browser/modules/FormValidationHandler.jsm | 18 +- browser/modules/HiddenFrame.jsm | 8 +- browser/modules/NetworkPrioritizer.jsm | 2 +- browser/modules/PermissionUI.jsm | 4 +- browser/modules/PluginContent.jsm | 104 ++-- browser/modules/ProcessHangMonitor.jsm | 48 +- browser/modules/ReaderParent.jsm | 12 +- browser/modules/RemotePrompt.jsm | 8 +- browser/modules/SelfSupportBackend.jsm | 28 +- browser/modules/SitePermissions.jsm | 32 +- browser/modules/Social.jsm | 16 +- browser/modules/SocialService.jsm | 70 +-- browser/modules/TransientPrefs.jsm | 2 +- browser/modules/URLBarZoom.jsm | 2 +- browser/modules/Windows8WindowFrameColor.jsm | 2 +- browser/modules/WindowsJumpLists.jsm | 6 +- browser/modules/WindowsPreviewPerTab.jsm | 72 +-- browser/modules/offlineAppCache.jsm | 2 +- browser/modules/test/browser_ContentSearch.js | 8 +- browser/modules/test/browser_PermissionUI.js | 8 +- .../test/browser_ProcessHangNotifications.js | 12 +- browser/modules/test/contentSearch.js | 4 +- browser/modules/test/unit/social/head.js | 4 +- .../xpcshell/test_DirectoryLinksProvider.js | 14 +- browser/modules/webrtcUI.jsm | 44 +- .../mozscreenshots/extension/TestRunner.jsm | 2 +- .../extension/configurations/Buttons.jsm | 2 +- storage/test/unit/head_storage.js | 12 +- toolkit/.eslintrc.js | 3 + .../content/aboutCheckerboard.js | 2 +- .../aboutmemory/content/aboutMemory.js | 20 +- .../content/aboutPerformance.js | 48 +- .../components/addoncompat/CompatWarning.jsm | 4 +- toolkit/components/addoncompat/Prefetcher.jsm | 18 +- .../addoncompat/RemoteAddonsChild.jsm | 100 ++-- .../addoncompat/RemoteAddonsParent.jsm | 92 ++-- toolkit/components/addoncompat/ShimWaiver.jsm | 2 +- .../components/addoncompat/defaultShims.js | 6 +- .../addoncompat/multiprocessShims.js | 8 +- .../addoncompat/tests/addon/bootstrap.js | 22 +- .../tests/browser/browser_addonShims.js | 8 +- .../asyncshutdown/AsyncShutdown.jsm | 48 +- .../asyncshutdown/nsAsyncShutdown.js | 28 +- .../asyncshutdown/tests/xpcshell/head.js | 20 +- .../test_AsyncShutdown_leave_uncaught.js | 2 +- .../tests/unit/head_autocomplete.js | 28 +- .../autocomplete/tests/unit/test_330578.js | 2 +- .../autocomplete/tests/unit/test_378079.js | 38 +- .../autocomplete/tests/unit/test_393191.js | 38 +- .../autocomplete/tests/unit/test_440866.js | 38 +- .../tests/unit/test_autocomplete_multiple.js | 38 +- .../tests/unit/test_previousResult.js | 38 +- .../tests/unit/test_stopSearch.js | 20 +- .../components/captivedetect/captivedetect.js | 8 +- .../contentprefs/ContentPrefService2.jsm | 2 +- .../contentprefs/ContentPrefServiceChild.jsm | 52 +- .../contentprefs/ContentPrefServiceParent.jsm | 30 +- .../contentprefs/nsContentPrefService.js | 12 +- .../contentprefs/tests/unit/test_bug679784.js | 4 +- .../tests/unit/test_getPrefAsync.js | 2 +- .../contentprefs/tests/unit_cps2/head.js | 22 +- .../tests/unit_cps2/test_setGet.js | 6 +- toolkit/components/crashes/CrashManager.jsm | 76 +-- .../components/crashes/CrashManagerTest.jsm | 8 +- toolkit/components/crashes/CrashService.js | 4 +- .../components/crashmonitor/CrashMonitor.jsm | 6 +- .../components/crashmonitor/nsCrashMonitor.js | 2 +- .../chrome/xpcshellTestHarnessAdaptor.js | 4 +- toolkit/components/ctypes/tests/unit/head.js | 2 +- .../ctypes/tests/unit/test_finalizer.js | 38 +- .../ctypes/tests/unit/test_jsctypes.js | 34 +- .../test/unit/test_app_rep_windows.js | 4 +- .../test/xpcshell/test_ext_storage_sync.js | 1 - .../components/exthelper/extApplication.js | 2 +- toolkit/components/feeds/test/test_xml.js | 2 +- .../filepicker/content/filepicker.js | 4 +- toolkit/components/filepicker/nsFilePicker.js | 16 +- .../filepicker/test/unit/test_filecomplete.js | 2 +- .../FormAutofillContentService.js | 12 +- .../formautofill/FormAutofillStartup.js | 4 +- .../content/RequestAutocompleteUI.jsm | 2 +- .../content/requestAutocomplete.js | 8 +- .../formautofill/test/chrome/loader.js | 2 +- .../formautofill/test/head_common.js | 10 +- .../formautofill/test/loader_common.js | 4 +- toolkit/components/gfx/SanityTest.js | 12 +- .../components/gfx/content/gfxFrameScript.js | 8 +- .../jsdownloads/src/DownloadCore.jsm | 78 +-- .../jsdownloads/src/DownloadImport.jsm | 8 +- .../jsdownloads/src/DownloadLegacy.js | 16 +- .../jsdownloads/src/DownloadList.jsm | 26 +- .../jsdownloads/src/DownloadUIHelper.jsm | 4 +- .../components/jsdownloads/src/Downloads.jsm | 6 +- .../test/unit/common_test_Download.js | 16 +- .../components/jsdownloads/test/unit/head.js | 30 +- .../test/unit/test_DownloadImport.js | 6 +- .../test/unit/test_DownloadList.js | 22 +- toolkit/components/lz4/lz4.js | 4 +- .../test/unit/test_mediasniffer.js | 8 +- .../test/unit/test_mediasniffer_ext.js | 6 +- .../microformats/microformat-shiv.js | 248 +++++----- .../components/narrate/NarrateControls.jsm | 20 +- toolkit/components/narrate/Narrator.jsm | 32 +- toolkit/components/narrate/VoiceSelect.jsm | 22 +- .../narrate/test/NarrateTestUtils.jsm | 26 +- .../components/passwordmgr/LoginHelper.jsm | 2 +- .../components/passwordmgr/LoginImport.jsm | 26 +- .../passwordmgr/LoginManagerContent.jsm | 24 +- .../passwordmgr/LoginManagerContextMenu.jsm | 6 +- .../passwordmgr/LoginManagerParent.jsm | 18 +- .../passwordmgr/content/passwordManager.js | 2 +- toolkit/components/passwordmgr/crypto-SDR.js | 10 +- toolkit/components/passwordmgr/nsLoginInfo.js | 6 +- .../passwordmgr/nsLoginManagerPrompter.js | 76 +-- .../components/passwordmgr/storage-json.js | 14 +- .../passwordmgr/storage-mozStorage.js | 90 ++-- .../browser/browser_passwordmgr_observers.js | 2 +- .../browser/browser_passwordmgr_switchtab.js | 4 +- .../passwordmgr/test/prompt_common.js | 4 +- .../test/unit/test_notifications.js | 2 +- .../passwordmgr/test/unit/test_storage.js | 2 +- .../unit/test_user_autocomplete_result.js | 32 +- .../perfmonitoring/AddonWatcher.jsm | 12 +- .../perfmonitoring/PerformanceStats.jsm | 82 ++-- .../perfmonitoring/PerformanceWatcher.jsm | 18 +- .../tests/browser/browser_compartments.js | 8 +- .../perfmonitoring/tests/browser/head.js | 8 +- .../components/places/BookmarkHTMLUtils.jsm | 16 +- .../components/places/BookmarkJSONUtils.jsm | 8 +- toolkit/components/places/Bookmarks.jsm | 8 +- toolkit/components/places/ClusterLib.js | 2 +- toolkit/components/places/ColorAnalyzer.js | 2 +- .../components/places/ColorAnalyzer_worker.js | 10 +- toolkit/components/places/History.jsm | 16 +- toolkit/components/places/PlacesBackups.jsm | 4 +- toolkit/components/places/PlacesDBUtils.jsm | 28 +- .../PlacesSearchAutocompleteProvider.jsm | 12 +- .../components/places/PlacesTransactions.jsm | 48 +- toolkit/components/places/PlacesUtils.jsm | 46 +- toolkit/components/places/UnifiedComplete.js | 52 +- .../components/places/nsLivemarkService.js | 2 +- .../components/places/nsPlacesExpiration.js | 16 +- toolkit/components/places/nsTaggingService.js | 6 +- .../test_1017502-bookmarks_foreign_count.js | 2 +- .../places/tests/bookmarks/test_393498.js | 4 +- .../bookmarks/test_405938_restore_queries.js | 2 +- .../test_424958-json-quoted-folders.js | 6 +- .../places/tests/bookmarks/test_448584.js | 6 +- .../places/tests/bookmarks/test_458683.js | 6 +- .../places/tests/bookmarks/test_675416.js | 2 +- .../places/tests/bookmarks/test_711914.js | 2 +- .../tests/bookmarks/test_async_observers.js | 18 +- .../places/tests/bookmarks/test_bookmarks.js | 14 +- .../tests/bookmarks/test_bookmarks_insert.js | 6 +- .../bookmarks/test_bookmarks_notifications.js | 2 +- .../places/tests/bookmarks/test_keywords.js | 2 +- .../bookmarks/test_nsINavBookmarkObserver.js | 8 +- .../places/tests/browser/browser_bug399606.js | 16 +- .../places/tests/browser/browser_bug646422.js | 16 +- .../tests/browser/browser_double_redirect.js | 2 +- .../places/tests/browser/browser_notfound.js | 16 +- .../places/tests/browser/browser_redirect.js | 16 +- .../places/tests/browser/browser_settitle.js | 16 +- .../tests/browser/browser_visited_notfound.js | 2 +- ...er_visituri_privatebrowsing_perwindowpb.js | 2 +- .../components/places/tests/browser/head.js | 24 +- .../tests/expiration/test_analyze_runs.js | 2 +- .../expiration/test_annos_expire_session.js | 6 +- .../tests/expiration/test_notifications.js | 2 +- .../test_notifications_onDeleteURI.js | 12 +- .../test_notifications_onDeleteVisits.js | 12 +- .../tests/expiration/test_outdated_analyze.js | 6 +- .../tests/expiration/test_pref_maxpages.js | 12 +- .../test_moz-anno_favicon_mime_type.js | 6 +- .../components/places/tests/head_common.js | 62 +-- .../places/tests/history/test_insert.js | 2 +- .../places/tests/history/test_remove.js | 50 +- .../history/test_removeVisitsByFilter.js | 26 +- .../migration/test_current_from_downgraded.js | 2 +- .../tests/migration/test_current_from_v19.js | 2 +- .../places/tests/queries/test_async.js | 34 +- .../test_history_queries_titles_liveUpdate.js | 24 +- .../tests/queries/test_querySerialization.js | 8 +- .../places/tests/queries/test_sorting.js | 56 +-- .../unifiedcomplete/head_autocomplete.js | 10 +- .../tests/unifiedcomplete/test_416211.js | 6 +- .../test_avoid_stripping_to_empty_tokens.js | 2 +- .../tests/unifiedcomplete/test_enabled.js | 6 +- .../test_remote_tab_matches.js | 2 +- .../test_search_engine_host.js | 2 +- .../places/tests/unit/nsDummyObserver.js | 26 +- .../places/tests/unit/test_000_frecency.js | 14 +- .../places/tests/unit/test_405497.js | 2 +- .../places/tests/unit/test_408221.js | 14 +- .../places/tests/unit/test_413784.js | 14 +- .../unit/test_418643_removeFolderChildren.js | 4 +- .../places/tests/unit/test_452777.js | 2 +- .../places/tests/unit/test_454977.js | 2 +- .../places/tests/unit/test_463863.js | 2 +- .../unit/test_PlacesUtils_lazyobservers.js | 14 +- .../places/tests/unit/test_adaptive.js | 14 +- .../tests/unit/test_adaptive_bug527311.js | 12 +- .../places/tests/unit/test_analyze.js | 6 +- .../places/tests/unit/test_annotations.js | 8 +- .../unit/test_asyncExecuteLegacyQueries.js | 14 +- .../tests/unit/test_async_history_api.js | 4 +- .../tests/unit/test_async_transactions.js | 26 +- .../places/tests/unit/test_bookmarks_html.js | 2 +- .../places/tests/unit/test_bookmarks_json.js | 2 +- .../test_bookmarks_restore_notification.js | 2 +- .../places/tests/unit/test_browserhistory.js | 8 +- .../places/tests/unit/test_childlessTags.js | 4 +- .../tests/unit/test_download_history.js | 20 +- .../places/tests/unit/test_frecency.js | 14 +- .../unit/test_history_autocomplete_tags.js | 14 +- .../places/tests/unit/test_history_clear.js | 16 +- .../tests/unit/test_history_observer.js | 20 +- .../places/tests/unit/test_isURIVisited.js | 8 +- .../places/tests/unit/test_isvisited.js | 8 +- .../places/tests/unit/test_keywords.js | 2 +- .../places/tests/unit/test_markpageas.js | 2 +- .../tests/unit/test_nsINavHistoryViewer.js | 34 +- .../tests/unit/test_onItemChanged_tags.js | 14 +- .../places/tests/unit/test_placesTxn.js | 16 +- .../tests/unit/test_preventive_maintenance.js | 108 ++--- .../tests/unit/test_sql_guid_functions.js | 4 +- .../unit/test_tag_autocomplete_search.js | 14 +- .../printing/content/printPreviewProgress.js | 12 +- .../printing/content/printProgress.js | 12 +- .../components/printing/content/printUtils.js | 32 +- .../printing/content/printdialog.js | 6 +- .../printing/content/printjoboptions.js | 6 +- ...vateBrowsingTrackingProtectionWhitelist.js | 2 +- .../ContentProcessSingleton.js | 4 +- .../processsingleton/MainProcessSingleton.js | 6 +- .../promiseworker/PromiseWorker.jsm | 24 +- .../tests/xpcshell/data/worker.js | 4 +- .../promiseworker/worker/PromiseWorker.js | 16 +- .../components/prompts/src/CommonDialog.jsm | 22 +- .../prompts/src/SharedPromptUtils.jsm | 18 +- toolkit/components/prompts/src/nsPrompter.js | 136 +++--- .../components/prompts/test/chromeScript.js | 2 +- .../components/prompts/test/prompt_common.js | 2 +- toolkit/components/reader/AboutReader.jsm | 78 +-- toolkit/components/reader/ReaderMode.jsm | 28 +- toolkit/components/reader/ReaderWorker.js | 2 +- .../remotebrowserutils/RemoteWebNavigation.js | 20 +- .../components/satchel/AutoCompletePopup.jsm | 22 +- toolkit/components/satchel/FormHistory.jsm | 40 +- .../components/satchel/FormHistoryStartup.js | 6 +- .../components/satchel/formSubmitListener.js | 16 +- .../components/satchel/nsFormAutoComplete.js | 30 +- .../satchel/nsFormAutoCompleteResult.jsm | 16 +- toolkit/components/satchel/nsFormHistory.js | 62 +-- .../satchel/nsInputListAutoComplete.js | 4 +- .../components/satchel/test/parent_utils.js | 4 +- .../components/satchel/test/satchel_common.js | 6 +- .../satchel/test/unit/head_satchel.js | 16 +- .../satchel/test/unit/test_async_expire.js | 4 +- .../satchel/test/unit/test_autocomplete.js | 20 +- .../satchel/test/unit/test_db_corrupt.js | 8 +- .../satchel/test/unit/test_history_api.js | 34 +- .../satchel/test/unit/test_notify.js | 6 +- .../satchel/test/unit/test_previous_result.js | 4 +- .../components/search/SearchStaticData.jsm | 2 +- .../search/SearchSuggestionController.jsm | 16 +- toolkit/components/search/nsSearchService.js | 26 +- .../components/search/nsSearchSuggestions.js | 12 +- toolkit/components/search/nsSidebar.js | 8 +- .../search/tests/xpcshell/head_search.js | 6 +- .../tests/xpcshell/test_addEngine_callback.js | 16 +- .../xpcshell/test_location_malformed_json.js | 2 +- .../tests/xpcshell/test_location_sync.js | 2 +- .../tests/xpcshell/test_searchSuggest.js | 6 +- .../securityreporter/SecurityReporter.js | 6 +- toolkit/components/sqlite/sqlite_internal.js | 4 +- .../startup/tests/unit/head_startup.js | 2 +- .../components/telemetry/TelemetryArchive.jsm | 14 +- .../telemetry/TelemetryController.jsm | 64 +-- .../telemetry/TelemetryEnvironment.jsm | 106 ++--- toolkit/components/telemetry/TelemetryLog.jsm | 4 +- .../telemetry/TelemetryReportingPolicy.jsm | 34 +- .../components/telemetry/TelemetrySend.jsm | 78 +-- .../components/telemetry/TelemetrySession.jsm | 102 ++-- .../telemetry/TelemetryStopwatch.jsm | 34 +- .../components/telemetry/TelemetryStorage.jsm | 108 ++--- .../components/telemetry/TelemetryUtils.jsm | 16 +- .../telemetry/ThirdPartyCookieProbe.jsm | 12 +- toolkit/components/telemetry/UITelemetry.jsm | 22 +- .../tests/unit/TelemetryArchiveTesting.jsm | 6 +- .../components/telemetry/tests/unit/head.js | 18 +- .../tests/unit/test_TelemetryEnvironment.js | 12 +- .../thumbnails/BackgroundPageThumbs.jsm | 26 +- .../components/thumbnails/PageThumbUtils.jsm | 14 +- toolkit/components/thumbnails/PageThumbs.jsm | 22 +- .../content/backgroundPageThumbsContent.js | 16 +- toolkit/components/thumbnails/test/head.js | 4 +- .../test/thumbnails_crash_content_helper.js | 4 +- .../timermanager/nsUpdateTimerManager.js | 10 +- .../components/viewconfig/content/config.js | 56 +-- .../viewsource/content/viewSource-content.js | 4 +- .../viewsource/content/viewSource.js | 2 +- .../viewsource/content/viewSourceUtils.js | 36 +- .../test/browser/browser_contextmenu.js | 2 +- .../viewsource/test/browser/head.js | 2 +- toolkit/components/workerloader/require.js | 8 +- .../workerloader/tests/utils_worker.js | 4 +- toolkit/components/xulstore/XULStore.js | 28 +- toolkit/content/aboutProfiles.js | 2 +- toolkit/content/aboutServiceWorkers.js | 4 +- toolkit/content/aboutSupport.js | 16 +- toolkit/content/aboutTelemetry.js | 90 ++-- toolkit/content/aboutwebrtc/aboutWebrtc.js | 70 +-- toolkit/content/browser-child.js | 42 +- toolkit/content/browser-content.js | 98 ++-- toolkit/content/contentAreaUtils.js | 30 +- toolkit/content/findUtils.js | 4 +- toolkit/content/finddialog.js | 2 +- .../tests/browser/browser_bug1170531.js | 2 +- .../browser_bug295977_autoscroll_overflow.js | 4 +- .../browser/browser_content_url_annotation.js | 2 +- .../tests/browser/browser_isSynthetic.js | 4 +- .../tests/browser/common/mockTransfer.js | 16 +- .../file_autocomplete_with_composition.js | 74 +-- toolkit/content/tests/chrome/popup_trigger.js | 242 +++++----- .../chrome/content/TileManager.js | 2 +- .../chrome/content/WidgetStack.js | 74 +-- .../chrome/content/overlay.js | 4 +- toolkit/content/tests/widgets/tree_shared.js | 34 +- toolkit/content/treeUtils.js | 6 +- toolkit/crashreporter/CrashReports.jsm | 2 +- toolkit/crashreporter/content/crashes.js | 4 +- .../test/browser/browser_bug471404.js | 6 +- .../test/browser/browser_clearReports.js | 2 +- toolkit/crashreporter/test/browser/head.js | 4 +- .../unit/test_crash_with_memory_report.js | 4 +- toolkit/forgetaboutsite/ForgetAboutSite.jsm | 2 +- .../test/unit/test_removeDataFromDomain.js | 4 +- toolkit/identity/Identity.jsm | 2 +- toolkit/identity/IdentityProvider.jsm | 2 +- toolkit/identity/MinimalIdentity.jsm | 2 +- toolkit/identity/RelyingParty.jsm | 8 +- toolkit/identity/jwcrypto.jsm | 8 +- toolkit/identity/tests/unit/head_identity.js | 8 +- .../tests/unit/test_authentication.js | 6 +- .../tests/unit/test_firefox_accounts.js | 6 +- toolkit/identity/tests/unit/test_jwcrypto.js | 12 +- toolkit/identity/tests/unit/test_log_utils.js | 2 +- .../identity/tests/unit/test_provisioning.js | 20 +- toolkit/modules/Battery.jsm | 4 +- toolkit/modules/BinarySearch.jsm | 6 +- toolkit/modules/BrowserUtils.jsm | 30 +- toolkit/modules/CertUtils.jsm | 6 +- toolkit/modules/CharsetMenu.jsm | 22 +- toolkit/modules/ClientID.jsm | 14 +- toolkit/modules/Console.jsm | 6 +- toolkit/modules/DateTimePickerHelper.jsm | 18 +- toolkit/modules/DeferredTask.jsm | 10 +- toolkit/modules/Deprecated.jsm | 2 +- toolkit/modules/Finder.jsm | 48 +- toolkit/modules/FinderHighlighter.jsm | 8 +- toolkit/modules/FinderIterator.jsm | 4 +- toolkit/modules/GMPInstallManager.jsm | 28 +- toolkit/modules/GMPUtils.jsm | 20 +- toolkit/modules/Geometry.jsm | 20 +- toolkit/modules/InlineSpellChecker.jsm | 34 +- toolkit/modules/InlineSpellCheckerContent.jsm | 2 +- toolkit/modules/Integration.jsm | 2 +- toolkit/modules/LightweightThemeConsumer.jsm | 14 +- toolkit/modules/Log.jsm | 74 +-- toolkit/modules/NewTabUtils.jsm | 44 +- toolkit/modules/ObjectUtils.jsm | 6 +- toolkit/modules/PageMenu.jsm | 24 +- toolkit/modules/PageMetadata.jsm | 2 +- toolkit/modules/PermissionsUtils.jsm | 2 +- toolkit/modules/PopupNotifications.jsm | 12 +- toolkit/modules/Preferences.jsm | 2 +- toolkit/modules/PrivateBrowsingUtils.jsm | 2 +- toolkit/modules/ProfileAge.jsm | 14 +- toolkit/modules/Promise-backend.js | 34 +- toolkit/modules/PromiseUtils.jsm | 2 +- toolkit/modules/PropertyListUtils.jsm | 8 +- toolkit/modules/RemoteController.jsm | 16 +- toolkit/modules/RemoteFinder.jsm | 46 +- toolkit/modules/RemotePageManager.jsm | 58 +-- toolkit/modules/RemoteSecurityUI.jsm | 2 +- toolkit/modules/RemoteWebProgress.jsm | 18 +- toolkit/modules/ResetProfile.jsm | 4 +- toolkit/modules/SelectContentHelper.jsm | 22 +- toolkit/modules/SelectParentHelper.jsm | 14 +- toolkit/modules/SessionRecorder.jsm | 30 +- toolkit/modules/ShortcutUtils.jsm | 4 +- toolkit/modules/SpatialNavigation.jsm | 6 +- toolkit/modules/Sqlite.jsm | 68 +-- toolkit/modules/Task.jsm | 2 +- toolkit/modules/WebChannel.jsm | 22 +- toolkit/modules/WindowDraggingUtils.jsm | 8 +- toolkit/modules/WindowsRegistry.jsm | 4 +- toolkit/modules/secondscreen/RokuApp.jsm | 6 +- .../secondscreen/SimpleServiceDiscovery.jsm | 26 +- toolkit/modules/sessionstore/FormData.jsm | 16 +- .../modules/sessionstore/ScrollPosition.jsm | 6 +- toolkit/modules/sessionstore/Utils.jsm | 8 +- .../tests/browser/browser_Deprecated.js | 12 +- .../modules/tests/browser/browser_Finder.js | 4 +- .../browser/browser_FinderHighlighter.js | 2 +- .../browser/browser_Finder_hidden_textarea.js | 2 +- .../modules/tests/browser/browser_Geometry.js | 8 +- .../browser/browser_InlineSpellChecker.js | 2 +- .../tests/xpcshell/test_GMPInstallManager.js | 20 +- toolkit/modules/tests/xpcshell/test_Http.js | 28 +- toolkit/modules/tests/xpcshell/test_Log.js | 2 +- .../tests/xpcshell/test_NewTabUtils.js | 10 +- .../tests/xpcshell/test_ObjectUtils.js | 2 +- .../tests/xpcshell/test_Preferences.js | 4 +- .../modules/tests/xpcshell/test_Promise.js | 2 +- .../modules/tests/xpcshell/test_client_id.js | 4 +- .../tests/xpcshell/test_session_recorder.js | 2 +- toolkit/modules/tests/xpcshell/test_sqlite.js | 30 +- .../tests/xpcshell/test_sqlite_shutdown.js | 4 +- .../tests/xpcshell/test_web_channel.js | 4 +- .../tests/xpcshell/test_web_channel_broker.js | 2 +- toolkit/mozapps/downloads/DownloadLastDir.jsm | 16 +- toolkit/mozapps/extensions/AddonManager.jsm | 246 +++++----- .../extensions/ChromeManifestParser.jsm | 10 +- toolkit/mozapps/extensions/DeferredSave.jsm | 12 +- .../extensions/LightweightThemeManager.jsm | 50 +- toolkit/mozapps/extensions/addonManager.js | 28 +- .../mozapps/extensions/amContentHandler.js | 6 +- .../mozapps/extensions/amInstallTrigger.js | 24 +- .../extensions/amWebInstallListener.js | 28 +- .../mozapps/extensions/content/extensions.js | 444 +++++++++--------- .../mozapps/extensions/content/newaddon.js | 2 +- toolkit/mozapps/extensions/content/update.js | 70 +-- .../extensions/content/xpinstallConfirm.js | 2 +- .../extensions/internal/AddonLogging.jsm | 12 +- .../extensions/internal/AddonRepository.jsm | 104 ++-- .../AddonRepository_SQLiteMigrator.jsm | 40 +- .../extensions/internal/AddonTestUtils.jsm | 12 +- .../internal/AddonUpdateChecker.jsm | 28 +- .../extensions/internal/GMPProvider.jsm | 38 +- .../LightweightThemeImageOptimizer.jsm | 16 +- .../extensions/internal/PluginProvider.jsm | 26 +- .../internal/ProductAddonChecker.jsm | 29 +- .../extensions/internal/XPIProvider.jsm | 254 +++++----- .../extensions/internal/XPIProviderUtils.js | 74 +-- .../mozapps/extensions/nsBlocklistService.js | 76 +-- .../extensions/nsBlocklistServiceContent.js | 22 +- .../extensions/test/AddonManagerTesting.jsm | 14 +- .../browser_addonrepository_performance.js | 2 +- .../test/browser/browser_bug557956.js | 2 +- .../test/browser/browser_bug562797.js | 10 +- .../test/browser/browser_bug562992.js | 2 +- .../test/browser/browser_bug567127.js | 10 +- .../test/browser/browser_bug572561.js | 8 +- .../test/browser/browser_bug577990.js | 2 +- .../test/browser/browser_bug586574.js | 4 +- .../test/browser/browser_bug587970.js | 4 +- .../test/browser/browser_bug591663.js | 12 +- .../test/browser/browser_bug593535.js | 4 +- .../test/browser/browser_bug596336.js | 2 +- .../test/browser/browser_bug608316.js | 2 +- .../test/browser/browser_cancelCompatCheck.js | 4 +- .../test/browser/browser_discovery.js | 10 +- .../test/browser/browser_dragdrop.js | 10 +- .../extensions/test/browser/browser_eula.js | 2 +- .../test/browser/browser_gmpProvider.js | 2 +- .../test/browser/browser_inlinesettings.js | 12 +- .../browser/browser_inlinesettings_custom.js | 2 +- .../browser/browser_inlinesettings_info.js | 12 +- .../test/browser/browser_install.js | 12 +- .../test/browser/browser_installssl.js | 4 +- .../test/browser/browser_manualupdates.js | 4 +- .../test/browser/browser_searching.js | 10 +- .../test/browser/browser_updatessl.js | 6 +- .../test/browser/browser_webapi_install.js | 2 +- .../mozapps/extensions/test/browser/head.js | 50 +- .../extensions/test/xpcshell/head_addons.js | 40 +- .../test/xpcshell/test_AddonRepository.js | 36 +- .../test_AddonRepository_compatmode.js | 12 +- .../test/xpcshell/test_DeferredSave.js | 8 +- .../test/xpcshell/test_XPIcancel.js | 6 +- .../test/xpcshell/test_backgroundupdate.js | 4 +- .../test/xpcshell/test_badschema.js | 4 +- .../test_blocklist_metadata_filters.js | 4 +- .../test/xpcshell/test_blocklist_prefs.js | 4 +- .../test/xpcshell/test_blocklist_regexp.js | 4 +- .../test/xpcshell/test_blocklistchange.js | 12 +- .../test/xpcshell/test_bug1180901_2.js | 4 +- .../test/xpcshell/test_bug299716_2.js | 2 +- .../test/xpcshell/test_bug335238.js | 14 +- .../test/xpcshell/test_bug384052.js | 10 +- .../test/xpcshell/test_bug393285.js | 4 +- .../test/xpcshell/test_bug406118.js | 4 +- .../test/xpcshell/test_bug424262.js | 4 +- .../test/xpcshell/test_bug430120.js | 6 +- .../test/xpcshell/test_bug449027.js | 8 +- .../test/xpcshell/test_bug455906.js | 8 +- .../test/xpcshell/test_bug465190.js | 4 +- .../test/xpcshell/test_bug514327_3.js | 8 +- .../test/xpcshell/test_bug542391.js | 6 +- .../test/xpcshell/test_bug554133.js | 4 +- .../test/xpcshell/test_bug594058.js | 6 +- .../test/xpcshell/test_bug655254.js | 4 +- .../test/xpcshell/test_bug757663.js | 12 +- .../test/xpcshell/test_cache_certdb.js | 2 +- .../test/xpcshell/test_cacheflush.js | 6 +- .../extensions/test/xpcshell/test_corrupt.js | 4 +- .../xpcshell/test_corrupt_strictcompat.js | 4 +- .../extensions/test/xpcshell/test_dss.js | 2 +- .../test/xpcshell/test_duplicateplugins.js | 4 +- .../extensions/test/xpcshell/test_hotfix.js | 8 +- .../extensions/test/xpcshell/test_install.js | 40 +- .../xpcshell/test_install_strictcompat.js | 40 +- .../test/xpcshell/test_json_updatecheck.js | 4 +- .../extensions/test/xpcshell/test_locked.js | 4 +- .../test/xpcshell/test_locked_strictcompat.js | 4 +- .../test/xpcshell/test_mapURIToAddonID.js | 10 +- .../test/xpcshell/test_metadata_update.js | 4 +- .../extensions/test/xpcshell/test_migrate4.js | 4 +- .../test/xpcshell/test_pluginchange.js | 4 +- .../test/xpcshell/test_pref_properties.js | 8 +- .../test/xpcshell/test_signed_migrate.js | 4 +- .../test/xpcshell/test_softblocked.js | 4 +- .../extensions/test/xpcshell/test_startup.js | 2 +- .../test/xpcshell/test_system_update.js | 8 +- .../extensions/test/xpcshell/test_theme.js | 4 +- .../extensions/test/xpcshell/test_types.js | 4 +- .../extensions/test/xpcshell/test_update.js | 118 ++--- .../test/xpcshell/test_updateCancel.js | 4 +- .../test/xpcshell/test_update_compatmode.js | 30 +- .../test/xpcshell/test_update_ignorecompat.js | 10 +- .../test/xpcshell/test_update_strictcompat.js | 102 ++-- .../test/xpcshell/test_updatecheck.js | 2 +- .../test/xpcshell/test_webextension.js | 4 +- .../xpcshell/test_webextension_install.js | 8 +- .../xpinstall/browser_amosigned_trigger.js | 2 +- .../browser_amosigned_trigger_iframe.js | 2 +- .../test/xpinstall/browser_badhash.js | 2 +- .../test/xpinstall/browser_badhashtype.js | 2 +- .../test/xpinstall/browser_bug638292.js | 2 +- .../xpinstall/browser_concurrent_installs.js | 6 +- .../extensions/test/xpinstall/browser_hash.js | 2 +- .../test/xpinstall/browser_hash2.js | 2 +- .../test/xpinstall/browser_httphash.js | 2 +- .../test/xpinstall/browser_httphash2.js | 2 +- .../test/xpinstall/browser_httphash3.js | 2 +- .../test/xpinstall/browser_httphash4.js | 2 +- .../test/xpinstall/browser_httphash5.js | 2 +- .../test/xpinstall/browser_httphash6.js | 2 +- .../test/xpinstall/browser_relative.js | 2 +- .../test/xpinstall/browser_switchtab.js | 2 +- .../xpinstall/browser_unsigned_trigger.js | 2 +- .../browser_unsigned_trigger_iframe.js | 2 +- .../browser_unsigned_trigger_xorigin.js | 2 +- .../mozapps/extensions/test/xpinstall/head.js | 44 +- toolkit/mozapps/preferences/fontbuilder.js | 2 +- toolkit/mozapps/preferences/removemp.js | 6 +- toolkit/mozapps/update/content/history.js | 4 +- toolkit/mozapps/update/content/updates.js | 94 ++-- toolkit/mozapps/update/nsUpdateService.js | 8 +- toolkit/mozapps/update/nsUpdateServiceStub.js | 2 +- toolkit/mozapps/update/tests/chrome/utils.js | 2 +- toolkit/mozapps/update/tests/data/shared.js | 2 +- .../update/tests/data/xpcshellUtilsAUS.js | 6 +- .../downloadInterruptedRecovery.js | 10 +- .../tests/unit_aus_update/uiAutoPref.js | 4 +- .../tests/unit_aus_update/uiSilentPref.js | 4 +- .../uiUnsupportedAlreadyNotified.js | 4 +- 824 files changed, 7774 insertions(+), 7790 deletions(-) diff --git a/browser/base/content/aboutDialog-appUpdater.js b/browser/base/content/aboutDialog-appUpdater.js index f78d2366f689..06fe9e18ce3b 100644 --- a/browser/base/content/aboutDialog-appUpdater.js +++ b/browser/base/content/aboutDialog-appUpdater.js @@ -168,7 +168,7 @@ appUpdater.prototype = * @param aChildID * The id of the deck's child to select, e.g. "apply". */ - selectPanel: function(aChildID) { + selectPanel(aChildID) { let panel = document.getElementById(aChildID); let button = panel.querySelector("button"); @@ -191,7 +191,7 @@ appUpdater.prototype = /** * Check for updates */ - checkForUpdates: function() { + checkForUpdates() { // Clear prefs that could prevent a user from discovering available updates. if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_CANCELATIONS_OSX)) { Services.prefs.clearUserPref(PREF_APP_UPDATE_CANCELATIONS_OSX); @@ -209,7 +209,7 @@ appUpdater.prototype = * Handles oncommand for the "Restart to Update" button * which is presented after the download has been downloaded. */ - buttonRestartAfterDownload: function() { + buttonRestartAfterDownload() { if (!this.isPending && !this.isApplied) { return; } @@ -249,7 +249,7 @@ appUpdater.prototype = /** * See nsIUpdateService.idl */ - onCheckComplete: function(aRequest, aUpdates, aUpdateCount) { + onCheckComplete(aRequest, aUpdates, aUpdateCount) { gAppUpdater.isChecking = false; gAppUpdater.update = gAppUpdater.aus. selectUpdate(aUpdates, aUpdates.length); @@ -281,7 +281,7 @@ appUpdater.prototype = /** * See nsIUpdateService.idl */ - onError: function(aRequest, aUpdate) { + onError(aRequest, aUpdate) { // Errors in the update check are treated as no updates found. If the // update check fails repeatedly without a success the user will be // notified with the normal app update user interface so this is safe. @@ -292,7 +292,7 @@ appUpdater.prototype = /** * See nsISupports.idl */ - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (!aIID.equals(Components.interfaces.nsIUpdateCheckListener) && !aIID.equals(Components.interfaces.nsISupports)) throw Components.results.NS_ERROR_NO_INTERFACE; @@ -303,7 +303,7 @@ appUpdater.prototype = /** * Starts the download of an update mar. */ - startDownload: function() { + startDownload() { if (!this.update) this.update = this.um.activeUpdate; this.update.QueryInterface(Components.interfaces.nsIWritablePropertyBag); @@ -322,7 +322,7 @@ appUpdater.prototype = /** * Switches to the UI responsible for tracking the download. */ - setupDownloadingUI: function() { + setupDownloadingUI() { this.downloadStatus = document.getElementById("downloadStatus"); this.downloadStatus.value = DownloadUtils.getTransferTotal(0, this.update.selectedPatch.size); @@ -330,7 +330,7 @@ appUpdater.prototype = this.aus.addDownloadListener(this); }, - removeDownloadListener: function() { + removeDownloadListener() { if (this.aus) { this.aus.removeDownloadListener(this); } @@ -339,13 +339,13 @@ appUpdater.prototype = /** * See nsIRequestObserver.idl */ - onStartRequest: function(aRequest, aContext) { + onStartRequest(aRequest, aContext) { }, /** * See nsIRequestObserver.idl */ - onStopRequest: function(aRequest, aContext, aStatusCode) { + onStopRequest(aRequest, aContext, aStatusCode) { switch (aStatusCode) { case Components.results.NS_ERROR_UNEXPECTED: if (this.update.selectedPatch.state == "download-failed" && @@ -404,13 +404,13 @@ appUpdater.prototype = /** * See nsIProgressEventSink.idl */ - onStatus: function(aRequest, aContext, aStatus, aStatusArg) { + onStatus(aRequest, aContext, aStatus, aStatusArg) { }, /** * See nsIProgressEventSink.idl */ - onProgress: function(aRequest, aContext, aProgress, aProgressMax) { + onProgress(aRequest, aContext, aProgress, aProgressMax) { this.downloadStatus.value = DownloadUtils.getTransferTotal(aProgress, aProgressMax); }, @@ -418,7 +418,7 @@ appUpdater.prototype = /** * See nsISupports.idl */ - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (!aIID.equals(Components.interfaces.nsIProgressEventSink) && !aIID.equals(Components.interfaces.nsIRequestObserver) && !aIID.equals(Components.interfaces.nsISupports)) diff --git a/browser/base/content/aboutaccounts/aboutaccounts.js b/browser/base/content/aboutaccounts/aboutaccounts.js index bb9d00b1627d..f1660ca4149a 100644 --- a/browser/base/content/aboutaccounts/aboutaccounts.js +++ b/browser/base/content/aboutaccounts/aboutaccounts.js @@ -101,7 +101,7 @@ function updateDisplayedEmail(user) { var wrapper = { iframe: null, - init: function(url, urlParams) { + init(url, urlParams) { // If a master-password is enabled, we want to encourage the user to // unlock it. Things still work if not, but the user will probably need // to re-auth next startup (in which case we will get here again and @@ -130,7 +130,7 @@ var wrapper = { webNav.loadURI(url, Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY, null, null, null); }, - retry: function() { + retry() { let webNav = this.iframe.frameLoader.docShell.QueryInterface(Ci.nsIWebNavigation); webNav.loadURI(this.url, Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY, null, null, null); }, @@ -140,7 +140,7 @@ var wrapper = { Ci.nsISupportsWeakReference, Ci.nsISupports]), - onStateChange: function(aWebProgress, aRequest, aState, aStatus) { + onStateChange(aWebProgress, aRequest, aState, aStatus) { let failure = false; // Captive portals sometimes redirect users @@ -164,19 +164,19 @@ var wrapper = { } }, - onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { if (aRequest && aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) { aRequest.cancel(Components.results.NS_BINDING_ABORTED); setErrorPage("networkError"); } }, - onProgressChange: function() {}, - onStatusChange: function() {}, - onSecurityChange: function() {}, + onProgressChange() {}, + onStatusChange() {}, + onSecurityChange() {}, }, - handleEvent: function(evt) { + handleEvent(evt) { switch (evt.type) { case "load": this.iframe.contentWindow.addEventListener("FirefoxAccountsCommand", this); @@ -194,7 +194,7 @@ var wrapper = { * * @param accountData the user's account data and credentials */ - onLogin: function(accountData) { + onLogin(accountData) { log("Received: 'login'. Data:" + JSON.stringify(accountData)); if (accountData.customizeSync) { @@ -251,16 +251,16 @@ var wrapper = { ); }, - onCanLinkAccount: function(accountData) { + onCanLinkAccount(accountData) { // We need to confirm a relink - see shouldAllowRelink for more let ok = shouldAllowRelink(accountData.email); - this.injectData("message", { status: "can_link_account", data: { ok: ok } }); + this.injectData("message", { status: "can_link_account", data: { ok } }); }, /** * onSignOut handler erases the current user's session from the fxaccounts service */ - onSignOut: function() { + onSignOut() { log("Received: 'sign_out'."); fxAccounts.signOut().then( @@ -269,7 +269,7 @@ var wrapper = { ); }, - handleRemoteCommand: function(evt) { + handleRemoteCommand(evt) { log('command: ' + evt.detail.command); let data = evt.detail.data; @@ -289,11 +289,11 @@ var wrapper = { } }, - injectData: function(type, content) { + injectData(type, content) { return fxAccounts.promiseAccountsSignUpURI().then(authUrl => { let data = { - type: type, - content: content + type, + content }; this.iframe.contentWindow.postMessage(data, authUrl); }) diff --git a/browser/base/content/abouthealthreport/abouthealth.js b/browser/base/content/abouthealthreport/abouthealth.js index a21248f62d48..ae59e238eb0a 100644 --- a/browser/base/content/abouthealthreport/abouthealth.js +++ b/browser/base/content/abouthealthreport/abouthealth.js @@ -15,28 +15,28 @@ const PREF_UNIFIED = "toolkit.telemetry.unified"; const PREF_REPORTING_URL = "datareporting.healthreport.about.reportUrl"; var healthReportWrapper = { - init: function() { + init() { let iframe = document.getElementById("remote-report"); iframe.addEventListener("load", healthReportWrapper.initRemotePage, false); iframe.src = this._getReportURI().spec; prefs.observe("uploadEnabled", this.updatePrefState, healthReportWrapper); }, - uninit: function() { + uninit() { prefs.ignore("uploadEnabled", this.updatePrefState, healthReportWrapper); }, - _getReportURI: function() { + _getReportURI() { let url = Services.urlFormatter.formatURLPref(PREF_REPORTING_URL); return Services.io.newURI(url, null, null); }, - setDataSubmission: function(enabled) { + setDataSubmission(enabled) { MozSelfSupport.healthReportDataSubmissionEnabled = enabled; this.updatePrefState(); }, - updatePrefState: function() { + updatePrefState() { try { let prefsObj = { enabled: MozSelfSupport.healthReportDataSubmissionEnabled, @@ -48,7 +48,7 @@ var healthReportWrapper = { } }, - sendTelemetryPingList: function() { + sendTelemetryPingList() { console.log("AboutHealthReport: Collecting Telemetry ping list."); MozSelfSupport.getTelemetryPingList().then((list) => { console.log("AboutHealthReport: Sending Telemetry ping list."); @@ -58,7 +58,7 @@ var healthReportWrapper = { }); }, - sendTelemetryPingData: function(pingId) { + sendTelemetryPingData(pingId) { console.log("AboutHealthReport: Collecting Telemetry ping data."); MozSelfSupport.getTelemetryPing(pingId).then((ping) => { console.log("AboutHealthReport: Sending Telemetry ping data."); @@ -75,7 +75,7 @@ var healthReportWrapper = { }); }, - sendCurrentEnvironment: function() { + sendCurrentEnvironment() { console.log("AboutHealthReport: Sending Telemetry environment data."); MozSelfSupport.getCurrentTelemetryEnvironment().then((environment) => { this.injectData("telemetry-current-environment-data", environment); @@ -84,7 +84,7 @@ var healthReportWrapper = { }); }, - sendCurrentPingData: function() { + sendCurrentPingData() { console.log("AboutHealthReport: Sending current Telemetry ping data."); MozSelfSupport.getCurrentTelemetrySubsessionPing().then((ping) => { this.injectData("telemetry-current-ping-data", ping); @@ -93,7 +93,7 @@ var healthReportWrapper = { }); }, - injectData: function(type, content) { + injectData(type, content) { let report = this._getReportURI(); // file URIs can't be used for targetOrigin, so we use "*" for this special case @@ -101,15 +101,15 @@ var healthReportWrapper = { let reportUrl = report.scheme == "file" ? "*" : report.spec; let data = { - type: type, - content: content + type, + content } let iframe = document.getElementById("remote-report"); iframe.contentWindow.postMessage(data, reportUrl); }, - handleRemoteCommand: function(evt) { + handleRemoteCommand(evt) { // Do an origin check to harden against the frame content being loaded from unexpected locations. let allowedPrincipal = Services.scriptSecurityManager.getCodebasePrincipal(this._getReportURI()); let targetPrincipal = evt.target.nodePrincipal; @@ -147,7 +147,7 @@ var healthReportWrapper = { } }, - initRemotePage: function() { + initRemotePage() { let iframe = document.getElementById("remote-report").contentDocument; iframe.addEventListener("RemoteHealthReportCommand", function onCommand(e) { healthReportWrapper.handleRemoteCommand(e); }, @@ -160,18 +160,18 @@ var healthReportWrapper = { ERROR_PAYLOAD_FAILED: 2, ERROR_PREFS_FAILED: 3, - reportFailure: function(error) { + reportFailure(error) { let details = { errorType: error, } healthReportWrapper.injectData("error", details); }, - handleInitFailure: function() { + handleInitFailure() { healthReportWrapper.reportFailure(healthReportWrapper.ERROR_INIT_FAILED); }, - handlePayloadFailure: function() { + handlePayloadFailure() { healthReportWrapper.reportFailure(healthReportWrapper.ERROR_PAYLOAD_FAILED); }, } diff --git a/browser/base/content/abouthome/aboutHome.js b/browser/base/content/abouthome/aboutHome.js index 498d9bd2ed31..54dd71b96493 100644 --- a/browser/base/content/abouthome/aboutHome.js +++ b/browser/base/content/abouthome/aboutHome.js @@ -186,18 +186,18 @@ function ensureSnippetsMapThen(aCallback) // The cache has been filled up, create the snippets map. gSnippetsMap = Object.freeze({ get: (aKey) => cache.get(aKey), - set: function(aKey, aValue) { + set(aKey, aValue) { db.transaction(SNIPPETS_OBJECTSTORE_NAME, "readwrite") .objectStore(SNIPPETS_OBJECTSTORE_NAME).put(aValue, aKey); return cache.set(aKey, aValue); }, has: (aKey) => cache.has(aKey), - delete: function(aKey) { + delete(aKey) { db.transaction(SNIPPETS_OBJECTSTORE_NAME, "readwrite") .objectStore(SNIPPETS_OBJECTSTORE_NAME).delete(aKey); return cache.delete(aKey); }, - clear: function() { + clear() { db.transaction(SNIPPETS_OBJECTSTORE_NAME, "readwrite") .objectStore(SNIPPETS_OBJECTSTORE_NAME).clear(); return cache.clear(); diff --git a/browser/base/content/browser-addons.js b/browser/base/content/browser-addons.js index 1b52cde94901..8957c36c69e0 100644 --- a/browser/base/content/browser-addons.js +++ b/browser/base/content/browser-addons.js @@ -30,7 +30,7 @@ function removeNotificationOnEnd(notification, installs) { } const gXPInstallObserver = { - _findChildShell: function(aDocShell, aSoughtShell) + _findChildShell(aDocShell, aSoughtShell) { if (aDocShell == aSoughtShell) return aDocShell; @@ -45,7 +45,7 @@ const gXPInstallObserver = { return null; }, - _getBrowser: function(aDocShell) + _getBrowser(aDocShell) { for (let browser of gBrowser.browsers) { if (this._findChildShell(browser.docShell, aDocShell)) @@ -56,7 +56,7 @@ const gXPInstallObserver = { pendingInstalls: new WeakMap(), - showInstallConfirmation: function(browser, installInfo, height = undefined) { + showInstallConfirmation(browser, installInfo, height = undefined) { // If the confirmation notification is already open cache the installInfo // and the new confirmation will be shown later if (PopupNotifications.getNotification("addon-install-confirmation", browser)) { @@ -217,7 +217,7 @@ const gXPInstallObserver = { .add(Ci.nsISecurityUITelemetry.WARNING_CONFIRM_ADDON_INSTALL); }, - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { var brandBundle = document.getElementById("bundle_brand"); var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo); @@ -282,7 +282,7 @@ const gXPInstallObserver = { action = { label: gNavigatorBundle.getString("xpinstallPromptAllowButton"), accessKey: gNavigatorBundle.getString("xpinstallPromptAllowButton.accesskey"), - callback: function() { + callback() { secHistogram.add(Ci.nsISecurityUITelemetry.WARNING_ADDON_ASKING_PREVENTED_CLICK_THROUGH); installInfo.install(); } @@ -433,7 +433,7 @@ const gXPInstallObserver = { action = { label: gNavigatorBundle.getString("addonInstallRestartButton"), accessKey: gNavigatorBundle.getString("addonInstallRestartButton.accesskey"), - callback: function() { + callback() { BrowserUtils.restartApplication(); } }; @@ -472,14 +472,14 @@ const gXPInstallObserver = { }; var LightWeightThemeWebInstaller = { - init: function() { + init() { let mm = window.messageManager; mm.addMessageListener("LightWeightThemeWebInstaller:Install", this); mm.addMessageListener("LightWeightThemeWebInstaller:Preview", this); mm.addMessageListener("LightWeightThemeWebInstaller:ResetPreview", this); }, - receiveMessage: function(message) { + receiveMessage(message) { // ignore requests from background tabs if (message.target != gBrowser.selectedBrowser) { return; @@ -503,7 +503,7 @@ var LightWeightThemeWebInstaller = { } }, - handleEvent: function(event) { + handleEvent(event) { switch (event.type) { case "TabSelect": { this._resetPreview(); @@ -519,7 +519,7 @@ var LightWeightThemeWebInstaller = { return this._manager = temp.LightweightThemeManager; }, - _installRequest: function(dataString, baseURI) { + _installRequest(dataString, baseURI) { let data = this._manager.parseTheme(dataString, baseURI); if (!data) { @@ -560,7 +560,7 @@ var LightWeightThemeWebInstaller = { let buttons = [{ label: allowButtonText, accessKey: allowButtonAccesskey, - callback: function() { + callback() { LightWeightThemeWebInstaller._install(data, notify); } }]; @@ -575,11 +575,11 @@ var LightWeightThemeWebInstaller = { notificationBar.persistence = 1; }, - _install: function(newLWTheme, notify) { + _install(newLWTheme, notify) { let previousLWTheme = this._manager.currentTheme; let listener = { - onEnabling: function(aAddon, aRequiresRestart) { + onEnabling(aAddon, aRequiresRestart) { if (!aRequiresRestart) { return; } @@ -590,7 +590,7 @@ var LightWeightThemeWebInstaller = { let action = { label: gNavigatorBundle.getString("lwthemeNeedsRestart.button"), accessKey: gNavigatorBundle.getString("lwthemeNeedsRestart.accesskey"), - callback: function() { + callback() { BrowserUtils.restartApplication(); } }; @@ -604,7 +604,7 @@ var LightWeightThemeWebInstaller = { action, null, options); }, - onEnabled: function(aAddon) { + onEnabled(aAddon) { if (notify) { LightWeightThemeWebInstaller._postInstallNotification(newLWTheme, previousLWTheme); } @@ -616,7 +616,7 @@ var LightWeightThemeWebInstaller = { AddonManager.removeAddonListener(listener); }, - _postInstallNotification: function(newTheme, previousTheme) { + _postInstallNotification(newTheme, previousTheme) { function text(id) { return gNavigatorBundle.getString("lwthemePostInstallNotification." + id); } @@ -624,14 +624,14 @@ var LightWeightThemeWebInstaller = { let buttons = [{ label: text("undoButton"), accessKey: text("undoButton.accesskey"), - callback: function() { + callback() { LightWeightThemeWebInstaller._manager.forgetUsedTheme(newTheme.id); LightWeightThemeWebInstaller._manager.currentTheme = previousTheme; } }, { label: text("manageButton"), accessKey: text("manageButton.accesskey"), - callback: function() { + callback() { BrowserOpenAddonsMgr("addons://list/theme"); } }]; @@ -648,7 +648,7 @@ var LightWeightThemeWebInstaller = { notificationBar.timeout = Date.now() + 20000; // 20 seconds }, - _removePreviousNotifications: function() { + _removePreviousNotifications() { let box = gBrowser.getNotificationBox(); ["lwtheme-install-request", @@ -659,7 +659,7 @@ var LightWeightThemeWebInstaller = { }); }, - _preview: function(dataString, baseURI) { + _preview(dataString, baseURI) { if (!this._isAllowed(baseURI)) return; @@ -672,14 +672,14 @@ var LightWeightThemeWebInstaller = { this._manager.previewTheme(data); }, - _resetPreview: function(baseURI) { + _resetPreview(baseURI) { if (baseURI && !this._isAllowed(baseURI)) return; gBrowser.tabContainer.removeEventListener("TabSelect", this, false); this._manager.resetPreview(); }, - _isAllowed: function(srcURIString) { + _isAllowed(srcURIString) { let uri; try { uri = makeURI(srcURIString); @@ -704,7 +704,7 @@ var LightWeightThemeWebInstaller = { var LightweightThemeListener = { _modifiedStyles: [], - init: function() { + init() { XPCOMUtils.defineLazyGetter(this, "styleSheet", function() { for (let i = document.styleSheets.length - 1; i >= 0; i--) { let sheet = document.styleSheets[i]; @@ -720,7 +720,7 @@ var LightweightThemeListener = { this.updateStyleSheet(document.documentElement.style.backgroundImage); }, - uninit: function() { + uninit() { Services.obs.removeObserver(this, "lightweight-theme-styling-update"); Services.obs.removeObserver(this, "lightweight-theme-optimized"); }, @@ -731,13 +731,13 @@ var LightweightThemeListener = { * * @param headerImage - a string containing a CSS image for the lightweight theme header. */ - updateStyleSheet: function(headerImage) { + updateStyleSheet(headerImage) { if (!this.styleSheet) return; this.substituteRules(this.styleSheet.cssRules, headerImage); }, - substituteRules: function(ruleList, headerImage, existingStyleRulesModified = 0) { + substituteRules(ruleList, headerImage, existingStyleRulesModified = 0) { let styleRulesModified = 0; for (let i = 0; i < ruleList.length; i++) { let rule = ruleList[i]; @@ -761,7 +761,7 @@ var LightweightThemeListener = { }, // nsIObserver - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if ((aTopic != "lightweight-theme-styling-update" && aTopic != "lightweight-theme-optimized") || !this.styleSheet) return; diff --git a/browser/base/content/browser-ctrlTab.js b/browser/base/content/browser-ctrlTab.js index 7cafd8541948..88cff082b1e2 100644 --- a/browser/base/content/browser-ctrlTab.js +++ b/browser/base/content/browser-ctrlTab.js @@ -96,7 +96,7 @@ var tabPreviews = { }; var tabPreviewPanelHelper = { - opening: function(host) { + opening(host) { host.panel.hidden = false; var handler = this._generateHandler(host); @@ -105,7 +105,7 @@ var tabPreviewPanelHelper = { host._prevFocus = document.commandDispatcher.focusedElement; }, - _generateHandler: function(host) { + _generateHandler(host) { var self = this; return function(event) { if (event.target == host.panel) { @@ -114,11 +114,11 @@ var tabPreviewPanelHelper = { } }; }, - _popupshown: function(host) { + _popupshown(host) { if ("setupGUI" in host) host.setupGUI(); }, - _popuphiding: function(host) { + _popuphiding(host) { if ("suspendGUI" in host) host.suspendGUI(); @@ -219,7 +219,7 @@ var ctrlTab = { else this.uninit(); }, - observe: function(aSubject, aTopic, aPrefName) { + observe(aSubject, aTopic, aPrefName) { this.readPref(); }, @@ -507,7 +507,7 @@ var ctrlTab = { } }, - filterForThumbnailExpiration: function(aCallback) { + filterForThumbnailExpiration(aCallback) { // Save a few more thumbnails than we actually display, so that when tabs // are closed, the previews we add instead still get thumbnails. const extraThumbnails = 3; @@ -521,7 +521,7 @@ var ctrlTab = { aCallback(urls); }, - _initRecentlyUsedTabs: function() { + _initRecentlyUsedTabs() { this._recentlyUsedTabs = Array.filter(gBrowser.tabs, tab => !tab.closing) .sort((tab1, tab2) => tab2.lastAccessed - tab1.lastAccessed); diff --git a/browser/base/content/browser-customization.js b/browser/base/content/browser-customization.js index d5d51b8931a3..672d25ec6caa 100644 --- a/browser/base/content/browser-customization.js +++ b/browser/base/content/browser-customization.js @@ -9,7 +9,7 @@ * events. */ var CustomizationHandler = { - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "customizationstarting": this._customizationStarting(); @@ -23,11 +23,11 @@ var CustomizationHandler = { } }, - isCustomizing: function() { + isCustomizing() { return document.documentElement.hasAttribute("customizing"); }, - _customizationStarting: function() { + _customizationStarting() { // Disable the toolbar context menu items let menubar = document.getElementById("main-menubar"); for (let childNode of menubar.childNodes) @@ -51,11 +51,11 @@ var CustomizationHandler = { } }, - _customizationChange: function() { + _customizationChange() { PlacesToolbarHelper.customizeChange(); }, - _customizationEnding: function(aDetails) { + _customizationEnding(aDetails) { // Update global UI elements that may have been added or removed if (aDetails.changed) { gURLBar = document.getElementById("urlbar"); diff --git a/browser/base/content/browser-data-submission-info-bar.js b/browser/base/content/browser-data-submission-info-bar.js index 0d2c7aabfc10..456f91b48ee0 100644 --- a/browser/base/content/browser-data-submission-info-bar.js +++ b/browser/base/content/browser-data-submission-info-bar.js @@ -27,7 +27,7 @@ var gDataNotificationInfoBar = { return this._log = Log.repository.getLoggerWithMessagePrefix(LOGGER_NAME, LOGGER_PREFIX); }, - init: function() { + init() { window.addEventListener("unload", () => { for (let o of this._OBSERVERS) { Services.obs.removeObserver(this, o); @@ -39,11 +39,11 @@ var gDataNotificationInfoBar = { } }, - _getDataReportingNotification: function(name = this._DATA_REPORTING_NOTIFICATION) { + _getDataReportingNotification(name = this._DATA_REPORTING_NOTIFICATION) { return this._notificationBox.getNotificationWithValue(name); }, - _displayDataPolicyInfoBar: function(request) { + _displayDataPolicyInfoBar(request) { if (this._getDataReportingNotification()) { return; } @@ -88,7 +88,7 @@ var gDataNotificationInfoBar = { request.onUserNotifyComplete(); }, - _clearPolicyNotification: function() { + _clearPolicyNotification() { let notification = this._getDataReportingNotification(); if (notification) { this._log.debug("Closing notification."); @@ -96,7 +96,7 @@ var gDataNotificationInfoBar = { } }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "datareporting:notify-data-policy:request": let request = subject.wrappedJSObject.object; diff --git a/browser/base/content/browser-devedition.js b/browser/base/content/browser-devedition.js index 8c1fe88a5b0e..aa4da1d5ba0e 100644 --- a/browser/base/content/browser-devedition.js +++ b/browser/base/content/browser-devedition.js @@ -21,7 +21,7 @@ var DevEdition = { return theme && theme.id == "firefox-devedition@mozilla.org"; }, - init: function() { + init() { this.initialized = true; Services.prefs.addObserver(this._devtoolsThemePrefName, this, false); Services.obs.addObserver(this, "lightweight-theme-styling-update", false); @@ -33,7 +33,7 @@ var DevEdition = { } }, - createStyleSheet: function() { + createStyleSheet() { let styleSheetAttr = `href="${this.styleSheetLocation}" type="text/css"`; this.styleSheet = document.createProcessingInstruction( "xml-stylesheet", styleSheetAttr); @@ -42,7 +42,7 @@ var DevEdition = { this.styleSheet.sheet.disabled = true; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic == "lightweight-theme-styling-update") { let newTheme = JSON.parse(data); if (newTheme && newTheme.id == "firefox-devedition@mozilla.org") { @@ -59,7 +59,7 @@ var DevEdition = { } }, - _inferBrightness: function() { + _inferBrightness() { ToolbarIconColor.inferFromText(); // Get an inverted full screen button if the dark theme is applied. if (this.isStyleSheetEnabled && @@ -78,7 +78,7 @@ var DevEdition = { } }, - _updateDevtoolsThemeAttribute: function() { + _updateDevtoolsThemeAttribute() { // Set an attribute on root element to make it possible // to change colors based on the selected devtools theme. let devtoolsTheme = Services.prefs.getCharPref(this._devtoolsThemePrefName); @@ -90,14 +90,14 @@ var DevEdition = { this._inferBrightness(); }, - handleEvent: function(e) { + handleEvent(e) { if (e.type === "load") { this.styleSheet.removeEventListener("load", this); this.refreshBrowserDisplay(); } }, - refreshBrowserDisplay: function() { + refreshBrowserDisplay() { // Don't touch things on the browser if gBrowserInit.onLoad hasn't // yet fired. if (this.initialized) { @@ -106,7 +106,7 @@ var DevEdition = { } }, - _toggleStyleSheet: function(deveditionThemeEnabled) { + _toggleStyleSheet(deveditionThemeEnabled) { let wasEnabled = this.isStyleSheetEnabled; if (deveditionThemeEnabled && !wasEnabled) { // The stylesheet may not have been created yet if it wasn't @@ -122,7 +122,7 @@ var DevEdition = { } }, - uninit: function() { + uninit() { Services.prefs.removeObserver(this._devtoolsThemePrefName, this); Services.obs.removeObserver(this, "lightweight-theme-styling-update", false); Services.obs.removeObserver(this, "lightweight-theme-window-updated", false); diff --git a/browser/base/content/browser-fullScreenAndPointerLock.js b/browser/base/content/browser-fullScreenAndPointerLock.js index 678500e7ab32..4e8539056735 100644 --- a/browser/base/content/browser-fullScreenAndPointerLock.js +++ b/browser/base/content/browser-fullScreenAndPointerLock.js @@ -8,19 +8,19 @@ var PointerlockFsWarning = { _element: null, _origin: null, - init: function() { + init() { this.Timeout.prototype = { - start: function() { + start() { this.cancel(); this._id = setTimeout(() => this._handle(), this._delay); }, - cancel: function() { + cancel() { if (this._id) { clearTimeout(this._id); this._id = 0; } }, - _handle: function() { + _handle() { this._id = 0; this._func(); }, @@ -30,6 +30,13 @@ var PointerlockFsWarning = { }; }, + /* eslint-disable object-shorthand */ + /* The object-shorthand rule must be disabled for this constructor + * because the ES6 method syntax causes "this.Timeout is not a + * constructor" exception. Further, using the {ignoreConstructors: true} + * option causes "TypeError: Cannot read property 'charAt' of undefined" + * in eslint. + */ /** * Timeout object for managing timeout request. If it is started when * the previous call hasn't finished, it would automatically cancelled @@ -40,15 +47,16 @@ var PointerlockFsWarning = { this._func = func; this._delay = delay; }, + /* eslint-enable object-shorthand */ - showPointerLock: function(aOrigin) { + showPointerLock(aOrigin) { if (!document.fullscreen) { let timeout = gPrefService.getIntPref("pointer-lock-api.warning.timeout"); this.show(aOrigin, "pointerlock-warning", timeout, 0); } }, - showFullScreen: function(aOrigin) { + showFullScreen(aOrigin) { let timeout = gPrefService.getIntPref("full-screen-api.warning.timeout"); let delay = gPrefService.getIntPref("full-screen-api.warning.delay"); this.show(aOrigin, "fullscreen-warning", timeout, delay); @@ -56,7 +64,7 @@ var PointerlockFsWarning = { // Shows a warning that the site has entered fullscreen or // pointer lock for a short duration. - show: function(aOrigin, elementId, timeout, delay) { + show(aOrigin, elementId, timeout, delay) { if (!this._element) { this._element = document.getElementById(elementId); @@ -111,7 +119,7 @@ var PointerlockFsWarning = { this._timeoutHide.start(); }, - close: function() { + close() { if (!this._element) { return; } @@ -180,7 +188,7 @@ var PointerlockFsWarning = { } }, - handleEvent: function(event) { + handleEvent(event) { switch (event.type) { case "mousemove": { let state = this._state; @@ -226,12 +234,12 @@ var PointerlockFsWarning = { var PointerLock = { - init: function() { + init() { window.messageManager.addMessageListener("PointerLock:Entered", this); window.messageManager.addMessageListener("PointerLock:Exited", this); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "PointerLock:Entered": { PointerlockFsWarning.showPointerLock(aMessage.data.originNoSuffix); @@ -253,7 +261,7 @@ var FullScreen = { "DOMFullscreen:Painted", ], - init: function() { + init() { // called when we go into full screen, even if initiated by a web page script window.addEventListener("fullscreen", this, true); window.addEventListener("MozDOMFullscreen:Entered", this, @@ -270,14 +278,14 @@ var FullScreen = { this.toggle(); }, - uninit: function() { + uninit() { for (let type of this._MESSAGES) { window.messageManager.removeMessageListener(type, this); } this.cleanup(); }, - toggle: function() { + toggle() { var enterFS = window.fullScreen; // Toggle the View:FullScreen command, which controls elements like the @@ -342,11 +350,11 @@ var FullScreen = { } }, - exitDomFullScreen : function() { + exitDomFullScreen() { document.exitFullscreen(); }, - handleEvent: function(event) { + handleEvent(event) { switch (event.type) { case "fullscreen": this.toggle(); @@ -377,7 +385,7 @@ var FullScreen = { } }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { let browser = aMessage.target; switch (aMessage.name) { case "DOMFullscreen:Request": { @@ -403,7 +411,7 @@ var FullScreen = { } }, - enterDomFullscreen : function(aBrowser) { + enterDomFullscreen(aBrowser) { if (!document.fullscreenElement) { return; @@ -456,7 +464,7 @@ var FullScreen = { window.addEventListener("activate", this); }, - cleanup: function() { + cleanup() { if (!window.fullScreen) { MousePosTracker.removeListener(this); document.removeEventListener("keypress", this._keyToggleCallback, false); @@ -465,7 +473,7 @@ var FullScreen = { } }, - cleanupDomFullscreen: function() { + cleanupDomFullscreen() { window.messageManager .broadcastAsyncMessage("DOMFullscreen:CleanUp"); @@ -478,7 +486,7 @@ var FullScreen = { document.documentElement.removeAttribute("inDOMFullscreen"); }, - _isRemoteBrowser: function(aBrowser) { + _isRemoteBrowser(aBrowser) { return gMultiProcessBrowser && aBrowser.getAttribute("remote") == "true"; }, @@ -487,21 +495,21 @@ var FullScreen = { .getInterface(Ci.nsIDOMWindowUtils); }, - getMouseTargetRect: function() + getMouseTargetRect() { return this._mouseTargetRect; }, // Event callbacks - _expandCallback: function() + _expandCallback() { FullScreen.showNavToolbox(); }, - onMouseEnter: function() + onMouseEnter() { FullScreen.hideNavToolbox(); }, - _keyToggleCallback: function(aEvent) + _keyToggleCallback(aEvent) { // if we can use the keyboard (eg Ctrl+L or Ctrl+E) to open the toolbars, we // should provide a way to collapse them too. @@ -516,7 +524,7 @@ var FullScreen = { // Checks whether we are allowed to collapse the chrome _isPopupOpen: false, _isChromeCollapsed: false, - _safeToCollapse: function() { + _safeToCollapse() { if (!gPrefService.getBoolPref("browser.fullscreen.autohide")) return false; @@ -538,7 +546,7 @@ var FullScreen = { return true; }, - _setPopupOpen: function(aEvent) + _setPopupOpen(aEvent) { // Popups should only veto chrome collapsing if they were opened when the chrome was not collapsed. // Otherwise, they would not affect chrome and the user would expect the chrome to go away. @@ -556,18 +564,18 @@ var FullScreen = { }, // Autohide helpers for the context menu item - getAutohide: function(aItem) + getAutohide(aItem) { aItem.setAttribute("checked", gPrefService.getBoolPref("browser.fullscreen.autohide")); }, - setAutohide: function() + setAutohide() { gPrefService.setBoolPref("browser.fullscreen.autohide", !gPrefService.getBoolPref("browser.fullscreen.autohide")); // Try again to hide toolbar when we change the pref. FullScreen.hideNavToolbox(true); }, - showNavToolbox: function(trackMouse = true) { + showNavToolbox(trackMouse = true) { this._fullScrToggler.hidden = true; gNavToolbox.removeAttribute("fullscreenShouldAnimate"); gNavToolbox.style.marginTop = ""; @@ -591,7 +599,7 @@ var FullScreen = { this._isChromeCollapsed = false; }, - hideNavToolbox: function(aAnimate = false) { + hideNavToolbox(aAnimate = false) { if (this._isChromeCollapsed || !this._safeToCollapse()) return; @@ -615,7 +623,7 @@ var FullScreen = { MousePosTracker.removeListener(this); }, - _updateToolbars: function(aEnterFS) { + _updateToolbars(aEnterFS) { for (let el of document.querySelectorAll("toolbar[fullscreentoolbar=true]")) { if (aEnterFS) { // Give the main nav bar and the tab bar the fullscreen context menu, diff --git a/browser/base/content/browser-fullZoom.js b/browser/base/content/browser-fullZoom.js index 2e963cfa6f9d..6f3f0271b08e 100644 --- a/browser/base/content/browser-fullZoom.js +++ b/browser/base/content/browser-fullZoom.js @@ -89,7 +89,7 @@ var FullZoom = { // nsIObserver - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "nsPref:changed": switch (aData) { @@ -154,7 +154,7 @@ var FullZoom = { let hasPref = false; let token = this._getBrowserToken(browser); this._cps2.getByDomainAndName(browser.currentURI.spec, this.name, ctxt, { - handleResult: function() { hasPref = true; }, + handleResult() { hasPref = true; }, handleCompletion: function() { if (!hasPref && token.isCurrent) this._applyPrefToZoom(undefined, browser); @@ -223,7 +223,7 @@ var FullZoom = { let value = undefined; let token = this._getBrowserToken(browser); this._cps2.getByDomainAndName(aURI.spec, this.name, ctxt, { - handleResult: function(resultPref) { value = resultPref.value; }, + handleResult(resultPref) { value = resultPref.value; }, handleCompletion: function() { if (!token.isCurrent) { this._notifyOnLocationChange(browser); @@ -269,7 +269,7 @@ var FullZoom = { * Sets the zoom level for the given browser to the given floating * point value, where 1 is the default zoom level. */ - setZoom: function(value, browser = gBrowser.selectedBrowser) { + setZoom(value, browser = gBrowser.selectedBrowser) { ZoomManager.setZoomForBrowser(browser, value); this._ignorePendingZoomAccesses(browser); this._applyZoomToPref(browser); @@ -487,7 +487,7 @@ var FullZoom = { } let value = undefined; this._cps2.getGlobal(this.name, this._loadContextFromBrowser(browser), { - handleResult: function(pref) { value = pref.value; }, + handleResult(pref) { value = pref.value; }, handleCompletion: (reason) => { this._globalValue = this._ensureValid(value); resolve(this._globalValue); diff --git a/browser/base/content/browser-fxaccounts.js b/browser/base/content/browser-fxaccounts.js index d841dc142e7c..951f35b9cbd0 100644 --- a/browser/base/content/browser-fxaccounts.js +++ b/browser/base/content/browser-fxaccounts.js @@ -88,7 +88,7 @@ var gFxAccounts = { .sort((a, b) => a.name.localeCompare(b.name)); }, - init: function() { + init() { // Bail out if we're already initialized and for pop-up windows. if (this._initialized || !window.toolbar.visible) { return; @@ -107,7 +107,7 @@ var gFxAccounts = { this.updateUI(); }, - uninit: function() { + uninit() { if (!this._initialized) { return; } @@ -119,7 +119,7 @@ var gFxAccounts = { this._initialized = false; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "fxa-migration:state-changed": this.onMigrationStateChanged(data, subject); @@ -133,7 +133,7 @@ var gFxAccounts = { } }, - onMigrationStateChanged: function() { + onMigrationStateChanged() { // Since we nuked most of the migration code, this notification will fire // once after legacy Sync has been disconnected (and should never fire // again) @@ -175,12 +175,12 @@ var gFxAccounts = { this.updateAppMenuItem(); }, - handleEvent: function(event) { + handleEvent(event) { this._inCustomizationMode = event.type == "customizationstarting"; this.updateAppMenuItem(); }, - updateUI: function() { + updateUI() { // It's possible someone signed in to FxA after seeing our notification // about "Legacy Sync migration" (which now is actually "Legacy Sync // auto-disconnect") so kill that notification if it still exists. @@ -194,7 +194,7 @@ var gFxAccounts = { }, // Note that updateAppMenuItem() returns a Promise that's only used by tests. - updateAppMenuItem: function() { + updateAppMenuItem() { let profileInfoEnabled = false; try { profileInfoEnabled = Services.prefs.getBoolPref("identity.fxaccounts.profile_image.enabled"); @@ -320,7 +320,7 @@ var gFxAccounts = { }); }, - onMenuPanelCommand: function() { + onMenuPanelCommand() { switch (this.panelUIFooter.getAttribute("fxastatus")) { case "signedin": @@ -341,11 +341,11 @@ var gFxAccounts = { PanelUI.hide(); }, - openPreferences: function() { + openPreferences() { openPreferences("paneSync", { urlParams: { entrypoint: "menupanel" } }); }, - openAccountsPage: function(action, urlParams = {}) { + openAccountsPage(action, urlParams = {}) { let params = new URLSearchParams(); if (action) { params.set("action", action); @@ -361,15 +361,15 @@ var gFxAccounts = { }); }, - openSignInAgainPage: function(entryPoint) { + openSignInAgainPage(entryPoint) { this.openAccountsPage("reauth", { entrypoint: entryPoint }); }, - sendTabToDevice: function(url, clientId, title) { + sendTabToDevice(url, clientId, title) { Weave.Service.clientsEngine.sendURIToClientForDisplay(url, clientId, title); }, - populateSendTabToDevicesMenu: function(devicesPopup, url, title) { + populateSendTabToDevicesMenu(devicesPopup, url, title) { // remove existing menu items while (devicesPopup.hasChildNodes()) { devicesPopup.removeChild(devicesPopup.firstChild); @@ -410,7 +410,7 @@ var gFxAccounts = { devicesPopup.appendChild(fragment); }, - updateTabContextMenu: function(aPopupMenu) { + updateTabContextMenu(aPopupMenu) { if (!this.sendTabToDeviceEnabled) { return; } @@ -420,7 +420,7 @@ var gFxAccounts = { .forEach(id => { document.getElementById(id).hidden = !remoteClientPresent }); }, - initPageContextMenu: function(contextMenu) { + initPageContextMenu(contextMenu) { if (!this.sendTabToDeviceEnabled) { return; } diff --git a/browser/base/content/browser-gestureSupport.js b/browser/base/content/browser-gestureSupport.js index 7c60a05675b0..c281ebf54e19 100644 --- a/browser/base/content/browser-gestureSupport.js +++ b/browser/base/content/browser-gestureSupport.js @@ -351,7 +351,7 @@ var gGestureSupport = { * @param aEvent * The continual motion update event to handle */ - _doUpdate: function(aEvent) {}, + _doUpdate(aEvent) {}, /** * Handle gesture end events. This function will be set by _setupSwipe. @@ -359,7 +359,7 @@ var gGestureSupport = { * @param aEvent * The gesture end event to handle */ - _doEnd: function(aEvent) {}, + _doEnd(aEvent) {}, /** * Convert the swipe gesture into a browser action based on the direction. @@ -444,7 +444,7 @@ var gGestureSupport = { * @param aEvent * The MozRotateGestureUpdate event triggering this call */ - rotate: function(aEvent) { + rotate(aEvent) { if (!(content.document instanceof ImageDocument)) return; @@ -463,7 +463,7 @@ var gGestureSupport = { /** * Perform a rotation end for ImageDocuments */ - rotateEnd: function() { + rotateEnd() { if (!(content.document instanceof ImageDocument)) return; @@ -531,7 +531,7 @@ var gGestureSupport = { * When the location/tab changes, need to reload the current rotation for the * image */ - restoreRotationState: function() { + restoreRotationState() { // Bug 863514 - Make gesture support work in electrolysis if (gMultiProcessBrowser) return; @@ -560,7 +560,7 @@ var gGestureSupport = { /** * Removes the transition rule by removing the completeRotation class */ - _clearCompleteRotation: function() { + _clearCompleteRotation() { let contentElement = content.document && content.document instanceof ImageDocument && content.document.body && @@ -731,7 +731,7 @@ var gHistorySwipeAnimation = { } }, - _getCurrentHistoryIndex: function() { + _getCurrentHistoryIndex() { return SessionStore.getSessionHistory(gBrowser.selectedTab).index; }, diff --git a/browser/base/content/browser-media.js b/browser/base/content/browser-media.js index 7d10635df286..9e0498b9259c 100644 --- a/browser/base/content/browser-media.js +++ b/browser/base/content/browser-media.js @@ -12,7 +12,7 @@ var gEMEHandler = { } return emeUIEnabled; }, - ensureEMEEnabled: function(browser, keySystem) { + ensureEMEEnabled(browser, keySystem) { Services.prefs.setBoolPref("media.eme.enabled", true); if (keySystem) { if (keySystem.startsWith("com.adobe") && @@ -27,7 +27,7 @@ var gEMEHandler = { } browser.reload(); }, - isKeySystemVisible: function(keySystem) { + isKeySystemVisible(keySystem) { if (!keySystem) { return false; } @@ -41,13 +41,13 @@ var gEMEHandler = { } return true; }, - getLearnMoreLink: function(msgId) { + getLearnMoreLink(msgId) { let text = gNavigatorBundle.getString("emeNotifications." + msgId + ".learnMoreLabel"); let baseURL = Services.urlFormatter.formatURLPref("app.support.baseURL"); return ""; }, - receiveMessage: function({target: browser, data: data}) { + receiveMessage({target: browser, data: data}) { let parsedData; try { parsedData = JSON.parse(data); @@ -102,7 +102,7 @@ var gEMEHandler = { this.showNotificationBar(browser, notificationId, keySystem, params, buttonCallback); }, - showNotificationBar: function(browser, notificationId, keySystem, labelParams, callback) { + showNotificationBar(browser, notificationId, keySystem, labelParams, callback) { let box = gBrowser.getNotificationBox(browser); if (box.getNotificationWithValue(notificationId)) { return; @@ -122,7 +122,7 @@ var gEMEHandler = { buttons.push({ label: gNavigatorBundle.getString(btnLabelId), accessKey: gNavigatorBundle.getString(btnAccessKeyId), - callback: callback + callback }); } @@ -139,7 +139,7 @@ var gEMEHandler = { box.appendNotification(fragment, notificationId, iconURL, box.PRIORITY_WARNING_MEDIUM, buttons); }, - showPopupNotificationForSuccess: function(browser, keySystem) { + showPopupNotificationForSuccess(browser, keySystem) { // We're playing EME content! Remove any "we can't play because..." messages. var box = gBrowser.getNotificationBox(browser); ["drmContentDisabled", @@ -174,7 +174,7 @@ var gEMEHandler = { let mainAction = { label: gNavigatorBundle.getString(btnLabelId), accessKey: gNavigatorBundle.getString(btnAccessKeyId), - callback: function() { openPreferences("paneContent"); }, + callback() { openPreferences("paneContent"); }, dismiss: true }; let options = { diff --git a/browser/base/content/browser-places.js b/browser/base/content/browser-places.js index 08e326b7e0fe..960065dd0192 100644 --- a/browser/base/content/browser-places.js +++ b/browser/base/content/browser-places.js @@ -9,7 +9,7 @@ var StarUI = { _isNewBookmark: false, _autoCloseTimer: 0, - _element: function(aID) { + _element(aID) { return document.getElementById(aID); }, @@ -633,10 +633,10 @@ var PlacesCommandHook = { PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "livemark" - , feedURI: feedURI + , feedURI , siteURI: gBrowser.currentURI - , title: title - , description: description + , title + , description , defaultInsertionPoint: toolbarIP , hiddenRows: [ "feedLocation" , "siteLocation" @@ -1143,7 +1143,7 @@ var PlacesToolbarHelper = { return !area || CustomizableUI.TYPE_MENU_PANEL == areaType; }, - onPlaceholderCommand: function() { + onPlaceholderCommand() { let widgetGroup = CustomizableUI.getWidget("personal-bookmarks"); let widget = widgetGroup.forWindow(window); if (widget.overflowed || @@ -1152,7 +1152,7 @@ var PlacesToolbarHelper = { } }, - _getParentToolbar: function(element) { + _getParentToolbar(element) { while (element) { if (element.localName == "toolbar") { return element; @@ -1162,7 +1162,7 @@ var PlacesToolbarHelper = { return null; }, - onWidgetUnderflow: function(aNode, aContainer) { + onWidgetUnderflow(aNode, aContainer) { // The view gets broken by being removed and reinserted by the overflowable // toolbar, so we have to force an uninit and reinit. let win = aNode.ownerGlobal; @@ -1171,7 +1171,7 @@ var PlacesToolbarHelper = { } }, - onWidgetAdded: function(aWidgetId, aArea, aPosition) { + onWidgetAdded(aWidgetId, aArea, aPosition) { if (aWidgetId == "personal-bookmarks" && !this._isCustomizing) { // It's possible (with the "Add to Menu", "Add to Toolbar" context // options) that the Places Toolbar Items have been moved without @@ -1182,7 +1182,7 @@ var PlacesToolbarHelper = { } }, - _resetView: function() { + _resetView() { if (this._viewElt) { // It's possible that the placesView might not exist, and we need to // do a full init. This could happen if the Bookmarks Toolbar Items are @@ -1274,7 +1274,7 @@ var BookmarkingUI = { this._getFormattedTooltip("starButtonOff.tooltip2"); }, - _getFormattedTooltip: function(strId) { + _getFormattedTooltip(strId) { let args = []; let shortcut = document.getElementById(this.BOOKMARK_BUTTON_SHORTCUT); if (shortcut) @@ -1287,7 +1287,7 @@ var BookmarkingUI = { * When in the panel, we don't update the button's icon. */ _currentAreaType: null, - _shouldUpdateStarState: function() { + _shouldUpdateStarState() { return this._currentAreaType == CustomizableUI.TYPE_TOOLBAR; }, @@ -1349,7 +1349,7 @@ var BookmarkingUI = { } }, - attachPlacesView: function(event, node) { + attachPlacesView(event, node) { // If the view is already there, bail out early. if (node.parentNode._placesView) return; @@ -1577,7 +1577,7 @@ var BookmarkingUI = { } }, - init: function() { + init() { CustomizableUI.addListener(this); this._updateCustomizationState(); }, @@ -1757,7 +1757,7 @@ var BookmarkingUI = { }, 1000); }, - _showSubview: function() { + _showSubview() { let view = document.getElementById("PanelUI-bookmarks"); view.addEventListener("ViewShowing", this); view.addEventListener("ViewHiding", this); @@ -1902,11 +1902,11 @@ var BookmarkingUI = { } }, - onBeginUpdateBatch: function() {}, - onEndUpdateBatch: function() {}, - onBeforeItemRemoved: function() {}, - onItemVisited: function() {}, - onItemMoved: function() {}, + onBeginUpdateBatch() {}, + onEndUpdateBatch() {}, + onBeforeItemRemoved() {}, + onItemVisited() {}, + onItemMoved() {}, // CustomizableUI events: _starButtonLabel: null, @@ -1920,7 +1920,7 @@ var BookmarkingUI = { return this._starButtonOverflowedStarredLabel = gNavigatorBundle.getString("starButtonOverflowedStarred.label"); }, - onWidgetOverflow: function(aNode, aContainer) { + onWidgetOverflow(aNode, aContainer) { let win = aNode.ownerGlobal; if (aNode.id != this.BOOKMARK_BUTTON_ID || win != window) return; @@ -1936,7 +1936,7 @@ var BookmarkingUI = { } }, - onWidgetUnderflow: function(aNode, aContainer) { + onWidgetUnderflow(aNode, aContainer) { let win = aNode.ownerGlobal; if (aNode.id != this.BOOKMARK_BUTTON_ID || win != window) return; diff --git a/browser/base/content/browser-plugins.js b/browser/base/content/browser-plugins.js index fb68d262c65e..ddfe7ff7a519 100644 --- a/browser/base/content/browser-plugins.js +++ b/browser/base/content/browser-plugins.js @@ -17,7 +17,7 @@ var gPluginHandler = { "PluginContent:LinkClickCallback", ], - init: function() { + init() { const mm = window.messageManager; for (let msg of this.MESSAGES) { mm.addMessageListener(msg, this); @@ -25,7 +25,7 @@ var gPluginHandler = { window.addEventListener("unload", this); }, - uninit: function() { + uninit() { const mm = window.messageManager; for (let msg of this.MESSAGES) { mm.removeMessageListener(msg, this); @@ -33,13 +33,13 @@ var gPluginHandler = { window.removeEventListener("unload", this); }, - handleEvent: function(event) { + handleEvent(event) { if (event.type == "unload") { this.uninit(); } }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "PluginContent:ShowClickToPlayNotification": this.showClickToPlayNotification(msg.target, msg.data.plugins, msg.data.showNow, @@ -83,13 +83,13 @@ var gPluginHandler = { }, // Callback for user clicking on a disabled plugin - managePlugins: function() { + managePlugins() { BrowserOpenAddonsMgr("addons://list/plugin"); }, // Callback for user clicking on the link in a click-to-play plugin // (where the plugin has an update) - openPluginUpdatePage: function(pluginTag) { + openPluginUpdatePage(pluginTag) { let url = Services.blocklist.getPluginInfoURL(pluginTag); if (!url) { url = Services.blocklist.getPluginBlocklistURL(pluginTag); @@ -106,12 +106,12 @@ var gPluginHandler = { }, // Callback for user clicking a "reload page" link - reloadPage: function(browser) { + reloadPage(browser) { browser.reload(); }, // Callback for user clicking the help icon - openHelpPage: function() { + openHelpPage() { openHelpLink("plugin-crashed", false); }, @@ -139,7 +139,7 @@ var gPluginHandler = { * and activate plugins if necessary. * aNewState should be either "allownow" "allowalways" or "block" */ - _updatePluginPermission: function(aNotification, aPluginInfo, aNewState) { + _updatePluginPermission(aNotification, aPluginInfo, aNewState) { let permission; let expireType; let expireTime; @@ -208,7 +208,7 @@ var gPluginHandler = { }); }, - showClickToPlayNotification: function(browser, plugins, showNow, + showClickToPlayNotification(browser, plugins, showNow, principal, location) { // It is possible that we've received a message from the frame script to show // a click to play notification for a principal that no longer matches the one @@ -281,8 +281,8 @@ var gPluginHandler = { persistent: showNow, eventCallback: this._clickToPlayNotificationEventCallback, primaryPlugin: primaryPluginPermission, - pluginData: pluginData, - principal: principal, + pluginData, + principal, }; PopupNotifications.show(browser, "click-to-play-plugins", "", "plugins-notification-icon", @@ -290,20 +290,20 @@ var gPluginHandler = { browser.messageManager.sendAsyncMessage("BrowserPlugins:NotificationShown"); }, - removeNotification: function(browser, name) { + removeNotification(browser, name) { let notification = PopupNotifications.getNotification(name, browser); if (notification) PopupNotifications.remove(notification); }, - hideNotificationBar: function(browser, name) { + hideNotificationBar(browser, name) { let notificationBox = gBrowser.getNotificationBox(browser); let notification = notificationBox.getNotificationWithValue(name); if (notification) notificationBox.removeNotification(notification, true); }, - updateHiddenPluginUI: function(browser, haveInsecure, actions, + updateHiddenPluginUI(browser, haveInsecure, actions, principal, location) { let origin = principal.originNoSuffix; @@ -391,7 +391,7 @@ var gPluginHandler = { { label: gNavigatorBundle.getString("pluginContinueBlocking.label"), accessKey: gNavigatorBundle.getString("pluginContinueBlocking.accesskey"), - callback: function() { + callback() { Services.telemetry.getHistogramById("PLUGINS_INFOBAR_BLOCK"). add(true); @@ -403,7 +403,7 @@ var gPluginHandler = { { label: gNavigatorBundle.getString("pluginActivateTrigger.label"), accessKey: gNavigatorBundle.getString("pluginActivateTrigger.accesskey"), - callback: function() { + callback() { Services.telemetry.getHistogramById("PLUGINS_INFOBAR_ALLOW"). add(true); @@ -437,14 +437,14 @@ var gPluginHandler = { } }, - contextMenuCommand: function(browser, plugin, command) { + contextMenuCommand(browser, plugin, command) { browser.messageManager.sendAsyncMessage("BrowserPlugins:ContextMenuCommand", - { command: command }, { plugin: plugin }); + { command }, { plugin }); }, // Crashed-plugin observer. Notified once per plugin crash, before events // are dispatched to individual plugin instances. - NPAPIPluginCrashed : function(subject, topic, data) { + NPAPIPluginCrashed(subject, topic, data) { let propertyBag = subject; if (!(propertyBag instanceof Ci.nsIPropertyBag2) || !(propertyBag instanceof Ci.nsIWritablePropertyBag2) || @@ -493,7 +493,7 @@ var gPluginHandler = { * For a GMP, this is the pluginID. For NPAPI plugins (where "pluginID" * means something different), this is the runID. */ - showPluginCrashedNotification: function(browser, messageString, pluginID) { + showPluginCrashedNotification(browser, messageString, pluginID) { // If there's already an existing notification bar, don't do anything. let notificationBox = gBrowser.getNotificationBox(browser); let notification = notificationBox.getNotificationWithValue("plugin-crashed"); @@ -511,7 +511,7 @@ var gPluginHandler = { label: reloadLabel, accessKey: reloadKey, popup: null, - callback: function() { browser.reload(); }, + callback() { browser.reload(); }, }]; if (AppConstants.MOZ_CRASHREPORTER && diff --git a/browser/base/content/browser-refreshblocker.js b/browser/base/content/browser-refreshblocker.js index 50ea992c4006..2c6f2da97930 100644 --- a/browser/base/content/browser-refreshblocker.js +++ b/browser/base/content/browser-refreshblocker.js @@ -17,7 +17,7 @@ var RefreshBlocker = { gBrowser.removeEventListener("RefreshBlocked", this); }, - handleEvent: function(event) { + handleEvent(event) { if (event.type == "RefreshBlocked") { this.block(event.originalTarget, event.detail); } @@ -68,7 +68,7 @@ var RefreshBlocker = { let buttons = [{ label: refreshButtonText, accessKey: refreshButtonAccesskey, - callback: function() { + callback() { if (browser.messageManager) { browser.messageManager.sendAsyncMessage("RefreshBlocker:Refresh", data); } diff --git a/browser/base/content/browser-safebrowsing.js b/browser/base/content/browser-safebrowsing.js index 430d84f132bd..b8b5976e39e4 100644 --- a/browser/base/content/browser-safebrowsing.js +++ b/browser/base/content/browser-safebrowsing.js @@ -4,7 +4,7 @@ var gSafeBrowsing = { - setReportPhishingMenu: function() { + setReportPhishingMenu() { // In order to detect whether or not we're at the phishing warning // page, we have to check the documentURI instead of the currentURI. // This is because when the DocShell loads an error page, the @@ -42,7 +42,7 @@ var gSafeBrowsing = { * @param name String One of "Phish", "Error", "Malware" or "MalwareError" * @return String the report phishing URL. */ - getReportURL: function(name) { + getReportURL(name) { return SafeBrowsing.getReportURL(name, gBrowser.currentURI); } } diff --git a/browser/base/content/browser-sidebar.js b/browser/base/content/browser-sidebar.js index 5893e6015bb9..76128ecd8b2b 100644 --- a/browser/base/content/browser-sidebar.js +++ b/browser/base/content/browser-sidebar.js @@ -258,7 +258,7 @@ var SidebarUI = { let selBrowser = gBrowser.selectedBrowser; selBrowser.messageManager.sendAsyncMessage("Sidebar:VisibilityChange", - {commandID: commandID, isOpen: true} + {commandID, isOpen: true} ); BrowserUITelemetry.countSidebarEvent(commandID, "show"); }); @@ -296,7 +296,7 @@ var SidebarUI = { let selBrowser = gBrowser.selectedBrowser; selBrowser.focus(); selBrowser.messageManager.sendAsyncMessage("Sidebar:VisibilityChange", - {commandID: commandID, isOpen: false} + {commandID, isOpen: false} ); BrowserUITelemetry.countSidebarEvent(commandID, "hide"); }, diff --git a/browser/base/content/browser-syncui.js b/browser/base/content/browser-syncui.js index 299b1743d065..6d219570f840 100644 --- a/browser/base/content/browser-syncui.js +++ b/browser/base/content/browser-syncui.js @@ -39,7 +39,7 @@ var gSyncUI = { _syncStartTime: 0, _syncAnimationTimer: 0, - init: function() { + init() { Cu.import("resource://services-common/stringbundle.js"); // Proceed to set up the UI if Sync has already started up. @@ -137,7 +137,7 @@ var gSyncUI = { // Note that we don't show login errors in a notification bar here, but do // still need to track a login-failed state so the "Tools" menu updates // with the correct state. - _loginFailed: function() { + _loginFailed() { // If Sync isn't already ready, we don't want to force it to initialize // by referencing Weave.Status - and it isn't going to be accurate before // Sync is ready anyway. @@ -242,7 +242,7 @@ var gSyncUI = { this.updateUI(); }, - _getAppName: function() { + _getAppName() { let brand = new StringBundle("chrome://branding/locale/brand.properties"); return brand.get("brandShortName"); }, @@ -304,7 +304,7 @@ var gSyncUI = { }, // Open the legacy-sync device pairing UI. Note used for FxA Sync. - openAddDevice: function() { + openAddDevice() { if (!Weave.Utils.ensureMPUnlocked()) return; @@ -316,11 +316,11 @@ var gSyncUI = { "syncAddDevice", "centerscreen,chrome,resizable=no"); }, - openPrefs: function(entryPoint) { + openPrefs(entryPoint) { openPreferences("paneSync", { urlParams: { entrypoint: entryPoint } }); }, - openSignInAgainPage: function(entryPoint = "syncbutton") { + openSignInAgainPage(entryPoint = "syncbutton") { gFxAccounts.openSignInAgainPage(entryPoint); }, @@ -423,7 +423,7 @@ var gSyncUI = { } }), - formatLastSyncDate: function(date) { + formatLastSyncDate(date) { let dateFormat; let sixDaysAgo = (() => { let tempDate = new Date(); @@ -441,7 +441,7 @@ var gSyncUI = { return this._stringBundle.formatStringFromName("lastSync2.label", [lastSyncDateString], 1); }, - onClientsSynced: function() { + onClientsSynced() { let broadcaster = document.getElementById("sync-syncnow-state"); if (broadcaster) { if (Weave.Service.clientsEngine.stats.numClients > 1) { diff --git a/browser/base/content/browser-tabsintitlebar-stub.js b/browser/base/content/browser-tabsintitlebar-stub.js index f6b91506b8a1..41325ec1bb32 100644 --- a/browser/base/content/browser-tabsintitlebar-stub.js +++ b/browser/base/content/browser-tabsintitlebar-stub.js @@ -7,9 +7,9 @@ // don't have CAN_DRAW_IN_TITLEBAR defined. var TabsInTitlebar = { - init: function() {}, - uninit: function() {}, - allowedBy: function(condition, allow) {}, + init() {}, + uninit() {}, + allowedBy(condition, allow) {}, updateAppearance: function updateAppearance(aForce) {}, get enabled() { return document.documentElement.getAttribute("tabsintitlebar") == "true"; diff --git a/browser/base/content/browser-tabsintitlebar.js b/browser/base/content/browser-tabsintitlebar.js index ab882c8948c9..1a8065179597 100644 --- a/browser/base/content/browser-tabsintitlebar.js +++ b/browser/base/content/browser-tabsintitlebar.js @@ -7,7 +7,7 @@ // this one on platforms which don't have CAN_DRAW_IN_TITLEBAR defined. var TabsInTitlebar = { - init: function() { + init() { if (this._initialized) { return; } @@ -49,7 +49,7 @@ var TabsInTitlebar = { } }, - allowedBy: function(condition, allow) { + allowedBy(condition, allow) { if (allow) { if (condition in this._disallowed) { delete this._disallowed[condition]; @@ -69,18 +69,18 @@ var TabsInTitlebar = { return document.documentElement.getAttribute("tabsintitlebar") == "true"; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic == "nsPref:changed") this._readPref(); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (aEvent.type == "resolutionchange" && aEvent.target == window) { this._update(true); } }, - _onMenuMutate: function(aMutations) { + _onMenuMutate(aMutations) { for (let mutation of aMutations) { if (mutation.attributeName == "inactive" || mutation.attributeName == "autohide") { @@ -96,12 +96,12 @@ var TabsInTitlebar = { _prefName: "browser.tabs.drawInTitlebar", _lastSizeMode: null, - _readPref: function() { + _readPref() { this.allowedBy("pref", Services.prefs.getBoolPref(this._prefName)); }, - _update: function(aForce = false) { + _update(aForce = false) { let $ = id => document.getElementById(id); let rect = ele => ele.getBoundingClientRect(); let verticalMargins = cstyle => parseFloat(cstyle.marginBottom) + parseFloat(cstyle.marginTop); @@ -253,12 +253,12 @@ var TabsInTitlebar = { } }, - _sizePlaceholder: function(type, width) { + _sizePlaceholder(type, width) { Array.forEach(document.querySelectorAll(".titlebar-placeholder[type='" + type + "']"), function(node) { node.width = width; }); }, - uninit: function() { + uninit() { this._initialized = false; removeEventListener("resolutionchange", this); Services.prefs.removeObserver(this._prefName, this); diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index 045a48f7af68..3d2eb02ac1d2 100755 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -170,10 +170,10 @@ XPCOMUtils.defineLazyGetter(this, "Win7Features", function() { Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available) { let AeroPeek = Cu.import("resource:///modules/WindowsPreviewPerTab.jsm", {}).AeroPeek; return { - onOpenWindow: function() { + onOpenWindow() { AeroPeek.onOpenWindow(window); }, - onCloseWindow: function() { + onCloseWindow() { AeroPeek.onCloseWindow(window); } }; @@ -408,7 +408,7 @@ const gClickAndHoldListenersOnElement = { }; const gSessionHistoryObserver = { - observe: function(subject, topic, data) + observe(subject, topic, data) { if (topic != "browser:purge-session-history") return; @@ -459,7 +459,7 @@ function findChildShell(aDocument, aDocShell, aSoughtURI) { var gPopupBlockerObserver = { _reportButton: null, - onReportButtonMousedown: function(aEvent) + onReportButtonMousedown(aEvent) { // If this method is called on the same event tick as the popup gets // hidden, do nothing to avoid re-opening the popup. @@ -470,7 +470,7 @@ var gPopupBlockerObserver = { .openPopup(this._reportButton, "after_end", 0, 2, false, false, aEvent); }, - handleEvent: function(aEvent) + handleEvent(aEvent) { if (aEvent.originalTarget != gBrowser.selectedBrowser) return; @@ -541,7 +541,7 @@ var gPopupBlockerObserver = { } }, - toggleAllowPopupsForSite: function(aEvent) + toggleAllowPopupsForSite(aEvent) { var pm = Services.perms; var shouldBlock = aEvent.target.getAttribute("block") == "true"; @@ -554,7 +554,7 @@ var gPopupBlockerObserver = { gBrowser.getNotificationBox().removeCurrentNotification(); }, - fillPopupList: function(aEvent) + fillPopupList(aEvent) { // XXXben - rather than using |currentURI| here, which breaks down on multi-framed sites // we should really walk the blockedPopups and create a list of "allow for " @@ -657,7 +657,7 @@ var gPopupBlockerObserver = { }, null); }, - onPopupHiding: function(aEvent) { + onPopupHiding(aEvent) { if (aEvent.target.anchorNode.id == "page-report-button") aEvent.target.anchorNode.removeAttribute("open"); @@ -672,7 +672,7 @@ var gPopupBlockerObserver = { } }, - showBlockedPopup: function(aEvent) + showBlockedPopup(aEvent) { var target = aEvent.target; var popupReportIndex = target.getAttribute("popupReportIndex"); @@ -680,7 +680,7 @@ var gPopupBlockerObserver = { browser.unblockPopup(popupReportIndex); }, - showAllBlockedPopups: function(aBrowser) + showAllBlockedPopups(aBrowser) { aBrowser.retrieveListOfBlockedPopups().then(popups => { for (let i = 0; i < popups.length; i++) { @@ -690,7 +690,7 @@ var gPopupBlockerObserver = { }, null); }, - editPopupSettings: function() + editPopupSettings() { let prefillValue = ""; try { @@ -729,7 +729,7 @@ var gPopupBlockerObserver = { "_blank", "resizable,dialog=no,centerscreen", params); }, - dontShowMessage: function() + dontShowMessage() { var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage"); gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage); @@ -824,7 +824,7 @@ function gKeywordURIFixup({ target: browser, data: fixupInfo }) { { label: yesMessage, accessKey: gNavigatorBundle.getString("keywordURIFixup.goTo.accesskey"), - callback: function() { + callback() { // Do not set this preference while in private browsing. if (!PrivateBrowsingUtils.isWindowPrivate(window)) { let pref = "browser.fixup.domainwhitelist." + asciiHost; @@ -836,7 +836,7 @@ function gKeywordURIFixup({ target: browser, data: fixupInfo }) { { label: gNavigatorBundle.getString("keywordURIFixup.dismiss"), accessKey: gNavigatorBundle.getString("keywordURIFixup.dismiss.accesskey"), - callback: function() { + callback() { let notification = notificationBox.getNotificationWithValue("keyword-uri-fixup"); notificationBox.removeNotification(notification, true); } @@ -896,11 +896,11 @@ function _loadURIWithFlags(browser, uri, params) { } let loadParams = { - uri: uri, - flags: flags, + uri, + flags, referrer: referrer ? referrer.spec : null, - referrerPolicy: referrerPolicy, - postData: postData + referrerPolicy, + postData } if (params.userContextId) { @@ -1001,7 +1001,7 @@ addEventListener("DOMContentLoaded", function onDCL() { var gBrowserInit = { delayedStartupFinished: false, - onLoad: function() { + onLoad() { gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver, false); Services.obs.addObserver(gPluginHandler.NPAPIPluginCrashed, "plugin-crashed", false); @@ -1104,12 +1104,12 @@ var gBrowserInit = { this._loadHandled = true; }, - _cancelDelayedStartup: function() { + _cancelDelayedStartup() { window.removeEventListener("MozAfterPaint", this._boundDelayedStartup); this._boundDelayedStartup = null; }, - _delayedStartup: function() { + _delayedStartup() { let tmp = {}; Cu.import("resource://gre/modules/TelemetryTimestamps.jsm", tmp); let TelemetryTimestamps = tmp.TelemetryTimestamps; @@ -1470,7 +1470,7 @@ var gBrowserInit = { }, // Returns the URI(s) to load at startup. - _getUriToLoad: function() { + _getUriToLoad() { // window.arguments[0]: URI to load (string), or an nsIArray of // nsISupportsStrings to load, or a xul:tab of // a tabbrowser, which will be replaced by this @@ -1494,7 +1494,7 @@ var gBrowserInit = { return uri; }, - onUnload: function() { + onUnload() { // In certain scenarios it's possible for unload to be fired before onload, // (e.g. if the window is being closed after browser.js loads but before the // load completes). In that case, there's nothing to do here. @@ -2054,7 +2054,7 @@ var gLastOpenDirectory = { gPrefService.setComplexValue("browser.open.lastDir", Ci.nsILocalFile, this._lastDir); }, - reset: function() { + reset() { this._lastDir = null; } }; @@ -2111,10 +2111,10 @@ function loadURI(uri, referrer, postData, allowThirdPartyFixup, referrerPolicy, try { openLinkIn(uri, "current", { referrerURI: referrer, - referrerPolicy: referrerPolicy, - postData: postData, - allowThirdPartyFixup: allowThirdPartyFixup, - userContextId: userContextId, + referrerPolicy, + postData, + allowThirdPartyFixup, + userContextId, originPrincipal, forceAboutBlankViewerInCurrent, }); @@ -2367,7 +2367,7 @@ function BrowserViewSourceOfDocument(aArgsOrDocument) { */ function BrowserViewSource(browser) { BrowserViewSourceOfDocument({ - browser: browser, + browser, outerWindowID: browser.outerWindowID, URL: browser.currentURI.spec, }); @@ -2616,21 +2616,21 @@ var gMenuButtonBadgeManager = { downloadBadge: null, appUpdateBadge: null, - init: function() { + init() { PanelUI.panel.addEventListener("popupshowing", this, true); }, - uninit: function() { + uninit() { PanelUI.panel.removeEventListener("popupshowing", this, true); }, - handleEvent: function(e) { + handleEvent(e) { if (e.type === "popupshowing") { this.clearBadges(); } }, - _showBadge: function() { + _showBadge() { let badgeToShow = this.downloadBadge || this.appUpdateBadge || this.fxaBadge; if (badgeToShow) { @@ -2640,7 +2640,7 @@ var gMenuButtonBadgeManager = { } }, - _changeBadge: function(badgeId, badgeStatus = null) { + _changeBadge(badgeId, badgeStatus = null) { if (badgeId == this.BADGEID_APPUPDATE) { this.appUpdateBadge = badgeStatus; } else if (badgeId == this.BADGEID_DOWNLOAD) { @@ -2653,7 +2653,7 @@ var gMenuButtonBadgeManager = { this._showBadge(); }, - addBadge: function(badgeId, badgeStatus) { + addBadge(badgeId, badgeStatus) { if (!badgeStatus) { Cu.reportError("badgeStatus must be defined"); return; @@ -2661,11 +2661,11 @@ var gMenuButtonBadgeManager = { this._changeBadge(badgeId, badgeStatus); }, - removeBadge: function(badgeId) { + removeBadge(badgeId) { this._changeBadge(badgeId); }, - clearBadges: function() { + clearBadges() { this.appUpdateBadge = null; this.downloadBadge = null; this.fxaBadge = null; @@ -2680,7 +2680,7 @@ var gMenuButtonUpdateBadge = { timer: null, cancelObserverRegistered: false, - init: function() { + init() { try { this.enabled = Services.prefs.getBoolPref("app.update.badge"); } catch (e) {} @@ -2695,7 +2695,7 @@ var gMenuButtonUpdateBadge = { } }, - uninit: function() { + uninit() { if (this.timer) this.timer.cancel(); if (this.enabled) { @@ -2709,7 +2709,7 @@ var gMenuButtonUpdateBadge = { } }, - onMenuPanelCommand: function(event) { + onMenuPanelCommand(event) { if (event.originalTarget.getAttribute("update-status") === "succeeded") { // restart the app let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"] @@ -2726,7 +2726,7 @@ var gMenuButtonUpdateBadge = { } }, - observe: function(subject, topic, status) { + observe(subject, topic, status) { if (topic == "update-canceled") { this.reset(); return; @@ -2746,7 +2746,7 @@ var gMenuButtonUpdateBadge = { // The timer callback will call uninit() when it completes. }, - notify: function() { + notify() { // If the update is successfully applied, or if the updater has fallen back // to non-staged updates, add a badge to the hamburger menu to indicate an // update will be applied once the browser restarts. @@ -2754,7 +2754,7 @@ var gMenuButtonUpdateBadge = { this.displayBadge(true); }, - displayBadge: function(succeeded) { + displayBadge(succeeded) { let status = succeeded ? "succeeded" : "failed"; let badgeStatus = "update-" + status; gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_APPUPDATE, badgeStatus); @@ -2780,7 +2780,7 @@ var gMenuButtonUpdateBadge = { updateButton.hidden = false; }, - reset: function() { + reset() { gMenuButtonBadgeManager.removeBadge( gMenuButtonBadgeManager.BADGEID_APPUPDATE); let updateButton = document.getElementById("PanelUI-update-status"); @@ -2808,7 +2808,7 @@ const PREF_SSL_IMPACT = PREF_SSL_IMPACT_ROOTS.reduce((prefs, root) => { * us via async messaging. */ var BrowserOnClick = { - init: function() { + init() { let mm = window.messageManager; mm.addMessageListener("Browser:CertExceptionError", this); mm.addMessageListener("Browser:OpenCaptivePortalPage", this); @@ -2825,7 +2825,7 @@ var BrowserOnClick = { Services.obs.addObserver(this, "captive-portal-login-success", false); }, - uninit: function() { + uninit() { let mm = window.messageManager; mm.removeMessageListener("Browser:CertExceptionError", this); mm.removeMessageListener("Browser:SiteBlockedError", this); @@ -2841,7 +2841,7 @@ var BrowserOnClick = { Services.obs.removeObserver(this, "captive-portal-login-success"); }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "captive-portal-login-abort": case "captive-portal-login-success": @@ -2852,7 +2852,7 @@ var BrowserOnClick = { } }, - handleEvent: function(event) { + handleEvent(event) { if (!event.isTrusted || // Don't trust synthetic events event.button == 2) { return; @@ -2870,7 +2870,7 @@ var BrowserOnClick = { } }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Browser:CertExceptionError": this.onCertError(msg.target, msg.data.elementId, @@ -2928,7 +2928,7 @@ var BrowserOnClick = { } }, - onSSLErrorReport: function(browser, uri, securityInfo) { + onSSLErrorReport(browser, uri, securityInfo) { if (!Services.prefs.getBoolPref("security.ssl.errorReporting.enabled")) { Cu.reportError("User requested certificate error report sending, but certificate error reporting is disabled"); return; @@ -2945,7 +2945,7 @@ var BrowserOnClick = { uri.host, uri.port); }, - onCertError: function(browser, elementId, isTopFrame, location, securityInfoAsString) { + onCertError(browser, elementId, isTopFrame, location, securityInfoAsString) { let secHistogram = Services.telemetry.getHistogramById("SECURITY_UI"); let securityInfo; @@ -2959,7 +2959,7 @@ var BrowserOnClick = { let sslStatus = securityInfo.QueryInterface(Ci.nsISSLStatusProvider) .SSLStatus; let params = { exceptionAdded : false, - sslStatus : sslStatus }; + sslStatus }; try { switch (Services.prefs.getIntPref("browser.ssl_override_behavior")) { @@ -3014,7 +3014,7 @@ var BrowserOnClick = { } }, - onOpenCaptivePortalPage: function() { + onOpenCaptivePortalPage() { // Open a new tab with the canonical URL that we use to check for a captive portal. // It will be redirected to the login page. let canonicalURL = Services.prefs.getCharPref("captivedetect.canonicalURL"); @@ -3036,7 +3036,7 @@ var BrowserOnClick = { Services.obs.addObserver(tabCloser, "captive-portal-login-success", false); }, - onAboutBlocked: function(elementId, reason, isTopFrame, location) { + onAboutBlocked(elementId, reason, isTopFrame, location) { // Depending on what page we are displaying here (malware/phishing/unwanted) // use the right strings and links for each. let bucketName = ""; @@ -3091,7 +3091,7 @@ var BrowserOnClick = { * the next page also in the parent) and instructs the browser to open the url * in the current tab which will make it update the remoteness of the tab. */ - onE10sAboutNewTab: function(event, ownerDoc) { + onE10sAboutNewTab(event, ownerDoc) { let isTopFrame = (ownerDoc.defaultView.parent === ownerDoc.defaultView); if (!isTopFrame) { return; @@ -3107,7 +3107,7 @@ var BrowserOnClick = { } }, - ignoreWarningButton: function(reason) { + ignoreWarningButton(reason) { // Allow users to override and continue through to the site, // but add a notify bar as a reminder, so that they don't lose // track after, e.g., tab switching. @@ -3122,7 +3122,7 @@ var BrowserOnClick = { let buttons = [{ label: gNavigatorBundle.getString("safebrowsing.getMeOutOfHereButton.label"), accessKey: gNavigatorBundle.getString("safebrowsing.getMeOutOfHereButton.accessKey"), - callback: function() { getMeOutOfHere(); } + callback() { getMeOutOfHere(); } }]; let title; @@ -3131,7 +3131,7 @@ var BrowserOnClick = { buttons[1] = { label: gNavigatorBundle.getString("safebrowsing.notAnAttackButton.label"), accessKey: gNavigatorBundle.getString("safebrowsing.notAnAttackButton.accessKey"), - callback: function() { + callback() { openUILinkIn(gSafeBrowsing.getReportURL('MalwareMistake'), 'tab'); } }; @@ -3140,7 +3140,7 @@ var BrowserOnClick = { buttons[1] = { label: gNavigatorBundle.getString("safebrowsing.notADeceptiveSiteButton.label"), accessKey: gNavigatorBundle.getString("safebrowsing.notADeceptiveSiteButton.accessKey"), - callback: function() { + callback() { openUILinkIn(gSafeBrowsing.getReportURL('PhishMistake'), 'tab'); } }; @@ -3374,7 +3374,7 @@ var PrintPreviewListener = { _tabBeforePrintPreview: null, _simplifyPageTab: null, - getPrintPreviewBrowser: function() { + getPrintPreviewBrowser() { if (!this._printPreviewTab) { let browser = gBrowser.selectedTab.linkedBrowser; let preferredRemoteType = browser.remoteType; @@ -3387,23 +3387,23 @@ var PrintPreviewListener = { } return gBrowser.getBrowserForTab(this._printPreviewTab); }, - createSimplifiedBrowser: function() { + createSimplifiedBrowser() { this._simplifyPageTab = gBrowser.loadOneTab("about:blank", { inBackground: true }); return this.getSimplifiedSourceBrowser(); }, - getSourceBrowser: function() { + getSourceBrowser() { return this._tabBeforePrintPreview ? this._tabBeforePrintPreview.linkedBrowser : gBrowser.selectedBrowser; }, - getSimplifiedSourceBrowser: function() { + getSimplifiedSourceBrowser() { return this._simplifyPageTab ? gBrowser.getBrowserForTab(this._simplifyPageTab) : null; }, - getNavToolbox: function() { + getNavToolbox() { return gNavToolbox; }, - onEnter: function() { + onEnter() { // We might have accidentally switched tabs since the user invoked print // preview if (gBrowser.selectedTab != this._printPreviewTab) { @@ -3412,7 +3412,7 @@ var PrintPreviewListener = { gInPrintPreviewMode = true; this._toggleAffectedChrome(); }, - onExit: function() { + onExit() { gBrowser.selectedTab = this._tabBeforePrintPreview; this._tabBeforePrintPreview = null; gInPrintPreviewMode = false; @@ -3425,7 +3425,7 @@ var PrintPreviewListener = { gBrowser.deactivatePrintPreviewBrowsers(); this._printPreviewTab = null; }, - _toggleAffectedChrome: function() { + _toggleAffectedChrome() { gNavToolbox.collapsed = gInPrintPreviewMode; if (gInPrintPreviewMode) @@ -3435,7 +3435,7 @@ var PrintPreviewListener = { TabsInTitlebar.allowedBy("print-preview", !gInPrintPreviewMode); }, - _hideChrome: function() { + _hideChrome() { this._chromeState = {}; this._chromeState.sidebarOpen = SidebarUI.isOpen; @@ -3463,7 +3463,7 @@ var PrintPreviewListener = { syncNotifications.notificationsHidden = true; } }, - _showChrome: function() { + _showChrome() { if (this._chromeState.notificationsOpen) gBrowser.getNotificationBox().notificationsHidden = false; @@ -3499,20 +3499,20 @@ function FillInHTMLTooltip(tipElement) var browserDragAndDrop = { canDropLink: aEvent => Services.droppedLinkHandler.canDropLink(aEvent, true), - dragOver: function(aEvent) + dragOver(aEvent) { if (this.canDropLink(aEvent)) { aEvent.preventDefault(); } }, - dropLinks: function(aEvent, aDisallowInherit) { + dropLinks(aEvent, aDisallowInherit) { return Services.droppedLinkHandler.dropLinks(aEvent, aDisallowInherit); } }; var homeButtonObserver = { - onDrop: function(aEvent) + onDrop(aEvent) { // disallow setting home pages that inherit the principal let links = browserDragAndDrop.dropLinks(aEvent, true); @@ -3521,7 +3521,7 @@ var homeButtonObserver = { } }, - onDragOver: function(aEvent) + onDragOver(aEvent) { if (gPrefService.prefIsLocked("browser.startup.homepage")) { return; @@ -3529,7 +3529,7 @@ var homeButtonObserver = { browserDragAndDrop.dragOver(aEvent); aEvent.dropEffect = "link"; }, - onDragExit: function(aEvent) + onDragExit(aEvent) { } } @@ -3596,14 +3596,14 @@ var newWindowButtonObserver = { } const DOMLinkHandler = { - init: function() { + init() { let mm = window.messageManager; mm.addMessageListener("Link:AddFeed", this); mm.addMessageListener("Link:SetIcon", this); mm.addMessageListener("Link:AddSearch", this); }, - receiveMessage: function(aMsg) { + receiveMessage(aMsg) { switch (aMsg.name) { case "Link:AddFeed": let link = {type: aMsg.data.type, href: aMsg.data.href, title: aMsg.data.title}; @@ -3620,7 +3620,7 @@ const DOMLinkHandler = { } }, - setIcon: function(aBrowser, aURL, aLoadingPrincipal) { + setIcon(aBrowser, aURL, aLoadingPrincipal) { if (gBrowser.isFailedIcon(aURL)) return false; @@ -3632,7 +3632,7 @@ const DOMLinkHandler = { return true; }, - addSearch: function(aBrowser, aEngine, aURL) { + addSearch(aBrowser, aEngine, aURL) { let tab = gBrowser.getTabForBrowser(aBrowser); if (!tab) return; @@ -3642,7 +3642,7 @@ const DOMLinkHandler = { } const BrowserSearch = { - addEngine: function(browser, engine, uri) { + addEngine(browser, engine, uri) { // Check to see whether we've already added an engine with this title if (browser.engines) { if (browser.engines.some(e => e.title == engine.title)) @@ -3678,7 +3678,7 @@ const BrowserSearch = { * available when a page is loaded or the user switches tabs to a page that * has search engines. */ - updateOpenSearchBadge: function() { + updateOpenSearchBadge() { var searchBar = this.searchBar; if (!searchBar) return; @@ -3770,7 +3770,7 @@ const BrowserSearch = { * @return engine The search engine used to perform a search, or null if no * search was performed. */ - _loadSearch: function(searchText, useNewTab, purpose) { + _loadSearch(searchText, useNewTab, purpose) { let engine; // If the search bar is visible, use the current engine, otherwise, fall @@ -3794,7 +3794,7 @@ const BrowserSearch = { openLinkIn(submission.uri.spec, useNewTab ? "tab" : "current", { postData: submission.postData, - inBackground: inBackground, + inBackground, relatedToCurrent: true }); return engine; @@ -3820,14 +3820,14 @@ const BrowserSearch = { * This should only be called from the context menu. See * BrowserSearch.loadSearch for the preferred API. */ - loadSearchFromContext: function(terms) { + loadSearchFromContext(terms) { let engine = BrowserSearch._loadSearch(terms, true, "contextmenu"); if (engine) { BrowserSearch.recordSearchInTelemetry(engine, "contextmenu"); } }, - pasteAndSearch: function(event) { + pasteAndSearch(event) { BrowserSearch.searchBar.select(); goDoCommand("cmd_paste"); BrowserSearch.searchBar.handleSearchCommand(event); @@ -3850,7 +3850,7 @@ const BrowserSearch = { openUILinkIn(this.searchEnginesURL, where); }, - _getSearchEngineId: function(engine) { + _getSearchEngineId(engine) { if (engine && engine.identifier) { return engine.identifier; } @@ -3879,7 +3879,7 @@ const BrowserSearch = { * indicates where the item was in the suggestion list and how the user * selected it: {selection: {index: The selected index, kind: "key" or "mouse"}} */ - recordSearchInTelemetry: function(engine, source, details = {}) { + recordSearchInTelemetry(engine, source, details = {}) { BrowserUITelemetry.countSearchEvent(source, null, details.selection); try { BrowserUsageTelemetry.recordSearch(engine, source, details); @@ -3903,7 +3903,7 @@ const BrowserSearch = { * @param where * (string) Where was the search link opened (e.g. new tab, current tab, ..). */ - recordOneoffSearchInTelemetry: function(engine, source, type, where) { + recordOneoffSearchInTelemetry(engine, source, type, where) { let id = this._getSearchEngineId(engine) + "." + source; BrowserUITelemetry.countOneoffSearchEvent(id, type, where); try { @@ -4295,7 +4295,7 @@ var XULBrowserWindow = { // Left here for add-on compatibility, see bug 752434 inContentWhitelist: [], - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (aIID.equals(Ci.nsIWebProgressListener) || aIID.equals(Ci.nsIWebProgressListener2) || aIID.equals(Ci.nsISupportsWeakReference) || @@ -4325,34 +4325,34 @@ var XULBrowserWindow = { return this.canViewSource = document.getElementById("canViewSource"); }, - init: function() { + init() { // Initialize the security button's state and tooltip text. var securityUI = gBrowser.securityUI; this.onSecurityChange(null, null, securityUI.state, true); }, - setJSStatus: function() { + setJSStatus() { // unsupported }, - forceInitialBrowserRemote: function(aRemoteType) { + forceInitialBrowserRemote(aRemoteType) { let initBrowser = document.getAnonymousElementByAttribute(gBrowser, "anonid", "initialBrowser"); gBrowser.updateBrowserRemoteness(initBrowser, true, { remoteType: aRemoteType }); }, - forceInitialBrowserNonRemote: function(aOpener) { + forceInitialBrowserNonRemote(aOpener) { let initBrowser = document.getAnonymousElementByAttribute(gBrowser, "anonid", "initialBrowser"); gBrowser.updateBrowserRemoteness(initBrowser, false, { opener: aOpener }); }, - setDefaultStatus: function(status) { + setDefaultStatus(status) { this.defaultStatus = status; this.updateStatusField(); }, - setOverLink: function(url, anchorElt) { + setOverLink(url, anchorElt) { // Encode bidirectional formatting characters. // (RFC 3987 sections 3.2 and 4.1 paragraph 6) url = url.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g, @@ -4365,7 +4365,7 @@ var XULBrowserWindow = { LinkTargetDisplay.update(); }, - showTooltip: function(x, y, tooltip, direction) { + showTooltip(x, y, tooltip, direction) { if (Cc["@mozilla.org/widget/dragservice;1"].getService(Ci.nsIDragService). getCurrentSession()) { return; @@ -4381,16 +4381,16 @@ var XULBrowserWindow = { elt.openPopupAtScreen(anchor.boxObject.screenX + x, anchor.boxObject.screenY + y, false, null); }, - hideTooltip: function() { + hideTooltip() { let elt = document.getElementById("remoteBrowserTooltip"); elt.hidePopup(); }, - getTabCount: function() { + getTabCount() { return gBrowser.tabs.length; }, - updateStatusField: function() { + updateStatusField() { var text, type, types = ["overLink"]; if (this._busyUI) types.push("status"); @@ -4414,14 +4414,14 @@ var XULBrowserWindow = { }, // Called before links are navigated to to allow us to retarget them if needed. - onBeforeLinkTraversal: function(originalTarget, linkURI, linkNode, isAppTab) { + onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) { let target = BrowserUtils.onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab); SocialUI.closeSocialPanelForLinkTraversal(target, linkNode); return target; }, // Check whether this URI should load in the current process - shouldLoadURI: function(aDocShell, aURI, aReferrer) { + shouldLoadURI(aDocShell, aURI, aReferrer) { if (!gMultiProcessBrowser) return true; @@ -4442,13 +4442,13 @@ var XULBrowserWindow = { return true; }, - onProgressChange: function(aWebProgress, aRequest, + onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { // Do nothing. }, - onProgressChange64: function(aWebProgress, aRequest, + onProgressChange64(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { return this.onProgressChange(aWebProgress, aRequest, @@ -4457,7 +4457,7 @@ var XULBrowserWindow = { }, // This function fires only for the currently selected tab. - onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { const nsIWebProgressListener = Ci.nsIWebProgressListener; const nsIChannel = Ci.nsIChannel; @@ -4541,7 +4541,7 @@ var XULBrowserWindow = { } }, - onLocationChange: function(aWebProgress, aRequest, aLocationURI, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocationURI, aFlags) { var location = aLocationURI ? aLocationURI.spec : ""; // If displayed, hide the form validation popup. @@ -4685,15 +4685,15 @@ var XULBrowserWindow = { } }, - asyncUpdateUI: function() { + asyncUpdateUI() { FeedHandler.updateFeeds(); BrowserSearch.updateOpenSearchBadge(); }, // Left here for add-on compatibility, see bug 752434 - hideChromeForLocation: function() {}, + hideChromeForLocation() {}, - onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { this.status = aMessage; this.updateStatusField(); }, @@ -4708,7 +4708,7 @@ var XULBrowserWindow = { // 3. Called directly during this object's initializations. // aRequest will be null always in case 2 and 3, and sometimes in case 1 (for // instance, there won't be a request when STATE_BLOCKED_TRACKING_CONTENT is observed). - onSecurityChange: function(aWebProgress, aRequest, aState, aIsSimulated) { + onSecurityChange(aWebProgress, aRequest, aState, aIsSimulated) { // Don't need to do anything if the data we use to update the UI hasn't // changed let uri = gBrowser.currentURI; @@ -4780,7 +4780,7 @@ var LinkTargetDisplay = { return XULBrowserWindow.statusTextField.label != ""; }, - update: function() { + update() { clearTimeout(this._timer); window.removeEventListener("mousemove", this, true); @@ -4801,7 +4801,7 @@ var LinkTargetDisplay = { } }, - handleEvent: function(event) { + handleEvent(event) { switch (event.type) { case "mousemove": // Restart the delay since the mouse was moved @@ -4811,14 +4811,14 @@ var LinkTargetDisplay = { } }, - _showDelayed: function() { + _showDelayed() { this._timer = setTimeout(function(self) { XULBrowserWindow.updateStatusField(); window.removeEventListener("mousemove", self, true); }, this.DELAY_SHOW, this); }, - _hide: function() { + _hide() { clearTimeout(this._timer); XULBrowserWindow.updateStatusField(); @@ -4826,7 +4826,7 @@ var LinkTargetDisplay = { }; var CombinedStopReload = { - init: function() { + init() { if (this._initialized) return; @@ -4843,7 +4843,7 @@ var CombinedStopReload = { this.stop = stop; }, - uninit: function() { + uninit() { if (!this._initialized) return; @@ -4854,14 +4854,14 @@ var CombinedStopReload = { this.stop = null; }, - handleEvent: function(event) { + handleEvent(event) { // the only event we listen to is "click" on the stop button if (event.button == 0 && !this.stop.disabled) this._stopClicked = true; }, - switchToStop: function() { + switchToStop() { if (!this._initialized) return; @@ -4869,7 +4869,7 @@ var CombinedStopReload = { this.reload.setAttribute("displaystop", "true"); }, - switchToReload: function(aDelay) { + switchToReload(aDelay) { if (!this._initialized) return; @@ -4896,7 +4896,7 @@ var CombinedStopReload = { }, 650, this); }, - _cancelTransition: function() { + _cancelTransition() { if (this._timer) { clearTimeout(this._timer); this._timer = 0; @@ -4909,7 +4909,7 @@ var TabsProgressListener = { // we won't see STATE_START events for pre-rendered tabs. _startedLoadTimer: new WeakSet(), - onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { // Collect telemetry data about tab load times. if (aWebProgress.isTopLevel && (!aRequest.originalURI || aRequest.originalURI.spec.scheme != "about")) { if (aStateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW) { @@ -4963,7 +4963,7 @@ var TabsProgressListener = { } }, - onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, + onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) { // Filter out location changes caused by anchor navigation // or history.push/pop/replaceState. @@ -5001,7 +5001,7 @@ function nsBrowserAccess() { } nsBrowserAccess.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIBrowserDOMWindow, Ci.nsISupports]), - _openURIInNewTab: function(aURI, aReferrer, aReferrerPolicy, aIsPrivate, + _openURIInNewTab(aURI, aReferrer, aReferrerPolicy, aIsPrivate, aIsExternal, aForceNotRemote = false, aUserContextId = Ci.nsIScriptSecurityManager.DEFAULT_USER_CONTEXT_ID, aOpener = null) { @@ -5045,7 +5045,7 @@ nsBrowserAccess.prototype = { return browser; }, - openURI: function(aURI, aOpener, aWhere, aFlags) { + openURI(aURI, aOpener, aWhere, aFlags) { // This function should only ever be called if we're opening a URI // from a non-remote browser window (via nsContentTreeOwner). if (aOpener && Cu.isCrossProcessWrapper(aOpener)) { @@ -5126,7 +5126,7 @@ nsBrowserAccess.prototype = { gBrowser.loadURIWithFlags(aURI.spec, { flags: loadflags, referrerURI: referrer, - referrerPolicy: referrerPolicy, + referrerPolicy, }); } if (!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground")) @@ -5160,7 +5160,7 @@ nsBrowserAccess.prototype = { return null; }, - isTabContentWindow: function(aWindow) { + isTabContentWindow(aWindow) { return gBrowser.browsers.some(browser => browser.contentWindow == aWindow); }, @@ -5376,7 +5376,7 @@ function displaySecurityInfo() var gHomeButton = { prefDomain: "browser.startup.homepage", - observe: function(aSubject, aTopic, aPrefName) + observe(aSubject, aTopic, aPrefName) { if (aTopic != "nsPref:changed" || aPrefName != this.prefDomain) return; @@ -5384,7 +5384,7 @@ var gHomeButton = { this.updateTooltip(); }, - updateTooltip: function(homeButton) + updateTooltip(homeButton) { if (!homeButton) homeButton = document.getElementById("home-button"); @@ -5398,7 +5398,7 @@ var gHomeButton = { } }, - getHomePage: function() + getHomePage() { var url; try { @@ -5703,8 +5703,8 @@ function handleLinkClick(event, href, linkNode) { let params = { charset: doc.characterSet, allowMixedContent: persistAllowMixedContentInChildTab, - referrerURI: referrerURI, - referrerPolicy: referrerPolicy, + referrerURI, + referrerPolicy, noReferrer: BrowserUtils.linkHasNoReferrer(linkNode), originPrincipal: doc.nodePrincipal, }; @@ -5884,7 +5884,7 @@ var gPageStyleMenu = { // _pageStyleSheets: new WeakMap(), - init: function() { + init() { let mm = window.messageManager; mm.addMessageListener("PageStyle:StyleSheets", (msg) => { this._pageStyleSheets.set(msg.target.permanentKey, msg.data); @@ -5904,7 +5904,7 @@ var gPageStyleMenu = { * See the documentation for gPageStyleMenu for a description * of the Object structure. */ - getBrowserStyleSheets: function(browser) { + getBrowserStyleSheets(browser) { if (!browser) { browser = gBrowser.selectedBrowser; } @@ -5916,7 +5916,7 @@ var gPageStyleMenu = { return data.filteredStyleSheets; }, - _getStyleSheetInfo: function(browser) { + _getStyleSheetInfo(browser) { let data = this._pageStyleSheets.get(browser.permanentKey); if (!data) { return { @@ -5929,7 +5929,7 @@ var gPageStyleMenu = { return data; }, - fillPopup: function(menuPopup) { + fillPopup(menuPopup) { let styleSheetInfo = this._getStyleSheetInfo(gBrowser.selectedBrowser); var noStyle = menuPopup.firstChild; var persistentOnly = noStyle.nextSibling; @@ -5973,12 +5973,12 @@ var gPageStyleMenu = { sep.hidden = (noStyle.hidden && persistentOnly.hidden) || !haveAltSheets; }, - switchStyleSheet: function(title) { + switchStyleSheet(title) { let mm = gBrowser.selectedBrowser.messageManager; - mm.sendAsyncMessage("PageStyle:Switch", {title: title}); + mm.sendAsyncMessage("PageStyle:Switch", {title}); }, - disableStyle: function() { + disableStyle() { let mm = gBrowser.selectedBrowser.messageManager; mm.sendAsyncMessage("PageStyle:Disable"); }, @@ -5999,7 +5999,7 @@ function setStyleDisabled(disabled) { var LanguageDetectionListener = { - init: function() { + init() { window.messageManager.addMessageListener("Translation:DocumentState", msg => { Translation.documentStateReceived(msg.target, msg.data); }); @@ -6011,7 +6011,7 @@ var BrowserOffline = { _inited: false, // BrowserOffline Public Methods - init: function() + init() { if (!this._uiElement) this._uiElement = document.getElementById("workOfflineMenuitemState"); @@ -6023,14 +6023,14 @@ var BrowserOffline = { this._inited = true; }, - uninit: function() + uninit() { if (this._inited) { Services.obs.removeObserver(this, "network:offline-status-changed"); } }, - toggleOfflineStatus: function() + toggleOfflineStatus() { var ioService = Services.io; @@ -6043,7 +6043,7 @@ var BrowserOffline = { }, // nsIObserver - observe: function(aSubject, aTopic, aState) + observe(aSubject, aTopic, aState) { if (aTopic != "network:offline-status-changed") return; @@ -6054,7 +6054,7 @@ var BrowserOffline = { }, // BrowserOffline Implementation Methods - _canGoOffline: function() + _canGoOffline() { try { var cancelGoOffline = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool); @@ -6071,7 +6071,7 @@ var BrowserOffline = { }, _uiElement: null, - _updateOfflineUI: function(aOffline) + _updateOfflineUI(aOffline) { var offlineLocked = gPrefService.prefIsLocked("network.online"); if (offlineLocked) @@ -6165,7 +6165,7 @@ var OfflineApps = { let mainAction = { label: gNavigatorBundle.getString("offlineApps.allowStoring.label"), accessKey: gNavigatorBundle.getString("offlineApps.allowStoring.accesskey"), - callback: function() { + callback() { for (let [ciBrowser, ciDocId, ciUri] of notification.options.controlledItems) { OfflineApps.allowSite(ciBrowser, ciDocId, ciUri); } @@ -6174,7 +6174,7 @@ var OfflineApps = { let secondaryActions = [{ label: gNavigatorBundle.getString("offlineApps.dontAllow.label"), accessKey: gNavigatorBundle.getString("offlineApps.dontAllow.accesskey"), - callback: function() { + callback() { for (let [, , ciUri] of notification.options.controlledItems) { OfflineApps.disallowSite(ciUri); } @@ -6283,7 +6283,7 @@ var IndexedDBPromptHelper = { var mainAction = { label: gNavigatorBundle.getString("offlineApps.allowStoring.label"), accessKey: gNavigatorBundle.getString("offlineApps.allowStoring.accesskey"), - callback: function() { + callback() { observer.observe(null, responseTopic, Ci.nsIPermissionManager.ALLOW_ACTION); } @@ -6293,7 +6293,7 @@ var IndexedDBPromptHelper = { { label: gNavigatorBundle.getString("offlineApps.dontAllow.label"), accessKey: gNavigatorBundle.getString("offlineApps.dontAllow.accesskey"), - callback: function() { + callback() { observer.observe(null, responseTopic, Ci.nsIPermissionManager.DENY_ACTION); } @@ -6414,11 +6414,11 @@ function warnAboutClosingWindow() { } var MailIntegration = { - sendLinkForBrowser: function(aBrowser) { + sendLinkForBrowser(aBrowser) { this.sendMessage(aBrowser.currentURI.spec, aBrowser.contentTitle); }, - sendMessage: function(aBody, aSubject) { + sendMessage(aBody, aSubject) { // generate a mailto url based on the url and the url's title var mailtoUrl = "mailto:"; if (aBody) { @@ -6435,7 +6435,7 @@ var MailIntegration = { // a generic method which can be used to pass arbitrary urls to the operating // system. // aURL --> a nsIURI which represents the url to launch - _launchExternalUrl: function(aURL) { + _launchExternalUrl(aURL) { var extProtocolSvc = Cc["@mozilla.org/uriloader/external-protocol-service;1"] .getService(Ci.nsIExternalProtocolService); @@ -6504,7 +6504,7 @@ function AddKeywordForSearchField() { PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , uri: makeURI(bookmarkData.spec) - , title: title + , title , description: bookmarkData.description , keyword: "" , postData: bookmarkData.postData @@ -6840,7 +6840,7 @@ var gIdentityHandler = { * Handler for mouseclicks on the "More Information" button in the * "identity-popup" panel. */ - handleMoreInfoClick : function(event) { + handleMoreInfoClick(event) { displaySecurityInfo(); event.stopPropagation(); this._identityPopup.hidePopup(); @@ -6898,7 +6898,7 @@ var gIdentityHandler = { * Helper to parse out the important parts of _sslStatus (of the SSL cert in * particular) for use in constructing identity UI strings */ - getIdentityData : function() { + getIdentityData() { var result = {}; var cert = this._sslStatus.serverCert; @@ -6999,7 +6999,7 @@ var gIdentityHandler = { /** * Attempt to provide proper IDN treatment for host names */ - getEffectiveHost: function() { + getEffectiveHost() { if (!this._IDNService) this._IDNService = Cc["@mozilla.org/network/idn-service;1"] .getService(Ci.nsIIDNService); @@ -7179,7 +7179,7 @@ var gIdentityHandler = { let buttons = [{ label: gNavigatorBundle.getString("revokeOverride.label"), accessKey: gNavigatorBundle.getString("revokeOverride.accesskey"), - callback: function(aNotification, aButton) { + callback(aNotification, aButton) { try { let weakCryptoOverride = Cc["@mozilla.org/security/weakcryptooverride;1"] .getService(Ci.nsIWeakCryptoOverride); @@ -7369,7 +7369,7 @@ var gIdentityHandler = { /** * Click handler for the identity-box element in primary chrome. */ - handleIdentityButtonEvent : function(event) { + handleIdentityButtonEvent(event) { event.stopPropagation(); if ((event.type == "click" && event.button != 0) || @@ -7430,7 +7430,7 @@ var gIdentityHandler = { } }, - onDragStart: function(event) { + onDragStart(event) { if (gURLBar.getAttribute("pageproxystate") != "valid") return; @@ -7446,12 +7446,12 @@ var gIdentityHandler = { dt.setDragImage(this._identityIcon, 16, 16); }, - onLocationChange: function() { + onLocationChange() { this._permissionJustRemoved = false; this.updatePermissionHint(); }, - updatePermissionHint: function() { + updatePermissionHint() { if (!this._permissionList.hasChildNodes() && !this._permissionJustRemoved) { this._permissionEmptyHint.removeAttribute("hidden"); } else { @@ -7465,7 +7465,7 @@ var gIdentityHandler = { } }, - updateSitePermissions: function() { + updateSitePermissions() { while (this._permissionList.hasChildNodes()) this._permissionList.removeChild(this._permissionList.lastChild); @@ -7504,7 +7504,7 @@ var gIdentityHandler = { this.updatePermissionHint(); }, - _handleHeightChange: function(aFunction, aWillShowReloadHint) { + _handleHeightChange(aFunction, aWillShowReloadHint) { let heightBefore = getComputedStyle(this._permissionList).height; aFunction(); let heightAfter = getComputedStyle(this._permissionList).height; @@ -7518,7 +7518,7 @@ var gIdentityHandler = { this._identityPopupMultiView.setHeightToFit(heightChange); }, - _createPermissionItem: function(aPermission) { + _createPermissionItem(aPermission) { let container = document.createElement("hbox"); container.setAttribute("class", "identity-popup-permission-item"); container.setAttribute("align", "center"); @@ -7681,7 +7681,7 @@ var gPrivateBrowsingUI = { }; var gRemoteTabsUI = { - init: function() { + init() { if (window.location.href != getBrowserURL() && // Also check hidden window for the Mac no-window case window.location.href != "chrome://browser/content/hiddenWindow.xul") { @@ -7828,7 +7828,7 @@ function switchToTabHavingURI(aURI, aOpenNew, aOpenParams = {}) { } var RestoreLastSessionObserver = { - init: function() { + init() { if (SessionStore.canRestoreLastSession && !PrivateBrowsingUtils.isWindowPrivate(window)) { Services.obs.addObserver(this, "sessionstore-last-session-cleared", true); @@ -7836,7 +7836,7 @@ var RestoreLastSessionObserver = { } }, - observe: function() { + observe() { // The last session can only be restored once so there's // no way we need to re-enable our menu item. Services.obs.removeObserver(this, "sessionstore-last-session-cleared"); @@ -8047,7 +8047,7 @@ var MousePosTracker = { return this._windowUtils = window.getInterface(Ci.nsIDOMWindowUtils); }, - addListener: function(listener) { + addListener(listener) { if (this._listeners.has(listener)) return; @@ -8057,11 +8057,11 @@ var MousePosTracker = { this._callListener(listener); }, - removeListener: function(listener) { + removeListener(listener) { this._listeners.delete(listener); }, - handleEvent: function(event) { + handleEvent(event) { var fullZoom = this._windowUtils.fullZoom; this._x = event.screenX / fullZoom - window.mozInnerScreenX; this._y = event.screenY / fullZoom - window.mozInnerScreenY; @@ -8075,7 +8075,7 @@ var MousePosTracker = { }, this); }, - _callListener: function(listener) { + _callListener(listener) { let rect = listener.getMouseTargetRect(); let hover = this._x >= rect.left && this._x <= rect.right && @@ -8097,7 +8097,7 @@ var MousePosTracker = { }; var ToolbarIconColor = { - init: function() { + init() { this._initialized = true; window.addEventListener("activate", this); @@ -8111,7 +8111,7 @@ var ToolbarIconColor = { this.inferFromText(); }, - uninit: function() { + uninit() { this._initialized = false; window.removeEventListener("activate", this); @@ -8119,7 +8119,7 @@ var ToolbarIconColor = { Services.obs.removeObserver(this, "lightweight-theme-styling-update"); }, - handleEvent: function(event) { + handleEvent(event) { switch (event.type) { case "activate": case "deactivate": @@ -8128,7 +8128,7 @@ var ToolbarIconColor = { } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "lightweight-theme-styling-update": // inferFromText needs to run after LightweightThemeConsumer.jsm's @@ -8138,7 +8138,7 @@ var ToolbarIconColor = { } }, - inferFromText: function() { + inferFromText() { if (!this._initialized) return; @@ -8172,14 +8172,14 @@ var ToolbarIconColor = { } var PanicButtonNotifier = { - init: function() { + init() { this._initialized = true; if (window.PanicButtonNotifierShouldNotify) { delete window.PanicButtonNotifierShouldNotify; this.notify(); } }, - notify: function() { + notify() { if (!this._initialized) { window.PanicButtonNotifierShouldNotify = true; return; @@ -8196,14 +8196,14 @@ var PanicButtonNotifier = { Cu.reportError(ex); } }, - close: function() { + close() { let popup = document.getElementById("panic-button-success-notification"); popup.hidePopup(); }, }; var AboutPrivateBrowsingListener = { - init: function() { + init() { window.messageManager.addMessageListener( "AboutPrivateBrowsing:OpenPrivateWindow", msg => { diff --git a/browser/base/content/content.js b/browser/base/content/content.js index c5e1c0ec1451..837cd5863b80 100644 --- a/browser/base/content/content.js +++ b/browser/base/content/content.js @@ -103,8 +103,8 @@ var handleContentContextMenu = function(event) { let addonInfo = {}; let subject = { - event: event, - addonInfo: addonInfo, + event, + addonInfo, }; subject.wrappedJSObject = subject; Services.obs.notifyObservers(subject, "content-contextmenu", null); @@ -197,18 +197,18 @@ var handleContentContextMenu = function(event) { let mainWin = browser.ownerGlobal; mainWin.gContextMenuContentData = { isRemote: false, - event: event, + event, popupNode: event.target, - browser: browser, - addonInfo: addonInfo, + browser, + addonInfo, documentURIObject: doc.documentURIObject, - docLocation: docLocation, - charSet: charSet, - referrer: referrer, - referrerPolicy: referrerPolicy, - contentType: contentType, - contentDisposition: contentDisposition, - selectionInfo: selectionInfo, + docLocation, + charSet, + referrer, + referrerPolicy, + contentType, + contentDisposition, + selectionInfo, disableSetDesktopBackground: disableSetDesktopBg, loginFillInfo, parentAllowsMixedContent, @@ -262,7 +262,7 @@ function getSerializedSecurityInfo(docShell) { } var AboutNetAndCertErrorListener = { - init: function(chromeGlobal) { + init(chromeGlobal) { addMessageListener("CertErrorDetails", this); addMessageListener("Browser:CaptivePortalFreed", this); chromeGlobal.addEventListener('AboutNetErrorLoad', this, false, true); @@ -280,7 +280,7 @@ var AboutNetAndCertErrorListener = { return content.document.documentURI.startsWith("about:certerror"); }, - receiveMessage: function(msg) { + receiveMessage(msg) { if (!this.isAboutCertError) { return; } @@ -348,7 +348,7 @@ var AboutNetAndCertErrorListener = { content.dispatchEvent(new content.CustomEvent("AboutNetErrorCaptivePortalFreed")); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (!this.isAboutNetError && !this.isAboutCertError) { return; } @@ -372,7 +372,7 @@ var AboutNetAndCertErrorListener = { } }, - changedCertPrefs: function() { + changedCertPrefs() { for (let prefName of PREF_SSL_IMPACT) { if (Services.prefs.prefHasUserValue(prefName)) { return true; @@ -382,7 +382,7 @@ var AboutNetAndCertErrorListener = { return false; }, - onPageLoad: function(evt) { + onPageLoad(evt) { if (this.isAboutCertError) { let originalTarget = evt.originalTarget; let ownerDoc = originalTarget.ownerDocument; @@ -394,7 +394,7 @@ var AboutNetAndCertErrorListener = { detail: JSON.stringify({ enabled: Services.prefs.getBoolPref("security.ssl.errorReporting.enabled"), changedCertPrefs: this.changedCertPrefs(), - automatic: automatic + automatic }) })); @@ -402,16 +402,16 @@ var AboutNetAndCertErrorListener = { {reportStatus: TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN}); }, - openCaptivePortalPage: function(evt) { + openCaptivePortalPage(evt) { sendAsyncMessage("Browser:OpenCaptivePortalPage"); }, - onResetPreferences: function(evt) { + onResetPreferences(evt) { sendAsyncMessage("Browser:ResetSSLPreferences"); }, - onSetAutomatic: function(evt) { + onSetAutomatic(evt) { sendAsyncMessage("Browser:SetSSLErrorReportAuto", { automatic: evt.detail }); @@ -427,7 +427,7 @@ var AboutNetAndCertErrorListener = { } }, - onOverride: function(evt) { + onOverride(evt) { let {host, port} = content.document.mozDocumentURIIfNotForErrorPages; sendAsyncMessage("Browser:OverrideWeakCrypto", { uri: {host, port} }); } @@ -443,7 +443,7 @@ var ClickEventHandler = { .addSystemEventListener(global, "click", this, true); }, - handleEvent: function(event) { + handleEvent(event) { if (!event.isTrusted || event.defaultPrevented || event.button == 2) { return; } @@ -484,7 +484,7 @@ var ClickEventHandler = { let json = { button: event.button, shiftKey: event.shiftKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, href: null, title: null, - bookmark: false, referrerPolicy: referrerPolicy, + bookmark: false, referrerPolicy, originAttributes: principal ? principal.originAttributes : {}, isContentWindowPrivate: PrivateBrowsingUtils.isContentWindowPrivate(ownerDoc.defaultView)}; @@ -535,7 +535,7 @@ var ClickEventHandler = { } }, - onCertError: function(targetElement, ownerDoc) { + onCertError(targetElement, ownerDoc) { let docShell = ownerDoc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShell); @@ -547,7 +547,7 @@ var ClickEventHandler = { }); }, - onAboutBlocked: function(targetElement, ownerDoc) { + onAboutBlocked(targetElement, ownerDoc) { var reason = 'phishing'; if (/e=malwareBlocked/.test(ownerDoc.documentURI)) { reason = 'malware'; @@ -556,13 +556,13 @@ var ClickEventHandler = { } sendAsyncMessage("Browser:SiteBlockedError", { location: ownerDoc.location.href, - reason: reason, + reason, elementId: targetElement.getAttribute("id"), isTopFrame: (ownerDoc.defaultView.parent === ownerDoc.defaultView) }); }, - onAboutNetError: function(event, documentURI) { + onAboutNetError(event, documentURI) { let elmId = event.originalTarget.getAttribute("id"); if (elmId == "returnButton") { sendAsyncMessage("Browser:SSLErrorGoBack", {}); @@ -591,7 +591,7 @@ var ClickEventHandler = { * element. This includes SVG links, because callers expect |node| * to behave like an element, which SVG links (XLink) don't. */ - _hrefAndLinkNodeForClickEvent: function(event) { + _hrefAndLinkNodeForClickEvent(event) { function isHTMLLink(aNode) { // Be consistent with what nsContextMenu.js does. return ((aNode instanceof content.HTMLAnchorElement && aNode.href) || @@ -656,7 +656,7 @@ addMessageListener("webrtc:StartBrowserSharing", () => { let windowID = content.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils).outerWindowID; sendAsyncMessage("webrtc:response:StartBrowserSharing", { - windowID: windowID + windowID }); }); @@ -876,20 +876,20 @@ addMessageListener("Bookmarks:GetPageDetails", (message) => { let doc = content.document; let isErrorPage = /^about:(neterror|certerror|blocked)/.test(doc.documentURI); sendAsyncMessage("Bookmarks:GetPageDetails:Result", - { isErrorPage: isErrorPage, + { isErrorPage, description: PlacesUIUtils.getDescriptionFromDocument(doc) }); }); var LightWeightThemeWebInstallListener = { _previewWindow: null, - init: function() { + init() { addEventListener("InstallBrowserTheme", this, false, true); addEventListener("PreviewBrowserTheme", this, false, true); addEventListener("ResetBrowserThemePreview", this, false, true); }, - handleEvent: function(event) { + handleEvent(event) { switch (event.type) { case "InstallBrowserTheme": { sendAsyncMessage("LightWeightThemeWebInstaller:Install", { @@ -923,7 +923,7 @@ var LightWeightThemeWebInstallListener = { } }, - _resetPreviewWindow: function() { + _resetPreviewWindow() { this._previewWindow.removeEventListener("pagehide", this, true); this._previewWindow = null; } @@ -982,11 +982,11 @@ addMessageListener("ContextMenu:SetAsDesktopBackground", (message) => { var PageInfoListener = { - init: function() { + init() { addMessageListener("PageInfo:getData", this); }, - receiveMessage: function(message) { + receiveMessage(message) { let strings = message.data.strings; let window; let document; @@ -1017,7 +1017,7 @@ var PageInfoListener = { this.getMediaInfo(document, window, strings); }, - getImageInfo: function(imageElement) { + getImageInfo(imageElement) { let imageInfo = null; if (imageElement) { imageInfo = { @@ -1030,7 +1030,7 @@ var PageInfoListener = { return imageInfo; }, - getMetaInfo: function(document) { + getMetaInfo(document) { let metaViewRows = []; // Get the meta tags from the page. @@ -1044,7 +1044,7 @@ var PageInfoListener = { return metaViewRows; }, - getWindowInfo: function(window) { + getWindowInfo(window) { let windowInfo = {}; windowInfo.isTopWindow = window == window.top; @@ -1058,7 +1058,7 @@ var PageInfoListener = { return windowInfo; }, - getDocumentInfo: function(document) { + getDocumentInfo(document) { let docInfo = {}; docInfo.title = document.title; docInfo.location = document.location.toString(); @@ -1079,7 +1079,7 @@ var PageInfoListener = { return docInfo; }, - getFeedsInfo: function(document, strings) { + getFeedsInfo(document, strings) { let feeds = []; // Get the feeds from the page. let linkNodes = document.getElementsByTagName("link"); @@ -1110,13 +1110,13 @@ var PageInfoListener = { }, // Only called once to get the media tab's media elements from the content page. - getMediaInfo: function(document, window, strings) + getMediaInfo(document, window, strings) { let frameList = this.goThroughFrames(document, window); Task.spawn(() => this.processFrames(document, frameList, strings)); }, - goThroughFrames: function(document, window) + goThroughFrames(document, window) { let frameList = [document]; if (window && window.frames.length > 0) { @@ -1130,7 +1130,7 @@ var PageInfoListener = { return frameList; }, - processFrames: function*(document, frameList, strings) + *processFrames(document, frameList, strings) { let nodeCount = 0; for (let doc of frameList) { @@ -1155,7 +1155,7 @@ var PageInfoListener = { sendAsyncMessage("PageInfo:mediaData", {isComplete: true}); }, - getMediaItems: function(document, strings, elem) + getMediaItems(document, strings, elem) { // Check for images defined in CSS (e.g. background, borders) let computedStyle = elem.ownerGlobal.getComputedStyle(elem); @@ -1241,7 +1241,7 @@ var PageInfoListener = { * makePreview in pageInfo.js uses to figure out how to display the preview. */ - serializeElementInfo: function(document, url, type, alt, item, isBG) + serializeElementInfo(document, url, type, alt, item, isBG) { let result = {}; @@ -1322,7 +1322,7 @@ var PageInfoListener = { // Other Misc Stuff // Modified from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html // parse a node to extract the contents of the node - getValueText: function(node) + getValueText(node) { let valueText = ""; @@ -1362,7 +1362,7 @@ var PageInfoListener = { // Copied from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html. // Traverse the tree in search of an img or area element and grab its alt tag. - getAltText: function(node) + getAltText(node) { let altText = ""; @@ -1380,7 +1380,7 @@ var PageInfoListener = { // Copied from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html. // Strip leading and trailing whitespace, and replace multiple consecutive whitespace characters with a single space. - stripWS: function(text) + stripWS(text) { let middleRE = /\s+/g; let endRE = /(^\s+)|(\s+$)/g; diff --git a/browser/base/content/contentSearchUI.js b/browser/base/content/contentSearchUI.js index 688d8b1cfe4b..d3f8d5f143ce 100644 --- a/browser/base/content/contentSearchUI.js +++ b/browser/base/content/contentSearchUI.js @@ -90,7 +90,7 @@ ContentSearchUIController.prototype = { } this._defaultEngine = { name: engine.name, - icon: icon, + icon, }; this._updateDefaultEngineHeader(); @@ -189,7 +189,7 @@ ContentSearchUIController.prototype = { return this._suggestionsList.children.length; }, - selectAndUpdateInput: function(idx) { + selectAndUpdateInput(idx) { this.selectedIndex = idx; let newValue = this.suggestionAtIndex(idx) || this._stickyInputValue; // Setting the input value when the value has not changed commits the current @@ -200,12 +200,12 @@ ContentSearchUIController.prototype = { this._updateSearchWithHeader(); }, - suggestionAtIndex: function(idx) { + suggestionAtIndex(idx) { let row = this._suggestionsList.children[idx]; return row ? row.textContent : null; }, - deleteSuggestionAtIndex: function(idx) { + deleteSuggestionAtIndex(idx) { // Only form history suggestions can be deleted. if (this.isFormHistorySuggestionAtIndex(idx)) { let suggestionStr = this.suggestionAtIndex(idx); @@ -215,20 +215,20 @@ ContentSearchUIController.prototype = { } }, - isFormHistorySuggestionAtIndex: function(idx) { + isFormHistorySuggestionAtIndex(idx) { let row = this._suggestionsList.children[idx]; return row && row.classList.contains("formHistory"); }, - addInputValueToFormHistory: function() { + addInputValueToFormHistory() { this._sendMsg("AddFormHistoryEntry", this.input.value); }, - handleEvent: function(event) { + handleEvent(event) { this["_on" + event.type[0].toUpperCase() + event.type.substr(1)](event); }, - _onCommand: function(aEvent) { + _onCommand(aEvent) { if (this.selectedButtonIndex == this._oneOffButtons.length) { // Settings button was selected. this._sendMsg("ManageEngines"); @@ -242,7 +242,7 @@ ContentSearchUIController.prototype = { } }, - search: function(aEvent) { + search(aEvent) { if (!this.defaultEngine) { return; // Not initialized yet. } @@ -291,7 +291,7 @@ ContentSearchUIController.prototype = { this.addInputValueToFormHistory(); }, - _onInput: function() { + _onInput() { if (!this.input.value) { this._stickyInputValue = ""; this._hideSuggestions(); @@ -304,7 +304,7 @@ ContentSearchUIController.prototype = { this._updateSearchWithHeader(); }, - _onKeypress: function(event) { + _onKeypress(event) { let selectedIndexDelta = 0; let selectedSuggestionDelta = 0; let selectedOneOffDelta = 0; @@ -451,7 +451,7 @@ ContentSearchUIController.prototype = { }, _currentEngineIndex: -1, - _cycleCurrentEngine: function(aReverse) { + _cycleCurrentEngine(aReverse) { if ((this._currentEngineIndex == this._engines.length - 1 && !aReverse) || (this._currentEngineIndex == 0 && aReverse)) { return; @@ -461,7 +461,7 @@ ContentSearchUIController.prototype = { this._sendMsg("SetCurrentEngine", engineName); }, - _onFocus: function() { + _onFocus() { if (this._mousedown) { return; } @@ -474,7 +474,7 @@ ContentSearchUIController.prototype = { this._speculativeConnect(); }, - _onBlur: function() { + _onBlur() { if (this._mousedown) { // At this point, this.input has lost focus, but a new element has not yet // received it. If we re-focus this.input directly, the new element will @@ -486,7 +486,7 @@ ContentSearchUIController.prototype = { this._hideSuggestions(); }, - _onMousemove: function(event) { + _onMousemove(event) { let idx = this._indexOfTableItem(event.target); if (idx >= this.numSuggestions) { this.selectedButtonIndex = idx - this.numSuggestions; @@ -495,14 +495,14 @@ ContentSearchUIController.prototype = { this.selectedIndex = idx; }, - _onMouseup: function(event) { + _onMouseup(event) { if (event.button == 2) { return; } this._onCommand(event); }, - _onMouseout: function(event) { + _onMouseout(event) { // We only deselect one-off buttons and the settings button when they are // moused out. let idx = this._indexOfTableItem(event.originalTarget); @@ -511,22 +511,22 @@ ContentSearchUIController.prototype = { } }, - _onClick: function(event) { + _onClick(event) { this._onMouseup(event); }, - _onContentSearchService: function(event) { + _onContentSearchService(event) { let methodName = "_onMsg" + event.detail.type; if (methodName in this) { this[methodName](event.detail.data); } }, - _onMsgFocusInput: function(event) { + _onMsgFocusInput(event) { this.input.focus(); }, - _onMsgSuggestions: function(suggestions) { + _onMsgSuggestions(suggestions) { // Ignore the suggestions if their search string or engine doesn't match // ours. Due to the async nature of message passing, this can easily happen // when the user types quickly. @@ -581,13 +581,13 @@ ContentSearchUIController.prototype = { } }, - _onMsgSuggestionsCancelled: function() { + _onMsgSuggestionsCancelled() { if (!this._table.hidden) { this._hideSuggestions(); } }, - _onMsgState: function(state) { + _onMsgState(state) { this.engines = state.engines; // No point updating the default engine (and the header) if there's no change. if (this.defaultEngine && @@ -598,16 +598,16 @@ ContentSearchUIController.prototype = { this.defaultEngine = state.currentEngine; }, - _onMsgCurrentState: function(state) { + _onMsgCurrentState(state) { this._onMsgState(state); }, - _onMsgCurrentEngine: function(engine) { + _onMsgCurrentEngine(engine) { this.defaultEngine = engine; this._pendingOneOffRefresh = true; }, - _onMsgStrings: function(strings) { + _onMsgStrings(strings) { this._strings = strings; this._updateDefaultEngineHeader(); this._updateSearchWithHeader(); @@ -616,7 +616,7 @@ ContentSearchUIController.prototype = { this.input.setAttribute("placeholder", this._strings.searchPlaceholder); }, - _updateDefaultEngineHeader: function() { + _updateDefaultEngineHeader() { let header = document.getElementById("contentSearchDefaultEngineHeader"); header.firstChild.setAttribute("src", this.defaultEngine.icon); if (!this._strings) { @@ -629,7 +629,7 @@ ContentSearchUIController.prototype = { this._strings.searchHeader.replace("%S", this.defaultEngine.name))); }, - _updateSearchWithHeader: function() { + _updateSearchWithHeader() { if (!this._strings) { return; } @@ -642,13 +642,13 @@ ContentSearchUIController.prototype = { } }, - _speculativeConnect: function() { + _speculativeConnect() { if (this.defaultEngine) { this._sendMsg("SpeculativeConnect", this.defaultEngine.name); } }, - _makeTableRow: function(type, suggestionStr, currentRow, searchWords) { + _makeTableRow(type, suggestionStr, currentRow, searchWords) { let row = document.createElementNS(HTML_NS, "tr"); row.dir = "auto"; row.classList.add("contentSearchSuggestionRow"); @@ -685,28 +685,28 @@ ContentSearchUIController.prototype = { }, // Converts favicon array buffer into a data URI. - _getFaviconURIFromBuffer: function(buffer) { + _getFaviconURIFromBuffer(buffer) { let blob = new Blob([buffer]); return URL.createObjectURL(blob); }, // Adds "@2x" to the name of the given PNG url for "retina" screens. - _getImageURIForCurrentResolution: function(uri) { + _getImageURIForCurrentResolution(uri) { if (window.devicePixelRatio > 1) { return uri.replace(/\.png$/, "@2x.png"); } return uri; }, - _getSearchEngines: function() { + _getSearchEngines() { this._sendMsg("GetState"); }, - _getStrings: function() { + _getStrings() { this._sendMsg("GetStrings"); }, - _getSuggestions: function() { + _getSuggestions() { this._stickyInputValue = this.input.value; if (this.defaultEngine) { this._sendMsg("GetSuggestions", { @@ -716,13 +716,13 @@ ContentSearchUIController.prototype = { } }, - _clearSuggestionRows: function() { + _clearSuggestionRows() { while (this._suggestionsList.firstElementChild) { this._suggestionsList.firstElementChild.remove(); } }, - _hideSuggestions: function() { + _hideSuggestions() { this.input.setAttribute("aria-expanded", "false"); this.selectedIndex = -1; this.selectedButtonIndex = -1; @@ -730,7 +730,7 @@ ContentSearchUIController.prototype = { this._table.hidden = true; }, - _indexOfTableItem: function(elt) { + _indexOfTableItem(elt) { if (elt.classList.contains("contentSearchOneOffItem")) { return this.numSuggestions + this._oneOffButtons.indexOf(elt); } @@ -746,7 +746,7 @@ ContentSearchUIController.prototype = { return elt.rowIndex; }, - _makeTable: function(id) { + _makeTable(id) { this._table = document.createElementNS(HTML_NS, "table"); this._table.id = id; this._table.hidden = true; @@ -815,7 +815,7 @@ ContentSearchUIController.prototype = { return this._table; }, - _setUpOneOffButtons: function() { + _setUpOneOffButtons() { // Sometimes we receive a CurrentEngine message from the ContentSearch service // before we've received a State message - i.e. before we have our engines. if (!this._engines) { @@ -896,11 +896,11 @@ ContentSearchUIController.prototype = { this._oneOffsTable.hidden = false; }, - _sendMsg: function(type, data = null) { + _sendMsg(type, data = null) { dispatchEvent(new CustomEvent("ContentSearchClient", { detail: { - type: type, - data: data, + type, + data, }, })); }, diff --git a/browser/base/content/pageinfo/pageInfo.js b/browser/base/content/pageinfo/pageInfo.js index 1e96c4e8b632..dd4336951248 100644 --- a/browser/base/content/pageinfo/pageInfo.js +++ b/browser/base/content/pageinfo/pageInfo.js @@ -24,12 +24,12 @@ pageInfoTreeView.prototype = { set rowCount(c) { throw "rowCount is a readonly property"; }, get rowCount() { return this.rows; }, - setTree: function(tree) + setTree(tree) { this.tree = tree; }, - getCellText: function(row, column) + getCellText(row, column) { // row can be null, but js arrays are 0-indexed. // colidx cannot be null, but can be larger than the number @@ -38,16 +38,16 @@ pageInfoTreeView.prototype = { return this.data[row][column.index] || ""; }, - setCellValue: function(row, column, value) + setCellValue(row, column, value) { }, - setCellText: function(row, column, value) + setCellText(row, column, value) { this.data[row][column.index] = value; }, - addRow: function(row) + addRow(row) { this.rows = this.data.push(row); this.rowCountChanged(this.rows - 1, 1); @@ -56,24 +56,24 @@ pageInfoTreeView.prototype = { } }, - addRows: function(rows) + addRows(rows) { for (let row of rows) { this.addRow(row); } }, - rowCountChanged: function(index, count) + rowCountChanged(index, count) { this.tree.rowCountChanged(index, count); }, - invalidate: function() + invalidate() { this.tree.invalidate(); }, - clear: function() + clear() { if (this.tree) this.tree.rowCountChanged(0, -this.rows); @@ -81,12 +81,12 @@ pageInfoTreeView.prototype = { this.data = [ ]; }, - handleCopy: function(row) + handleCopy(row) { return (row < 0 || this.copycol < 0) ? "" : (this.data[row][this.copycol] || ""); }, - performActionOnRow: function(action, row) + performActionOnRow(action, row) { if (action == "copy") { var data = this.handleCopy(row) @@ -94,7 +94,7 @@ pageInfoTreeView.prototype = { } }, - onPageMediaSort : function(columnname) + onPageMediaSort(columnname) { var tree = document.getElementById(this.treeid); var treecol = tree.columns.getNamedColumn(columnname); @@ -121,29 +121,29 @@ pageInfoTreeView.prototype = { this.sortcol = treecol.index; }, - getRowProperties: function(row) { return ""; }, - getCellProperties: function(row, column) { return ""; }, - getColumnProperties: function(column) { return ""; }, - isContainer: function(index) { return false; }, - isContainerOpen: function(index) { return false; }, - isSeparator: function(index) { return false; }, - isSorted: function() { return this.sortcol > -1 }, - canDrop: function(index, orientation) { return false; }, - drop: function(row, orientation) { return false; }, - getParentIndex: function(index) { return 0; }, - hasNextSibling: function(index, after) { return false; }, - getLevel: function(index) { return 0; }, - getImageSrc: function(row, column) { }, - getProgressMode: function(row, column) { }, - getCellValue: function(row, column) { }, - toggleOpenState: function(index) { }, - cycleHeader: function(col) { }, - selectionChanged: function() { }, - cycleCell: function(row, column) { }, - isEditable: function(row, column) { return false; }, - isSelectable: function(row, column) { return false; }, - performAction: function(action) { }, - performActionOnCell: function(action, row, column) { } + getRowProperties(row) { return ""; }, + getCellProperties(row, column) { return ""; }, + getColumnProperties(column) { return ""; }, + isContainer(index) { return false; }, + isContainerOpen(index) { return false; }, + isSeparator(index) { return false; }, + isSorted() { return this.sortcol > -1 }, + canDrop(index, orientation) { return false; }, + drop(row, orientation) { return false; }, + getParentIndex(index) { return 0; }, + hasNextSibling(index, after) { return false; }, + getLevel(index) { return 0; }, + getImageSrc(row, column) { }, + getProgressMode(row, column) { }, + getCellValue(row, column) { }, + toggleOpenState(index) { }, + cycleHeader(col) { }, + selectionChanged() { }, + cycleCell(row, column) { }, + isEditable(row, column) { return false; }, + isSelectable(row, column) { return false; }, + performAction(action) { }, + performActionOnCell(action, row, column) { } }; // mmm, yummy. global variables. @@ -359,7 +359,7 @@ function loadPageInfo(frameOuterWindowID, imageElement, browser) // Look for pageInfoListener in content.js. Sends message to listener with arguments. mm.sendAsyncMessage("PageInfo:getData", {strings: gStrings, - frameOuterWindowID: frameOuterWindowID}, + frameOuterWindowID}, { imageElement }); let pageInfoData; @@ -517,10 +517,10 @@ function toggleGroupbox(id) function openCacheEntry(key, cb) { var checkCacheListener = { - onCacheEntryCheck: function(entry, appCache) { + onCacheEntryCheck(entry, appCache) { return Components.interfaces.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable: function(entry, isNew, appCache, status) { + onCacheEntryAvailable(entry, isNew, appCache, status) { cb(entry); } }; @@ -1004,7 +1004,7 @@ function makeBlockImage(url) } var imagePermissionObserver = { - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { if (document.getElementById("mediaPreviewBox").collapsed) return; diff --git a/browser/base/content/pageinfo/permissions.js b/browser/base/content/pageinfo/permissions.js index b3e1720dc544..5a563c035e97 100644 --- a/browser/base/content/pageinfo/permissions.js +++ b/browser/base/content/pageinfo/permissions.js @@ -20,7 +20,7 @@ var gPermissions = SitePermissions.listPermissions().sort((a, b) => { gPermissions.push("plugins"); var permissionObserver = { - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { var permission = aSubject.QueryInterface(Components.interfaces.nsIPermission); diff --git a/browser/base/content/pageinfo/security.js b/browser/base/content/pageinfo/security.js index 2638cb13d76e..e3f0fdc886b9 100644 --- a/browser/base/content/pageinfo/security.js +++ b/browser/base/content/pageinfo/security.js @@ -9,18 +9,18 @@ XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper", "resource://gre/modules/LoginHelper.jsm"); var security = { - init: function(uri, windowInfo) { + init(uri, windowInfo) { this.uri = uri; this.windowInfo = windowInfo; }, // Display the server certificate (static) - viewCert : function() { + viewCert() { var cert = security._cert; viewCertHelper(window, cert); }, - _getSecurityInfo : function() { + _getSecurityInfo() { const nsISSLStatusProvider = Components.interfaces.nsISSLStatusProvider; const nsISSLStatus = Components.interfaces.nsISSLStatus; @@ -54,15 +54,15 @@ var security = { this.mapIssuerOrganization(cert.issuerOrganization) || cert.issuerName; var retval = { - hostName : hostName, + hostName, cAName : issuerName, encryptionAlgorithm : undefined, encryptionStrength : undefined, version: undefined, - isBroken : isBroken, - isMixed : isMixed, - isEV : isEV, - cert : cert, + isBroken, + isMixed, + isEV, + cert, certificateTransparency : undefined }; @@ -117,21 +117,21 @@ var security = { return retval; } return { - hostName : hostName, + hostName, cAName : "", encryptionAlgorithm : "", encryptionStrength : 0, version: "", - isBroken : isBroken, - isMixed : isMixed, - isEV : isEV, + isBroken, + isMixed, + isEV, cert : null, certificateTransparency : null }; }, // Find the secureBrowserUI object (if present) - _getSecurityUI : function() { + _getSecurityUI() { if (window.opener.gBrowser) return window.opener.gBrowser.securityUI; return null; @@ -140,7 +140,7 @@ var security = { // Interface for mapping a certificate issuer organization to // the value to be displayed. // Bug 82017 - this implementation should be moved to pipnss C++ code - mapIssuerOrganization: function(name) { + mapIssuerOrganization(name) { if (!name) return null; if (name == "RSA Data Security, Inc.") return "Verisign, Inc."; @@ -152,7 +152,7 @@ var security = { /** * Open the cookie manager window */ - viewCookies : function() + viewCookies() { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); @@ -181,7 +181,7 @@ var security = { /** * Open the login manager window */ - viewPasswords : function() { + viewPasswords() { LoginHelper.openPasswordManager(window, this._getSecurityInfo().hostName); }, diff --git a/browser/base/content/sanitize.js b/browser/base/content/sanitize.js index 725daa64ed5a..53cf4e943d37 100644 --- a/browser/base/content/sanitize.js +++ b/browser/base/content/sanitize.js @@ -38,14 +38,14 @@ function Sanitizer() { } Sanitizer.prototype = { // warning to the caller: this one may raise an exception (e.g. bug #265028) - clearItem: function(aItemName) + clearItem(aItemName) { this.items[aItemName].clear(); }, prefDomain: "", - getNameFromPreference: function(aPreferenceName) + getNameFromPreference(aPreferenceName) { return aPreferenceName.substr(this.prefDomain.length); }, @@ -516,7 +516,7 @@ Sanitizer.prototype = { openWindows: { privateStateForNewWindow: "non-private", - _canCloseWindow: function(aWindow) { + _canCloseWindow(aWindow) { if (aWindow.CanCloseWindow()) { // We already showed PermitUnload for the window, so let's // make sure we don't do it again when we actually close the @@ -526,7 +526,7 @@ Sanitizer.prototype = { } return false; }, - _resetAllWindowClosures: function(aWindowList) { + _resetAllWindowClosures(aWindowList) { for (let win of aWindowList) { win.skipNextCanClose = false; } diff --git a/browser/base/content/social-content.js b/browser/base/content/social-content.js index b5fa6a5c4bda..071d057d522c 100644 --- a/browser/base/content/social-content.js +++ b/browser/base/content/social-content.js @@ -114,7 +114,7 @@ const SocialErrorListener = { webNav.loadURI(url, null, null, null, null); } sendAsyncMessage("Social:ErrorPageNotify", { - origin: origin, + origin, url: src }); }, diff --git a/browser/base/content/sync/aboutSyncTabs.js b/browser/base/content/sync/aboutSyncTabs.js index e49411c7434f..731a0edfee81 100644 --- a/browser/base/content/sync/aboutSyncTabs.js +++ b/browser/base/content/sync/aboutSyncTabs.js @@ -23,7 +23,7 @@ if (AppConstants.MOZ_SERVICES_CLOUDSYNC) { var RemoteTabViewer = { _tabsList: null, - init: function() { + init() { Services.obs.addObserver(this, "weave:service:login:finish", false); Services.obs.addObserver(this, "weave:engine:sync:finish", false); @@ -34,14 +34,14 @@ var RemoteTabViewer = { this.buildList(true); }, - uninit: function() { + uninit() { Services.obs.removeObserver(this, "weave:service:login:finish"); Services.obs.removeObserver(this, "weave:engine:sync:finish"); Services.obs.removeObserver(this, "cloudsync:tabs:update"); }, - createItem: function(attrs) { + createItem(attrs) { let item = document.createElement("richlistitem"); // Copy the attributes from the argument into the item. @@ -56,7 +56,7 @@ var RemoteTabViewer = { return item; }, - filterTabs: function(event) { + filterTabs(event) { let val = event.target.value.toLowerCase(); let numTabs = this._tabsList.getRowCount(); let clientTabs = 0; @@ -89,7 +89,7 @@ var RemoteTabViewer = { } }, - openSelected: function() { + openSelected() { let items = this._tabsList.selectedItems; let urls = []; for (let i = 0; i < items.length; i++) { @@ -105,14 +105,14 @@ var RemoteTabViewer = { } }, - bookmarkSingleTab: function() { + bookmarkSingleTab() { let item = this._tabsList.selectedItems[0]; let uri = Weave.Utils.makeURI(item.getAttribute("url")); let title = item.getAttribute("title"); PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" - , uri: uri - , title: title + , uri + , title , hiddenRows: [ "description" , "location" , "loadInSidebar" @@ -120,7 +120,7 @@ var RemoteTabViewer = { }, window.top); }, - bookmarkSelectedTabs: function() { + bookmarkSelectedTabs() { let items = this._tabsList.selectedItems; let URIs = []; for (let i = 0; i < items.length; i++) { @@ -142,7 +142,7 @@ var RemoteTabViewer = { } }, - getIcon: function(iconUri, defaultIcon) { + getIcon(iconUri, defaultIcon) { try { let iconURI = Weave.Utils.makeURI(iconUri); return PlacesUtils.favicons.getFaviconLinkForIcon(iconURI).spec; @@ -158,7 +158,7 @@ var RemoteTabViewer = { _buildListRequested: false, - buildList: function(forceSync) { + buildList(forceSync) { if (this._waitingForBuildList) { this._buildListRequested = true; return; @@ -192,7 +192,7 @@ var RemoteTabViewer = { } }, - _clearTabList: function() { + _clearTabList() { let list = this._tabsList; // Clear out existing richlistitems. @@ -204,7 +204,7 @@ var RemoteTabViewer = { } }, - _generateWeaveTabList: function() { + _generateWeaveTabList() { let engine = Weave.Service.engineManager.get("tabs"); let list = this._tabsList; @@ -236,7 +236,7 @@ var RemoteTabViewer = { let attrs = { type: "tab", title: title || url, - url: url, + url, icon: this.getIcon(icon), } let tab = this.createItem(attrs); @@ -245,7 +245,7 @@ var RemoteTabViewer = { } }, - _generateCloudSyncTabList: function() { + _generateCloudSyncTabList() { let updateTabList = function(remoteTabs) { let list = this._tabsList; @@ -275,7 +275,7 @@ var RemoteTabViewer = { .then(updateTabList, Promise.reject.bind(Promise)); }, - adjustContextMenu: function(event) { + adjustContextMenu(event) { let mode = "all"; switch (this._tabsList.selectedItems.length) { case 0: @@ -300,7 +300,7 @@ var RemoteTabViewer = { } }, - _refetchTabs: function(force) { + _refetchTabs(force) { if (!force) { // Don't bother refetching tabs if we already did so recently let lastFetch = 0; @@ -325,7 +325,7 @@ var RemoteTabViewer = { return true; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "weave:service:login:finish": // A login has finished, which means that a Sync is about to start and @@ -346,7 +346,7 @@ var RemoteTabViewer = { } }, - handleClick: function(event) { + handleClick(event) { if (event.target.getAttribute("type") != "tab") { return; } diff --git a/browser/base/content/sync/genericChange.js b/browser/base/content/sync/genericChange.js index a9571b662f6d..5828e5dbb900 100644 --- a/browser/base/content/sync/genericChange.js +++ b/browser/base/content/sync/genericChange.js @@ -136,7 +136,7 @@ var Change = { window.setTimeout(window.close, 1500); }, - onDialogAccept: function() { + onDialogAccept() { switch (this._dialogType) { case "UpdatePassphrase": case "ResetPassphrase": @@ -147,7 +147,7 @@ var Change = { return undefined; }, - doGeneratePassphrase: function() { + doGeneratePassphrase() { let passphrase = Weave.Utils.generatePassphrase(); this._passphraseBox.value = Weave.Utils.hyphenatePassphrase(passphrase); this._dialog.getButton("finish").disabled = false; @@ -201,7 +201,7 @@ var Change = { return false; }, - validate: function(event) { + validate(event) { let valid = false; let errorString = ""; diff --git a/browser/base/content/sync/setup.js b/browser/base/content/sync/setup.js index ab7f61001565..9190263283a9 100644 --- a/browser/base/content/sync/setup.js +++ b/browser/base/content/sync/setup.js @@ -61,7 +61,7 @@ var gSyncSetup = { return document.getElementById("existingServer").selectedIndex == 0; }, - init: function() { + init() { let obs = [ ["weave:service:change-passphrase", "onResetPassphrase"], ["weave:service:login:start", "onLoginStart"], @@ -121,14 +121,14 @@ var gSyncSetup = { .getAttribute("accesskey"); }, - startNewAccountSetup: function() { + startNewAccountSetup() { if (!Weave.Utils.ensureMPUnlocked()) return; this._settingUpNew = true; this.wizard.pageIndex = NEW_ACCOUNT_START_PAGE; }, - useExistingAccount: function() { + useExistingAccount() { if (!Weave.Utils.ensureMPUnlocked()) return; this._settingUpNew = false; @@ -173,22 +173,22 @@ var gSyncSetup = { gSyncUtils.resetPassphrase(true); }, - onResetPassphrase: function() { + onResetPassphrase() { document.getElementById("existingPassphrase").value = Weave.Utils.hyphenatePassphrase(Weave.Service.identity.syncKey); this.checkFields(); this.wizard.advance(); }, - onLoginStart: function() { + onLoginStart() { this.toggleLoginFeedback(false); }, - onLoginEnd: function() { + onLoginEnd() { this.toggleLoginFeedback(true); }, - sendCredentialsAfterSync: function() { + sendCredentialsAfterSync() { let send = function() { Services.obs.removeObserver("weave:service:sync:finish", send); Services.obs.removeObserver("weave:service:sync:error", send); @@ -202,7 +202,7 @@ var gSyncSetup = { Services.obs.addObserver("weave:service:sync:error", send, false); }, - toggleLoginFeedback: function(stop) { + toggleLoginFeedback(stop) { document.getElementById("login-throbber").hidden = stop; let password = document.getElementById("existingPasswordFeedbackRow"); let server = document.getElementById("existingServerFeedbackRow"); @@ -231,7 +231,7 @@ var gSyncSetup = { this._setFeedbackMessage(feedback, false, Weave.Status.login); }, - setupInitialSync: function() { + setupInitialSync() { let action = document.getElementById("mergeChoiceRadio").selectedItem.id; switch (action) { case "resetClient": @@ -248,11 +248,11 @@ var gSyncSetup = { }, // fun with validation! - checkFields: function() { + checkFields() { this.wizard.canAdvance = this.readyToAdvance(); }, - readyToAdvance: function() { + readyToAdvance() { switch (this.wizard.pageIndex) { case INTRO_PAGE: return false; @@ -293,7 +293,7 @@ var gSyncSetup = { this.pin3.value.length == PIN_PART_LENGTH); }, - onEmailInput: function() { + onEmailInput() { // Check account validity when the user stops typing for 1 second. if (this._checkAccountTimer) window.clearTimeout(this._checkAccountTimer); @@ -302,7 +302,7 @@ var gSyncSetup = { }, 1000); }, - checkAccount: function() { + checkAccount() { delete this._checkAccountTimer; let value = Weave.Utils.normalizeAccount( document.getElementById("weaveEmail").value); @@ -337,7 +337,7 @@ var gSyncSetup = { this.checkFields(); }, - onPasswordChange: function() { + onPasswordChange() { let password = document.getElementById("weavePassword"); let pwconfirm = document.getElementById("weavePasswordConfirm"); let [valid, errorString] = gSyncUtils.validatePassword(password, pwconfirm); @@ -349,7 +349,7 @@ var gSyncSetup = { this.checkFields(); }, - onPageShow: function() { + onPageShow() { switch (this.wizard.pageIndex) { case PAIR_PAGE: this.wizard.getButton("back").hidden = true; @@ -420,7 +420,7 @@ var gSyncSetup = { } }, - onWizardAdvance: function() { + onWizardAdvance() { // Check pageIndex so we don't prompt before the Sync setup wizard appears. // This is a fallback in case the Master Password gets locked mid-wizard. if ((this.wizard.pageIndex >= 0) && @@ -509,7 +509,7 @@ var gSyncSetup = { return true; }, - onWizardBack: function() { + onWizardBack() { switch (this.wizard.pageIndex) { case NEW_ACCOUNT_START_PAGE: this.wizard.pageIndex = INTRO_PAGE; @@ -535,7 +535,7 @@ var gSyncSetup = { return true; }, - wizardFinish: function() { + wizardFinish() { this.setupInitialSync(); if (this.wizardType == "pair") { @@ -563,7 +563,7 @@ var gSyncSetup = { window.close(); }, - onWizardCancel: function() { + onWizardCancel() { if (this._resettingSync) return; @@ -572,12 +572,12 @@ var gSyncSetup = { Weave.Service.startOver(); }, - onSyncOptions: function() { + onSyncOptions() { this._beforeOptionsPage = this.wizard.pageIndex; this.wizard.pageIndex = OPTIONS_PAGE; }, - returnFromOptions: function() { + returnFromOptions() { this.wizard.getButton("next").label = this._nextButtonLabel; this.wizard.getButton("next").setAttribute("accesskey", this._nextButtonAccesskey); @@ -644,7 +644,7 @@ var gSyncSetup = { this._jpakeclient.controller = controller; }, - startEasySetup: function() { + startEasySetup() { // Don't do anything if we have a client already (e.g. we went to // Sync Options and just came back). if (this._jpakeclient) @@ -691,7 +691,7 @@ var gSyncSetup = { this._jpakeclient.receiveNoPIN(); }, - abortEasySetup: function() { + abortEasySetup() { document.getElementById("easySetupPIN1").value = ""; document.getElementById("easySetupPIN2").value = ""; document.getElementById("easySetupPIN3").value = ""; @@ -702,7 +702,7 @@ var gSyncSetup = { delete this._jpakeclient; }, - manualSetup: function() { + manualSetup() { this.abortEasySetup(); this.wizard.pageIndex = EXISTING_ACCOUNT_LOGIN_PAGE; }, @@ -710,7 +710,7 @@ var gSyncSetup = { // _handleNoScript is needed because it blocks the captcha. So we temporarily // allow the necessary sites so that we can verify the user is in fact a human. // This was done with the help of Giorgio (NoScript author). See bug 508112. - _handleNoScript: function(addExceptions) { + _handleNoScript(addExceptions) { // if NoScript isn't installed, or is disabled, bail out. let ns = Cc["@maone.net/noscript-service;1"]; if (ns == null) @@ -734,7 +734,7 @@ var gSyncSetup = { } }, - onExistingServerCommand: function() { + onExistingServerCommand() { let control = document.getElementById("existingServer"); if (control.selectedIndex == 0) { control.removeAttribute("editable"); @@ -750,7 +750,7 @@ var gSyncSetup = { this.checkFields(); }, - onExistingServerInput: function() { + onExistingServerInput() { // Check custom server validity when the user stops typing for 1 second. if (this._existingServerTimer) window.clearTimeout(this._existingServerTimer); @@ -759,7 +759,7 @@ var gSyncSetup = { }, 1000); }, - onServerCommand: function() { + onServerCommand() { setVisibility(document.getElementById("TOSRow"), this._usingMainServers); let control = document.getElementById("server"); if (!this._usingMainServers) { @@ -783,7 +783,7 @@ var gSyncSetup = { this.checkFields(); }, - onServerInput: function() { + onServerInput() { // Check custom server validity when the user stops typing for 1 second. if (this._checkServerTimer) window.clearTimeout(this._checkServerTimer); @@ -792,7 +792,7 @@ var gSyncSetup = { }, 1000); }, - checkServer: function() { + checkServer() { delete this._checkServerTimer; let el = document.getElementById("server"); let valid = false; @@ -813,7 +813,7 @@ var gSyncSetup = { this.checkFields(); }, - _validateServer: function(element) { + _validateServer(element) { let valid = false; let val = element.value; if (!val) @@ -859,7 +859,7 @@ var gSyncSetup = { return valid; }, - _handleChoice: function() { + _handleChoice() { let desc = document.getElementById("mergeChoiceRadio").selectedIndex; document.getElementById("chosenActionDeck").selectedIndex = desc; switch (desc) { @@ -983,7 +983,7 @@ var gSyncSetup = { // sets class and string on a feedback element // if no property string is passed in, we clear label/style - _setFeedback: function(element, success, string) { + _setFeedback(element, success, string) { element.hidden = success || !string; let classname = success ? "success" : "error"; let image = element.getElementsByAttribute("class", "statusIcon")[0]; @@ -993,7 +993,7 @@ var gSyncSetup = { }, // shim - _setFeedbackMessage: function(element, success, string) { + _setFeedbackMessage(element, success, string) { let str = ""; if (string) { try { @@ -1015,7 +1015,7 @@ var gSyncSetup = { } }, - onStateChange: function(webProgress, request, stateFlags, status) { + onStateChange(webProgress, request, stateFlags, status) { // We're only looking for the end of the frame load if ((stateFlags & Ci.nsIWebProgressListener.STATE_STOP) == 0) return; @@ -1029,10 +1029,10 @@ var gSyncSetup = { setVisibility(this.captchaBrowser, responseStatus != 404); // XXX TODO we should really log any responseStatus other than 200 }, - onProgressChange: function() {}, - onStatusChange: function() {}, - onSecurityChange: function() {}, - onLocationChange: function() {} + onProgressChange() {}, + onStatusChange() {}, + onSecurityChange() {}, + onLocationChange() {} }; // Define lazy getters for various XUL elements. diff --git a/browser/base/content/sync/utils.js b/browser/base/content/sync/utils.js index c49d4b3b71fb..ea60ba1a0541 100644 --- a/browser/base/content/sync/utils.js +++ b/browser/base/content/sync/utils.js @@ -22,7 +22,7 @@ var gSyncUtils = { }, // opens in a new window if we're in a modal prefwindow world, in a new tab otherwise - _openLink: function(url) { + _openLink(url) { let thisDocEl = document.documentElement, openerDocEl = window.opener && window.opener.document.documentElement; if (thisDocEl.id == "accountSetup" && window.opener && @@ -58,22 +58,22 @@ var gSyncUtils = { type, duringSetup); }, - changePassword: function() { + changePassword() { if (Weave.Utils.ensureMPUnlocked()) this.openChange("ChangePassword"); }, - resetPassphrase: function(duringSetup) { + resetPassphrase(duringSetup) { if (Weave.Utils.ensureMPUnlocked()) this.openChange("ResetPassphrase", duringSetup); }, - updatePassphrase: function() { + updatePassphrase() { if (Weave.Utils.ensureMPUnlocked()) this.openChange("UpdatePassphrase"); }, - resetPassword: function() { + resetPassword() { this._openLink(Weave.Service.pwResetURL); }, @@ -82,7 +82,7 @@ var gSyncUtils = { return Weave.Svc.Prefs.get(root + "termsURL"); }, - openToS: function() { + openToS() { this._openLink(this.tosURL); }, @@ -91,7 +91,7 @@ var gSyncUtils = { return Weave.Svc.Prefs.get(root + "privacyURL"); }, - openPrivacyPolicy: function() { + openPrivacyPolicy() { this._openLink(this.privacyPolicyURL); }, @@ -102,7 +102,7 @@ var gSyncUtils = { * @param elid : ID of the form element containing the passphrase. * @param callback : Function called once the iframe has loaded. */ - _preparePPiframe: function(elid, callback) { + _preparePPiframe(elid, callback) { let pp = document.getElementById(elid).value; // Create an invisible iframe whose contents we can print. @@ -137,7 +137,7 @@ var gSyncUtils = { * * @param elid : ID of the form element containing the passphrase. */ - passphrasePrint: function(elid) { + passphrasePrint(elid) { this._preparePPiframe(elid, function(iframe) { let webBrowserPrint = iframe.contentWindow .QueryInterface(Ci.nsIInterfaceRequestor) @@ -165,7 +165,7 @@ var gSyncUtils = { * * @param elid : ID of the form element containing the passphrase. */ - passphraseSave: function(elid) { + passphraseSave(elid) { let dialogTitle = this.bundle.GetStringFromName("save.recoverykey.title"); let defaultSaveName = this.bundle.GetStringFromName("save.recoverykey.defaultfilename"); this._preparePPiframe(elid, function(iframe) { @@ -203,7 +203,7 @@ var gSyncUtils = { * * returns [valid, errorString] */ - validatePassword: function(el1, el2) { + validatePassword(el1, el2) { let valid = false; let val1 = el1.value; let val2 = el2 ? el2.value : ""; diff --git a/browser/base/content/tab-content.js b/browser/base/content/tab-content.js index 34eb58627207..67db5b5fc183 100644 --- a/browser/base/content/tab-content.js +++ b/browser/base/content/tab-content.js @@ -27,7 +27,7 @@ XPCOMUtils.defineLazyGetter(this, "SimpleServiceDiscovery", function() { ssdp.registerDevice({ id: "roku:ecp", target: "roku:ecp", - factory: function(aService) { + factory(aService) { Cu.import("resource://gre/modules/RokuApp.jsm"); return new RokuApp(aService); }, @@ -98,13 +98,13 @@ addMessageListener("SecondScreen:tab-mirror", function(message) { if (app) { let width = content.innerWidth; let height = content.innerHeight; - let viewport = {cssWidth: width, cssHeight: height, width: width, height: height}; + let viewport = {cssWidth: width, cssHeight: height, width, height}; app.mirror(function() {}, content, viewport, function() {}, content); } }); var AboutHomeListener = { - init: function(chromeGlobal) { + init(chromeGlobal) { chromeGlobal.addEventListener('AboutHomeLoad', this, false, true); }, @@ -112,7 +112,7 @@ var AboutHomeListener = { return content.document.documentURI.toLowerCase() == "about:home"; }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (!this.isAboutHome) { return; } @@ -129,7 +129,7 @@ var AboutHomeListener = { } }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { if (!this.isAboutHome) { return; } @@ -140,7 +140,7 @@ var AboutHomeListener = { } }, - onUpdate: function(aData) { + onUpdate(aData) { let doc = content.document; if (aData.showRestoreLastSession && !PrivateBrowsingUtils.isContentWindowPrivate(content)) doc.getElementById("launcher").setAttribute("session", "true"); @@ -154,7 +154,7 @@ var AboutHomeListener = { docElt.setAttribute("snippetsVersion", aData.snippetsVersion); }, - onPageLoad: function() { + onPageLoad() { addMessageListener("AboutHome:Update", this); addEventListener("click", this, true); addEventListener("pagehide", this, true); @@ -163,7 +163,7 @@ var AboutHomeListener = { sendAsyncMessage("AboutHome:RequestUpdate"); }, - onClick: function(aEvent) { + onClick(aEvent) { if (!aEvent.isTrusted || // Don't trust synthetic events aEvent.button == 2 || aEvent.target.localName != "button") { return; @@ -210,7 +210,7 @@ var AboutHomeListener = { } }, - onPageHide: function(aEvent) { + onPageHide(aEvent) { if (aEvent.target.defaultView.frameElement) { return; } @@ -260,7 +260,7 @@ var AboutReaderListener = { _isLeavingReaderMode: false, - init: function() { + init() { addEventListener("AboutReaderContentLoaded", this, false, true); addEventListener("DOMContentLoaded", this, false); addEventListener("pageshow", this, false); @@ -269,7 +269,7 @@ var AboutReaderListener = { addMessageListener("Reader:PushState", this); }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Reader:ToggleReaderMode": if (!this.isAboutReader) { @@ -294,7 +294,7 @@ var AboutReaderListener = { return content.document.documentURI.startsWith("about:reader"); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (aEvent.originalTarget.defaultView != content) { return; } @@ -344,7 +344,7 @@ var AboutReaderListener = { * this is a suitable document). Calling it on things which won't be * painted is not going to work. */ - updateReaderButton: function(forceNonArticle) { + updateReaderButton(forceNonArticle) { if (!ReaderMode.isEnabledForParseOnLoad || this.isAboutReader || !content || !(content.document instanceof content.HTMLDocument) || content.document.mozSyntheticDocument) { @@ -354,14 +354,14 @@ var AboutReaderListener = { this.scheduleReadabilityCheckPostPaint(forceNonArticle); }, - cancelPotentialPendingReadabilityCheck: function() { + cancelPotentialPendingReadabilityCheck() { if (this._pendingReadabilityCheck) { removeEventListener("MozAfterPaint", this._pendingReadabilityCheck); delete this._pendingReadabilityCheck; } }, - scheduleReadabilityCheckPostPaint: function(forceNonArticle) { + scheduleReadabilityCheckPostPaint(forceNonArticle) { if (this._pendingReadabilityCheck) { // We need to stop this check before we re-add one because we don't know // if forceNonArticle was true or false last time. @@ -371,7 +371,7 @@ var AboutReaderListener = { addEventListener("MozAfterPaint", this._pendingReadabilityCheck); }, - onPaintWhenWaitedFor: function(forceNonArticle, event) { + onPaintWhenWaitedFor(forceNonArticle, event) { // In non-e10s, we'll get called for paints other than ours, and so it's // possible that this page hasn't been laid out yet, in which case we // should wait until we get an event that does relate to our layout. We @@ -401,18 +401,18 @@ var ContentSearchMediator = { "about:newtab", ]), - init: function(chromeGlobal) { + init(chromeGlobal) { chromeGlobal.addEventListener("ContentSearchClient", this, true, true); addMessageListener("ContentSearch", this); }, - handleEvent: function(event) { + handleEvent(event) { if (this._contentWhitelisted) { this._sendMsg(event.detail.type, event.detail.data); } }, - receiveMessage: function(msg) { + receiveMessage(msg) { if (msg.data.type == "AddToWhitelist") { for (let uri of msg.data.data) { this.whitelist.add(uri); @@ -429,18 +429,18 @@ var ContentSearchMediator = { return this.whitelist.has(content.document.documentURI); }, - _sendMsg: function(type, data = null) { + _sendMsg(type, data = null) { sendAsyncMessage("ContentSearch", { - type: type, - data: data, + type, + data, }); }, - _fireEvent: function(type, data = null) { + _fireEvent(type, data = null) { let event = Cu.cloneInto({ detail: { - type: type, - data: data, + type, + data, }, }, content); content.dispatchEvent(new content.CustomEvent("ContentSearchService", @@ -450,7 +450,7 @@ var ContentSearchMediator = { ContentSearchMediator.init(this); var PageStyleHandler = { - init: function() { + init() { addMessageListener("PageStyle:Switch", this); addMessageListener("PageStyle:Disable", this); addEventListener("pageshow", () => this.sendStyleSheetInfo()); @@ -460,23 +460,23 @@ var PageStyleHandler = { return docShell.contentViewer; }, - sendStyleSheetInfo: function() { + sendStyleSheetInfo() { let filteredStyleSheets = this._filterStyleSheets(this.getAllStyleSheets()); sendAsyncMessage("PageStyle:StyleSheets", { - filteredStyleSheets: filteredStyleSheets, + filteredStyleSheets, authorStyleDisabled: this.markupDocumentViewer.authorStyleDisabled, preferredStyleSheetSet: content.document.preferredStyleSheetSet }); }, - getAllStyleSheets: function(frameset = content) { + getAllStyleSheets(frameset = content) { let selfSheets = Array.slice(frameset.document.styleSheets); let subSheets = Array.map(frameset.frames, frame => this.getAllStyleSheets(frame)); return selfSheets.concat(...subSheets); }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "PageStyle:Switch": this.markupDocumentViewer.authorStyleDisabled = false; @@ -491,7 +491,7 @@ var PageStyleHandler = { this.sendStyleSheetInfo(); }, - _stylesheetSwitchAll: function(frameset, title) { + _stylesheetSwitchAll(frameset, title) { if (!title || this._stylesheetInFrame(frameset, title)) { this._stylesheetSwitchFrame(frameset, title); } @@ -502,7 +502,7 @@ var PageStyleHandler = { } }, - _stylesheetSwitchFrame: function(frame, title) { + _stylesheetSwitchFrame(frame, title) { var docStyleSheets = frame.document.styleSheets; for (let i = 0; i < docStyleSheets.length; ++i) { @@ -515,11 +515,11 @@ var PageStyleHandler = { } }, - _stylesheetInFrame: function(frame, title) { + _stylesheetInFrame(frame, title) { return Array.some(frame.document.styleSheets, (styleSheet) => styleSheet.title == title); }, - _filterStyleSheets: function(styleSheets) { + _filterStyleSheets(styleSheets) { let result = []; for (let currentStyleSheet of styleSheets) { @@ -661,13 +661,13 @@ let PrerenderContentHandler = { sendAsyncMessage("Prerender:Request", { href: aHref.spec, referrer: aReferrer ? aReferrer.spec : null, - id: id, + id, }); this._pending.push({ href: aHref, referrer: aReferrer, - id: id, + id, success: null, failure: null, }); @@ -699,12 +699,12 @@ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { } var WebBrowserChrome = { - onBeforeLinkTraversal: function(originalTarget, linkURI, linkNode, isAppTab) { + onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) { return BrowserUtils.onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab); }, // Check whether this URI should load in the current process - shouldLoadURI: function(aDocShell, aURI, aReferrer) { + shouldLoadURI(aDocShell, aURI, aReferrer) { if (!E10SUtils.shouldLoadURI(aDocShell, aURI, aReferrer)) { E10SUtils.redirectLoad(aDocShell, aURI, aReferrer); return false; @@ -713,23 +713,23 @@ var WebBrowserChrome = { return true; }, - shouldLoadURIInThisProcess: function(aURI) { + shouldLoadURIInThisProcess(aURI) { return E10SUtils.shouldLoadURIInThisProcess(aURI); }, // Try to reload the currently active or currently loading page in a new process. - reloadInFreshProcess: function(aDocShell, aURI, aReferrer) { + reloadInFreshProcess(aDocShell, aURI, aReferrer) { E10SUtils.redirectLoad(aDocShell, aURI, aReferrer, true); return true; }, - startPrerenderingDocument: function(aHref, aReferrer) { + startPrerenderingDocument(aHref, aReferrer) { if (PrerenderContentHandler.initialized) { PrerenderContentHandler.startPrerenderingDocument(aHref, aReferrer); } }, - shouldSwitchToPrerenderedDocument: function(aHref, aReferrer, aSuccess, aFailure) { + shouldSwitchToPrerenderedDocument(aHref, aReferrer, aSuccess, aFailure) { if (PrerenderContentHandler.initialized) { return PrerenderContentHandler.shouldSwitchToPrerenderedDocument( aHref, aReferrer, aSuccess, aFailure); @@ -747,7 +747,7 @@ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { var DOMFullscreenHandler = { - init: function() { + init() { addMessageListener("DOMFullscreen:Entered", this); addMessageListener("DOMFullscreen:CleanUp", this); addEventListener("MozDOMFullscreen:Request", this); @@ -765,7 +765,7 @@ var DOMFullscreenHandler = { .getInterface(Ci.nsIDOMWindowUtils); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { let windowUtils = this._windowUtils; switch (aMessage.name) { case "DOMFullscreen:Entered": { @@ -793,7 +793,7 @@ var DOMFullscreenHandler = { } }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "MozDOMFullscreen:Request": { sendAsyncMessage("DOMFullscreen:Request"); diff --git a/browser/base/content/test/general/browser_aboutAccounts.js b/browser/base/content/test/general/browser_aboutAccounts.js index c825c91cd02d..173ac8c52fde 100644 --- a/browser/base/content/test/general/browser_aboutAccounts.js +++ b/browser/base/content/test/general/browser_aboutAccounts.js @@ -36,11 +36,11 @@ registerCleanupFunction(function() { var gTests = [ { desc: "Test the remote commands", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/browser/browser/base/content/test/general/accounts_testRemoteCommands.html"); @@ -76,7 +76,7 @@ var gTests = [ { desc: "Test action=signin - no user logged in", teardown: () => gBrowser.removeCurrentTab(), - run: function* () + *run() { // When this loads with no user logged-in, we expect the "normal" URL const expected_url = "https://example.com/?is_sign_in"; @@ -95,11 +95,11 @@ var gTests = [ }, { desc: "Test action=signin - user logged in", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { // When this loads with a user logged-in, we expect the normal URL to // have been ignored and the "manage" page to be shown. @@ -124,7 +124,7 @@ var gTests = [ { desc: "Test action=signin - captive portal", teardown: () => gBrowser.removeCurrentTab(), - run: function* () + *run() { const signinUrl = "https://redirproxy.example.com/test"; setPref("identity.fxaccounts.remote.signin.uri", signinUrl); @@ -144,7 +144,7 @@ var gTests = [ gBrowser.removeCurrentTab(); BrowserOffline.toggleOfflineStatus(); }, - run: function* () + *run() { BrowserOffline.toggleOfflineStatus(); Services.cache2.clear(); @@ -164,7 +164,7 @@ var gTests = [ { desc: "Test action=signup - no user logged in", teardown: () => gBrowser.removeCurrentTab(), - run: function* () + *run() { const expected_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", expected_url); @@ -183,7 +183,7 @@ var gTests = [ { desc: "Test action=signup - user logged in", teardown: () => gBrowser.removeCurrentTab(), - run: function* () + *run() { const expected_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", expected_url); @@ -202,11 +202,11 @@ var gTests = [ }, { desc: "Test action=reauth", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { const expected_url = "https://example.com/?is_force_auth"; setPref("identity.fxaccounts.remote.force_auth.uri", expected_url); @@ -220,11 +220,11 @@ var gTests = [ }, { desc: "Test with migrateToDevEdition enabled (success)", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { let fxAccountsCommon = {}; Cu.import("resource://gre/modules/FxAccountsCommon.js", fxAccountsCommon); @@ -281,11 +281,11 @@ var gTests = [ }, { desc: "Test with migrateToDevEdition enabled (no user to migrate)", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { const pref = "identity.fxaccounts.migrateToDevEdition"; changedPrefs.add(pref); @@ -321,10 +321,10 @@ var gTests = [ }, { desc: "Test observers about:accounts", - teardown: function() { + teardown() { gBrowser.removeCurrentTab(); }, - run: function* () { + *run() { setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/"); yield setSignedInUser(); let tab = yield promiseNewTabLoadEvent("about:accounts"); @@ -339,7 +339,7 @@ var gTests = [ { desc: "Test entrypoint query string, no action, no user logged in", teardown: () => gBrowser.removeCurrentTab(), - run: function* () { + *run() { // When this loads with no user logged-in, we expect the "normal" URL setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/"); let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?entrypoint=abouthome"); @@ -349,7 +349,7 @@ var gTests = [ { desc: "Test entrypoint query string for signin", teardown: () => gBrowser.removeCurrentTab(), - run: function* () { + *run() { // When this loads with no user logged-in, we expect the "normal" URL const expected_url = "https://example.com/?is_sign_in"; setPref("identity.fxaccounts.remote.signin.uri", expected_url); @@ -360,7 +360,7 @@ var gTests = [ { desc: "Test entrypoint query string for signup", teardown: () => gBrowser.removeCurrentTab(), - run: function* () { + *run() { // When this loads with no user logged-in, we expect the "normal" URL const sign_up_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", sign_up_url); @@ -374,7 +374,7 @@ var gTests = [ teardown() { gBrowser.removeCurrentTab(); }, - run: function* () { + *run() { let signupURL = "https://example.com/"; setPref("identity.fxaccounts.remote.signup.uri", signupURL); let queryStr = "email=foo%40example.com&foo=bar&baz=quux"; @@ -390,7 +390,7 @@ var gTests = [ teardown() { gBrowser.removeCurrentTab(); }, - run: function* () { + *run() { let signupURL = "https://example.com/?param"; setPref("identity.fxaccounts.remote.signup.uri", signupURL); let queryStr = "email=foo%40example.com&foo=bar&baz=quux"; @@ -472,7 +472,7 @@ function checkVisibilities(tab, data) { } deferred.resolve(); }); - mm.sendAsyncMessage("test:check-visibilities", {ids: ids}); + mm.sendAsyncMessage("test:check-visibilities", {ids}); return deferred.promise; } diff --git a/browser/base/content/test/general/browser_aboutHealthReport.js b/browser/base/content/test/general/browser_aboutHealthReport.js index 4027db223feb..2b7eb1b08741 100644 --- a/browser/base/content/test/general/browser_aboutHealthReport.js +++ b/browser/base/content/test/general/browser_aboutHealthReport.js @@ -68,7 +68,7 @@ var gTests = [ Preferences.set("datareporting.healthreport.about.reportUrl", HTTPS_BASE + "healthreport_testRemoteCommands.html"); }), - run: function(iframe) + run(iframe) { let deferred = Promise.defer(); let results = 0; diff --git a/browser/base/content/test/general/browser_aboutHome.js b/browser/base/content/test/general/browser_aboutHome.js index ba5abf34732c..cf9ed841e481 100644 --- a/browser/base/content/test/general/browser_aboutHome.js +++ b/browser/base/content/test/general/browser_aboutHome.js @@ -495,7 +495,7 @@ add_task(function* () { let oldOpenPrefs = window.openPreferences; let openPrefsPromise = new Promise(resolve => { window.openPreferences = function(pane, params) { - resolve({ pane: pane, params: params }); + resolve({ pane, params }); }; }); @@ -647,7 +647,7 @@ function promiseNewEngine(basename) { return new Promise((resolve, reject) => { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => { try { @@ -656,7 +656,7 @@ function promiseNewEngine(basename) { }); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/general/browser_alltabslistener.js b/browser/base/content/test/general/browser_alltabslistener.js index da5e8ddd1933..622be9cd2eab 100644 --- a/browser/base/content/test/general/browser_alltabslistener.js +++ b/browser/base/content/test/general/browser_alltabslistener.js @@ -4,12 +4,12 @@ const gCompleteState = Ci.nsIWebProgressListener.STATE_STOP + Ci.nsIWebProgressListener.STATE_IS_NETWORK; var gFrontProgressListener = { - onProgressChange: function(aWebProgress, aRequest, + onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { }, - onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { var state = "onStateChange"; info("FrontProgress: " + state + " 0x" + aStateFlags.toString(16)); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -17,7 +17,7 @@ var gFrontProgressListener = { gFrontNotificationsPos++; }, - onLocationChange: function(aWebProgress, aRequest, aLocationURI, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocationURI, aFlags) { var state = "onLocationChange"; info("FrontProgress: " + state + " " + aLocationURI.spec); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -25,10 +25,10 @@ var gFrontProgressListener = { gFrontNotificationsPos++; }, - onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { }, - onSecurityChange: function(aWebProgress, aRequest, aState) { + onSecurityChange(aWebProgress, aRequest, aState) { var state = "onSecurityChange"; info("FrontProgress: " + state + " 0x" + aState.toString(16)); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -38,7 +38,7 @@ var gFrontProgressListener = { } var gAllProgressListener = { - onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { var state = "onStateChange"; info("AllProgress: " + state + " 0x" + aStateFlags.toString(16)); ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); @@ -53,7 +53,7 @@ var gAllProgressListener = { } }, - onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, + onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) { var state = "onLocationChange"; info("AllProgress: " + state + " " + aLocationURI.spec); @@ -63,12 +63,12 @@ var gAllProgressListener = { gAllNotificationsPos++; }, - onStatusChange: function(aBrowser, aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange(aBrowser, aWebProgress, aRequest, aStatus, aMessage) { var state = "onStatusChange"; ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); }, - onSecurityChange: function(aBrowser, aWebProgress, aRequest, aState) { + onSecurityChange(aBrowser, aWebProgress, aRequest, aState) { var state = "onSecurityChange"; info("AllProgress: " + state + " 0x" + aState.toString(16)); ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); diff --git a/browser/base/content/test/general/browser_blockHPKP.js b/browser/base/content/test/general/browser_blockHPKP.js index 47106cbb4623..d470a219f58d 100644 --- a/browser/base/content/test/general/browser_blockHPKP.js +++ b/browser/base/content/test/general/browser_blockHPKP.js @@ -60,7 +60,7 @@ function loadPinningPage() { // After the site is pinned try to load with a subdomain site that should // fail to validate var successfulPinningPageListener = { - handleEvent: function() { + handleEvent() { gBrowser.selectedBrowser.removeEventListener("load", this, true); BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kBadPinningDomain).then(function() { return promiseErrorPageLoaded(gBrowser.selectedBrowser); diff --git a/browser/base/content/test/general/browser_bug321000.js b/browser/base/content/test/general/browser_bug321000.js index b30b7101d568..a65b2703ee91 100644 --- a/browser/base/content/test/general/browser_bug321000.js +++ b/browser/base/content/test/general/browser_bug321000.js @@ -49,7 +49,7 @@ function test_paste(aCurrentTest) { // Register input listener. var inputListener = { test: aCurrentTest, - handleEvent: function(event) { + handleEvent(event) { element.removeEventListener(event.type, this, false); is(element.value, this.test.expected, this.test.desc); diff --git a/browser/base/content/test/general/browser_bug356571.js b/browser/base/content/test/general/browser_bug356571.js index 1bfa73ea1587..8af6b4a79003 100644 --- a/browser/base/content/test/general/browser_bug356571.js +++ b/browser/base/content/test/general/browser_bug356571.js @@ -15,7 +15,7 @@ const kPromptServiceFactory = Cm.getClassObject(Cc[kPromptServiceContractID], Ci.nsIFactory); var fakePromptServiceFactory = { - createInstance: function(aOuter, aIid) { + createInstance(aOuter, aIid) { if (aOuter != null) throw Cr.NS_ERROR_NO_AGGREGATION; return promptService.QueryInterface(aIid); @@ -24,7 +24,7 @@ var fakePromptServiceFactory = { var promptService = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]), - alert: function() { + alert() { didFail = true; } }; @@ -47,7 +47,7 @@ const kURIs = [ var gProgressListener = { _runCount: 0, - onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { if ((aStateFlags & kCompleteState) == kCompleteState) { if (++this._runCount != kURIs.length) return; diff --git a/browser/base/content/test/general/browser_bug424101.js b/browser/base/content/test/general/browser_bug424101.js index 8000d2ae9d5e..501448b8d399 100644 --- a/browser/base/content/test/general/browser_bug424101.js +++ b/browser/base/content/test/general/browser_bug424101.js @@ -24,7 +24,7 @@ add_task(function *() { let test = tests[index]; yield ContentTask.spawn(gBrowser.selectedBrowser, - { element: test.element, type: test.type, index: index }, + { element: test.element, type: test.type, index }, function* (arg) { let element = content.document.createElement(arg.element); element.id = "element" + arg.index; diff --git a/browser/base/content/test/general/browser_bug553455.js b/browser/base/content/test/general/browser_bug553455.js index b6004e0d3e5d..e3bfc7854492 100644 --- a/browser/base/content/test/general/browser_bug553455.js +++ b/browser/base/content/test/general/browser_bug553455.js @@ -152,13 +152,13 @@ function waitForInstallDialog() { let window = yield new Promise(resolve => { Services.wm.addListener({ - onOpenWindow: function(aXULWindow) { + onOpenWindow(aXULWindow) { Services.wm.removeListener(this); resolve(aXULWindow); }, - onCloseWindow: function(aXULWindow) { + onCloseWindow(aXULWindow) { }, - onWindowTitleChange: function(aXULWindow, aNewTitle) { + onWindowTitleChange(aXULWindow, aNewTitle) { } }); }); @@ -1055,7 +1055,7 @@ function test_cancel() { let install = notification.notification.options.installs[0]; let cancelledPromise = new Promise(resolve => { install.addListener({ - onDownloadCancelled: function() { + onDownloadCancelled() { install.removeListener(this); resolve(); } @@ -1124,7 +1124,7 @@ function test_failedSecurity() { var gTestStart = null; var XPInstallObserver = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo); info("Observed " + aTopic + " for " + installInfo.installs.length + " installs"); installInfo.installs.forEach(function(aInstall) { diff --git a/browser/base/content/test/general/browser_bug561636.js b/browser/base/content/test/general/browser_bug561636.js index 19e816716faf..585800b9e4c7 100644 --- a/browser/base/content/test/general/browser_bug561636.js +++ b/browser/base/content/test/general/browser_bug561636.js @@ -17,7 +17,7 @@ function checkPopupHide() var gObserver = { QueryInterface : XPCOMUtils.generateQI([Ci.nsIFormSubmitObserver]), - notifyInvalidSubmit : function(aFormElement, aInvalidElements) + notifyInvalidSubmit(aFormElement, aInvalidElements) { } }; diff --git a/browser/base/content/test/general/browser_bug592338.js b/browser/base/content/test/general/browser_bug592338.js index ca9cc361a84e..3744f26e4814 100644 --- a/browser/base/content/test/general/browser_bug592338.js +++ b/browser/base/content/test/general/browser_bug592338.js @@ -144,7 +144,7 @@ function test() { AddonManager.getInstallForURL(TESTROOT + "theme.xpi", function(aInstall) { aInstall.addListener({ - onInstallEnded: function() { + onInstallEnded() { AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(aAddon) { isnot(aAddon, null, "Should have installed the test theme."); diff --git a/browser/base/content/test/general/browser_bug676619.js b/browser/base/content/test/general/browser_bug676619.js index a5f49f0d423e..4e3341d76ca3 100644 --- a/browser/base/content/test/general/browser_bug676619.js +++ b/browser/base/content/test/general/browser_bug676619.js @@ -64,7 +64,7 @@ function test() { function addWindowListener(aURL, aCallback) { Services.wm.addListener({ - onOpenWindow: function(aXULWindow) { + onOpenWindow(aXULWindow) { info("window opened, waiting for focus"); Services.wm.removeListener(this); @@ -75,8 +75,8 @@ function addWindowListener(aURL, aCallback) { aCallback(domwindow); }, domwindow); }, - onCloseWindow: function(aXULWindow) { }, - onWindowTitleChange: function(aXULWindow, aNewTitle) { } + onCloseWindow(aXULWindow) { }, + onWindowTitleChange(aXULWindow, aNewTitle) { } }); } @@ -98,7 +98,7 @@ TabOpenListener.prototype = { tab: null, browser: null, - handleEvent: function(event) { + handleEvent(event) { if (event.type == "TabOpen") { gBrowser.tabContainer.removeEventListener("TabOpen", this, false); this.tab = event.originalTarget; diff --git a/browser/base/content/test/general/browser_bug734076.js b/browser/base/content/test/general/browser_bug734076.js index d7aca0250f09..4f0eda31083c 100644 --- a/browser/base/content/test/general/browser_bug734076.js +++ b/browser/base/content/test/general/browser_bug734076.js @@ -15,15 +15,15 @@ add_task(function* () name: "view background image", url: "http://mochi.test:8888/", element: "body", - go: function() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { + go() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { let contentBody = content.document.body; contentBody.style.backgroundImage = "url('" + arg.writeDomainURL + "')"; return "context-viewbgimage"; }); }, - verify: function() { + verify() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for view background image"); @@ -34,8 +34,8 @@ add_task(function* () name: "view image", url: "http://mochi.test:8888/", element: "img", - go: function() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { + go() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { let doc = content.document; let img = doc.createElement("img"); img.height = 100; @@ -46,7 +46,7 @@ add_task(function* () return "context-viewimage"; }); }, - verify: function() { + verify() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for view image"); @@ -57,8 +57,8 @@ add_task(function* () name: "show only this frame", url: "http://mochi.test:8888/", element: "iframe", - go: function() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { + go() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { let doc = content.document; let iframe = doc.createElement("iframe"); iframe.setAttribute("src", arg.writeDomainURL); @@ -73,7 +73,7 @@ add_task(function* () }); }); }, - verify: function() { + verify() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for 'show only this frame'"); diff --git a/browser/base/content/test/general/browser_contentAltClick.js b/browser/base/content/test/general/browser_contentAltClick.js index f6922b9efd6f..bce845ca7148 100644 --- a/browser/base/content/test/general/browser_contentAltClick.js +++ b/browser/base/content/test/general/browser_contentAltClick.js @@ -54,7 +54,7 @@ add_task(function* test_alt_click() // When 1 download has been attempted then resolve the promise. let finishedAllDownloads = new Promise( (resolve) => { downloadView = { - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { downloads.push(aDownload); resolve(); }, @@ -83,7 +83,7 @@ add_task(function* test_alt_click_on_xlinks() // When all 2 downloads have been attempted then resolve the promise. let finishedAllDownloads = new Promise( (resolve) => { downloadView = { - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { downloads.push(aDownload); if (downloads.length == 2) { resolve(); diff --git a/browser/base/content/test/general/browser_contentAreaClick.js b/browser/base/content/test/general/browser_contentAreaClick.js index 921416b82385..db91dd11c71c 100644 --- a/browser/base/content/test/general/browser_contentAreaClick.js +++ b/browser/base/content/test/general/browser_contentAreaClick.js @@ -18,8 +18,8 @@ var gTests = [ { desc: "Simple left click", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: {}, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [], @@ -28,8 +28,8 @@ var gTests = [ { desc: "Ctrl/Cmd left click", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: { ctrlKey: true, metaKey: true }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], @@ -41,10 +41,10 @@ var gTests = [ // just be like Alt click. { desc: "Shift+Alt left click", - setup: function() { + setup() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { shiftKey: true, @@ -56,10 +56,10 @@ var gTests = [ { desc: "Shift+Alt left click on XLinks", - setup: function() { + setup() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { shiftKey: true, @@ -71,8 +71,8 @@ var gTests = [ { desc: "Shift click", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: { shiftKey: true }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ], @@ -81,10 +81,10 @@ var gTests = [ { desc: "Alt click", - setup: function() { + setup() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { altKey: true }, @@ -95,10 +95,10 @@ var gTests = [ { desc: "Alt click on XLinks", - setup: function() { + setup() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { altKey: true }, @@ -109,8 +109,8 @@ var gTests = [ { desc: "Panel click", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: {}, targets: [ "panellink" ], expectedInvokedMethods: [ "urlSecurityCheck", "loadURI" ], @@ -119,8 +119,8 @@ var gTests = [ { desc: "Simple middle click opentab", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: { button: 1 }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ], @@ -129,10 +129,10 @@ var gTests = [ { desc: "Simple middle click openwin", - setup: function() { + setup() { gPrefService.setBoolPref("browser.tabs.opentabfor.middleclick", false); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.tabs.opentabfor.middleclick"); }, event: { button: 1 }, @@ -143,11 +143,11 @@ var gTests = [ { desc: "Middle mouse paste", - setup: function() { + setup() { gPrefService.setBoolPref("middlemouse.contentLoadURL", true); gPrefService.setBoolPref("general.autoScroll", false); }, - clean: function() { + clean() { gPrefService.clearUserPref("middlemouse.contentLoadURL"); gPrefService.clearUserPref("general.autoScroll"); }, @@ -199,7 +199,7 @@ function test() { // Click handler used to steal click events. var gClickHandler = { - handleEvent: function(event) { + handleEvent(event) { let linkId = event.target.id || event.target.localName; is(event.type, "click", gCurrentTest.desc + ":Handler received a click event on " + linkId); diff --git a/browser/base/content/test/general/browser_contentSearchUI.js b/browser/base/content/test/general/browser_contentSearchUI.js index aa346ed2cedd..9dc5fbcfb612 100644 --- a/browser/base/content/test/general/browser_contentSearchUI.js +++ b/browser/base/content/test/general/browser_contentSearchUI.js @@ -195,28 +195,28 @@ add_task(function* cycleSuggestions() { accelKey: true, }; - let state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + let state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); }); @@ -249,22 +249,22 @@ add_task(function* cycleOneOffs() { altKey: true, }; - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1); // If the settings button is selected, pressing alt+up/down should select the @@ -274,13 +274,13 @@ add_task(function* cycleOneOffs() { state = yield msg("key", "VK_TAB"); // Settings button selected. checkState(state, "xbar", ["xfoo", "xbar"], 1, 2); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); state = yield msg("key", "VK_TAB"); checkState(state, "xbar", ["xfoo", "xbar"], 1, 2); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); yield msg("removeLastOneOff"); @@ -418,7 +418,7 @@ add_task(function* search() { // Test typing a query and pressing enter. let p = msg("waitForSearch"); yield msg("key", { key: "x", waitForSuggestions: true }); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); let mesg = yield p; let eventData = { engineName: TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME, @@ -437,7 +437,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("key", "VK_DOWN"); yield msg("key", "VK_DOWN"); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME; @@ -455,7 +455,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("key", "VK_UP"); yield msg("key", "VK_UP"); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); mesg = yield p; delete eventData.selection; eventData.searchString = "x"; @@ -470,7 +470,7 @@ add_task(function* search() { modifiers.button = 0; yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("mousemove", -1); - yield msg("click", { eltIdx: -1, modifiers: modifiers }); + yield msg("click", { eltIdx: -1, modifiers }); mesg = yield p; eventData.originalEvent = modifiers; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME; @@ -483,7 +483,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); p = msg("waitForSearch"); yield msg("mousemove", 1); - yield msg("click", { eltIdx: 1, modifiers: modifiers }); + yield msg("click", { eltIdx: 1, modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.selection = { @@ -499,7 +499,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); p = msg("waitForSearch"); yield msg("mousemove", 3); - yield msg("click", { eltIdx: 3, modifiers: modifiers }); + yield msg("click", { eltIdx: 3, modifiers }); mesg = yield p; eventData.searchString = "x"; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_2_BASENAME; @@ -515,7 +515,7 @@ add_task(function* search() { p = msg("waitForSearch"); yield msg("mousemove", 1); yield msg("mousemove", 3); - yield msg("click", { eltIdx: 3, modifiers: modifiers }); + yield msg("click", { eltIdx: 3, modifiers }); mesg = yield p; eventData.searchString = "xfoo" eventData.selection = { @@ -534,7 +534,7 @@ add_task(function* search() { yield msg("key", "VK_DOWN"); yield msg("key", "VK_DOWN"); yield msg("key", "VK_TAB"); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); mesg = yield p; eventData.selection = { index: 1, @@ -554,7 +554,7 @@ add_task(function* search() { yield msg("commitComposition"); delete modifiers.button; p = msg("waitForSearch"); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); mesg = yield p; eventData.searchString = "x" eventData.originalEvent = modifiers; @@ -583,7 +583,7 @@ add_task(function* search() { modifiers.button = 0; p = msg("waitForSearch"); - yield msg("click", { eltIdx: 1, modifiers: modifiers }); + yield msg("click", { eltIdx: 1, modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.originalEvent = modifiers; @@ -662,8 +662,8 @@ function setUp(aNoEngine) { function msg(type, data = null) { gMsgMan.sendAsyncMessage(TEST_MSG, { - type: type, - data: data, + type, + data, }); let deferred = Promise.defer(); gMsgMan.addMessageListener(TEST_MSG, function onMsg(msgObj) { diff --git a/browser/base/content/test/general/browser_contextmenu.js b/browser/base/content/test/general/browser_contextmenu.js index 3e0135848ee4..88bf6a2f6192 100644 --- a/browser/base/content/test/general/browser_contextmenu.js +++ b/browser/base/content/test/general/browser_contextmenu.js @@ -500,7 +500,7 @@ add_task(function* test_contenteditable() { add_task(function* test_copylinkcommand() { yield test_contextmenu("#test-link", null, { - postCheckContextMenuFn: function*() { + *postCheckContextMenuFn() { document.commandDispatcher .getControllerForCommand("cmd_copyLink") .doCommand("cmd_copyLink"); @@ -562,7 +562,7 @@ add_task(function* test_pagemenu() { "context-viewsource", true, "context-viewinfo", true ], - {postCheckContextMenuFn: function*() { + {*postCheckContextMenuFn() { let item = contextMenu.getElementsByAttribute("generateditemid", "1")[0]; ok(item, "Got generated XUL menu item"); item.doCommand(); @@ -820,11 +820,11 @@ add_task(function* test_click_to_play_blocked_plugin() { "context-viewinfo", true ], { - preCheckContextMenuFn: function*() { + *preCheckContextMenuFn() { pushPrefs(["plugins.click_to_play", true]); setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY); }, - postCheckContextMenuFn: function*() { + *postCheckContextMenuFn() { getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_ENABLED; } } diff --git a/browser/base/content/test/general/browser_devedition.js b/browser/base/content/test/general/browser_devedition.js index d11a26e264be..4369b6b2bcd2 100644 --- a/browser/base/content/test/general/browser_devedition.js +++ b/browser/base/content/test/general/browser_devedition.js @@ -80,7 +80,7 @@ add_task(function* testDevtoolsTheme() { function dummyLightweightTheme(id) { return { - id: id, + id, name: id, headerURL: "resource:///chrome/browser/content/browser/defaultthemes/devedition.header.png", iconURL: "resource:///chrome/browser/content/browser/defaultthemes/devedition.icon.png", diff --git a/browser/base/content/test/general/browser_documentnavigation.js b/browser/base/content/test/general/browser_documentnavigation.js index eb789d0766a9..2047795491c9 100644 --- a/browser/base/content/test/general/browser_documentnavigation.js +++ b/browser/base/content/test/general/browser_documentnavigation.js @@ -60,7 +60,7 @@ function* expectFocusOnF6(backward, expectedDocument, expectedElement, onContent details += "," + contentFM.focusedElement.id; } - sendSyncMessage("BrowserTest:FocusChanged", { details : details }); + sendSyncMessage("BrowserTest:FocusChanged", { details }); }, true); }); } diff --git a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js b/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js index b1dde6b5ae62..01c9389ef997 100644 --- a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js +++ b/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js @@ -114,7 +114,7 @@ var gTests = [ { desc: "F11 key", affectsFullscreenMode: true, - exitFunc: function() { + exitFunc() { executeSoon(() => EventUtils.synthesizeKey("VK_F11", {})); } } diff --git a/browser/base/content/test/general/browser_e10s_about_process.js b/browser/base/content/test/general/browser_e10s_about_process.js index 2b4816754aa2..d3dcc56b9e57 100644 --- a/browser/base/content/test/general/browser_e10s_about_process.js +++ b/browser/base/content/test/general/browser_e10s_about_process.js @@ -27,11 +27,11 @@ function AboutModule() { } AboutModule.prototype = { - newChannel: function(aURI, aLoadInfo) { + newChannel(aURI, aLoadInfo) { throw Components.results.NS_ERROR_NOT_IMPLEMENTED; }, - getURIFlags: function(aURI) { + getURIFlags(aURI) { for (let module of TEST_MODULES) { if (aURI.path.startsWith(module.path)) { return module.flags; @@ -42,7 +42,7 @@ AboutModule.prototype = { return 0; }, - getIndexedDBOriginPostfix: function(aURI) { + getIndexedDBOriginPostfix(aURI) { return null; }, @@ -50,13 +50,13 @@ AboutModule.prototype = { }; var AboutModuleFactory = { - createInstance: function(aOuter, aIID) { + createInstance(aOuter, aIID) { if (aOuter) throw Components.results.NS_ERROR_NO_AGGREGATION; return new AboutModule().QueryInterface(aIID); }, - lockFactory: function(aLock) { + lockFactory(aLock) { throw Components.results.NS_ERROR_NOT_IMPLEMENTED; }, diff --git a/browser/base/content/test/general/browser_fullscreen-window-open.js b/browser/base/content/test/general/browser_fullscreen-window-open.js index f6e0063328c6..169657ff1aa0 100644 --- a/browser/base/content/test/general/browser_fullscreen-window-open.js +++ b/browser/base/content/test/general/browser_fullscreen-window-open.js @@ -66,7 +66,7 @@ function test_open() { title: "test_open", param: "", }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -77,7 +77,7 @@ function test_open_with_size() { title: "test_open_with_size", param: "width=400,height=400", }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -88,7 +88,7 @@ function test_open_with_pos() { title: "test_open_with_pos", param: "top=200,left=200", }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -100,11 +100,11 @@ function test_open_with_outerSize() { title: "test_open_with_outerSize", param: "outerWidth=200,outerHeight=200", }, - successFn: function() { + successFn() { is(window.outerWidth, outerWidth, "Don't change window.outerWidth."); is(window.outerHeight, outerHeight, "Don't change window.outerHeight."); }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -116,11 +116,11 @@ function test_open_with_innerSize() { title: "test_open_with_innerSize", param: "innerWidth=200,innerHeight=200", }, - successFn: function() { + successFn() { is(window.innerWidth, innerWidth, "Don't change window.innerWidth."); is(window.innerHeight, innerHeight, "Don't change window.innerHeight."); }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -131,7 +131,7 @@ function test_open_with_dialog() { title: "test_open_with_dialog", param: "dialog=yes", }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -148,7 +148,7 @@ function test_open_when_open_new_window_by_pref() { title: "test_open_when_open_new_window_by_pref", param: "width=400,height=400", }, - finalizeFn: function() { + finalizeFn() { Services.prefs.clearUserPref(PREF_NAME); }, }); @@ -163,7 +163,7 @@ function test_open_with_pref_to_disable_in_fullscreen() { title: "test_open_with_pref_disabled_in_fullscreen", param: "width=400,height=400", }, - finalizeFn: function() { + finalizeFn() { Services.prefs.setBoolPref(PREF_DISABLE_OPEN_NEW_WINDOW, true); }, }); @@ -177,7 +177,7 @@ function test_open_from_chrome() { title: "test_open_from_chrome", param: "", }, - finalizeFn: function() {} + finalizeFn() {} }); } @@ -251,7 +251,7 @@ function waitForWindowOpen(aOptions) { let listener = new WindowListener(message.title, getBrowserURL(), { onSuccess: aOptions.successFn, - onFinalize: onFinalize, + onFinalize, }); Services.wm.addListener(listener); @@ -292,7 +292,7 @@ function waitForWindowOpenFromChrome(aOptions) { let listener = new WindowListener(message.title, getBrowserURL(), { onSuccess: aOptions.successFn, - onFinalize: onFinalize, + onFinalize, }); Services.wm.addListener(listener); @@ -312,7 +312,7 @@ WindowListener.prototype = { callback_onSuccess: null, callBack_onFinalize: null, - onOpenWindow: function(aXULWindow) { + onOpenWindow(aXULWindow) { Services.wm.removeListener(this); let domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -340,8 +340,8 @@ WindowListener.prototype = { }; domwindow.addEventListener("load", onLoad, true); }, - onCloseWindow: function(aXULWindow) {}, - onWindowTitleChange: function(aXULWindow, aNewTitle) {}, + onCloseWindow(aXULWindow) {}, + onWindowTitleChange(aXULWindow, aNewTitle) {}, QueryInterface: XPCOMUtils.generateQI([Ci.nsIWindowMediatorListener, Ci.nsISupports]), }; diff --git a/browser/base/content/test/general/browser_fxa_oauth.js b/browser/base/content/test/general/browser_fxa_oauth.js index b676d2bd06d9..5babfa638e9e 100644 --- a/browser/base/content/test/general/browser_fxa_oauth.js +++ b/browser/base/content/test/general/browser_fxa_oauth.js @@ -21,7 +21,7 @@ const HTTP_ENDPOINT_WITH_KEYS = "/browser/browser/base/content/test/general/brow var gTests = [ { desc: "FxA OAuth - should open a new tab, complete OAuth flow", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; let properURL = "http://example.com/browser/browser/base/content/test/general/browser_fxa_oauth.html"; @@ -74,7 +74,7 @@ var gTests = [ }, { desc: "FxA OAuth - should open a new tab, complete OAuth flow when forcing auth", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; let properURL = "http://example.com/browser/browser/base/content/test/general/browser_fxa_oauth.html"; @@ -131,7 +131,7 @@ var gTests = [ }, { desc: "FxA OAuth - should receive an error when there's a state mismatch", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -169,7 +169,7 @@ var gTests = [ }, { desc: "FxA OAuth - should be able to request keys during OAuth flow", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -211,7 +211,7 @@ var gTests = [ }, { desc: "FxA OAuth - should not receive keys if not explicitly requested", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -252,7 +252,7 @@ var gTests = [ }, { desc: "FxA OAuth - should receive an error if keys could not be obtained", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; diff --git a/browser/base/content/test/general/browser_fxa_web_channel.js b/browser/base/content/test/general/browser_fxa_web_channel.js index ad4fb7b57ae4..a87c2338a6b4 100644 --- a/browser/base/content/test/general/browser_fxa_web_channel.js +++ b/browser/base/content/test/general/browser_fxa_web_channel.js @@ -23,7 +23,7 @@ const TEST_CHANNEL_ID = "account_updates_test"; var gTests = [ { desc: "FxA Web Channel - should receive message about profile changes", - run: function* () { + *run() { let client = new FxAccountsWebChannel({ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, @@ -37,7 +37,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: TEST_BASE_URL + "?profile_change" }, function* () { yield promiseObserver; @@ -46,7 +46,7 @@ var gTests = [ }, { desc: "fxa web channel - login messages should notify the fxAccounts object", - run: function* () { + *run() { let promiseLogin = new Promise((resolve, reject) => { let login = (accountData) => { @@ -66,13 +66,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - login: login + login } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: TEST_BASE_URL + "?login" }, function* () { yield promiseLogin; @@ -81,7 +81,7 @@ var gTests = [ }, { desc: "fxa web channel - can_link_account messages should respond", - run: function* () { + *run() { let properUrl = TEST_BASE_URL + "?can_link_account"; let promiseEcho = new Promise((resolve, reject) => { @@ -114,7 +114,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: properUrl }, function* () { yield promiseEcho; @@ -123,7 +123,7 @@ var gTests = [ }, { desc: "fxa web channel - logout messages should notify the fxAccounts object", - run: function* () { + *run() { let promiseLogout = new Promise((resolve, reject) => { let logout = (uid) => { Assert.equal(uid, 'uid'); @@ -136,13 +136,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - logout: logout + logout } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: TEST_BASE_URL + "?logout" }, function* () { yield promiseLogout; @@ -151,7 +151,7 @@ var gTests = [ }, { desc: "fxa web channel - delete messages should notify the fxAccounts object", - run: function* () { + *run() { let promiseDelete = new Promise((resolve, reject) => { let logout = (uid) => { Assert.equal(uid, 'uid'); @@ -164,13 +164,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - logout: logout + logout } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: TEST_BASE_URL + "?delete" }, function* () { yield promiseDelete; diff --git a/browser/base/content/test/general/browser_fxaccounts.js b/browser/base/content/test/general/browser_fxaccounts.js index cc7abad9ffdb..ae61ce0f3874 100644 --- a/browser/base/content/test/general/browser_fxaccounts.js +++ b/browser/base/content/test/general/browser_fxaccounts.js @@ -16,7 +16,7 @@ const TEST_ROOT = "http://example.com/browser/browser/base/content/test/general/ // The stub functions. let stubs = { - updateAppMenuItem: function() { + updateAppMenuItem() { return unstubs['updateAppMenuItem'].call(gFxAccounts).then(() => { Services.obs.notifyObservers(null, "test:browser_fxaccounts:updateAppMenuItem", null); }); @@ -25,7 +25,7 @@ const TEST_ROOT = "http://example.com/browser/browser/base/content/test/general/ // due to the promises it fires off at load time and there's no clear way to // know when they are done. // So just ensure openPreferences is called rather than whether it opens. - openPreferences: function() { + openPreferences() { Services.obs.notifyObservers(null, "test:browser_fxaccounts:openPreferences", null); } }; @@ -237,7 +237,7 @@ function setSignedInUser(verified) { sessionToken: "dead", kA: "beef", kB: "cafe", - verified: verified, + verified, oauthTokens: { // a token for the profile server. diff --git a/browser/base/content/test/general/browser_getshortcutoruri.js b/browser/base/content/test/general/browser_getshortcutoruri.js index a318ab6d1f04..7c54ac4975e1 100644 --- a/browser/base/content/test/general/browser_getshortcutoruri.js +++ b/browser/base/content/test/general/browser_getshortcutoruri.js @@ -19,7 +19,7 @@ function keywordResult(aURL, aPostData, aIsUnsafe) { function keyWordData() {} keyWordData.prototype = { - init: function(aKeyWord, aURL, aPostData, aSearchWord) { + init(aKeyWord, aURL, aPostData, aSearchWord) { this.keyword = aKeyWord; this.uri = makeURI(aURL); this.postData = aPostData; diff --git a/browser/base/content/test/general/browser_homeDrop.js b/browser/base/content/test/general/browser_homeDrop.js index 061ea17f0033..32228fca459e 100644 --- a/browser/base/content/test/general/browser_homeDrop.js +++ b/browser/base/content/test/general/browser_homeDrop.js @@ -32,7 +32,7 @@ add_task(function*() { let setHomepagePromise = new Promise(function(resolve) { let observer = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), - observe: function(subject, topic, data) { + observe(subject, topic, data) { is(topic, "nsPref:changed", "observed correct topic"); is(data, HOMEPAGE_PREF, "observed correct data"); let modified = Services.prefs.getComplexValue(HOMEPAGE_PREF, @@ -57,7 +57,7 @@ add_task(function*() { function dropInvalidURI() { return new Promise(resolve => { let consoleListener = { - observe: function(m) { + observe(m) { if (m.message.includes("NS_ERROR_DOM_BAD_URI")) { ok(true, "drop was blocked"); resolve(); diff --git a/browser/base/content/test/general/browser_keywordSearch.js b/browser/base/content/test/general/browser_keywordSearch.js index 4d64febef6d8..ff6ef4a0832f 100644 --- a/browser/base/content/test/general/browser_keywordSearch.js +++ b/browser/base/content/test/general/browser_keywordSearch.js @@ -20,7 +20,7 @@ function test() { waitForExplicitFinish(); let windowObserver = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { ok(false, "Alert window opened"); let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget); diff --git a/browser/base/content/test/general/browser_plainTextLinks.js b/browser/base/content/test/general/browser_plainTextLinks.js index 7a304fce0c89..a6f436dec1df 100644 --- a/browser/base/content/test/general/browser_plainTextLinks.js +++ b/browser/base/content/test/general/browser_plainTextLinks.js @@ -119,7 +119,7 @@ add_task(function *() { let contentAreaContextMenu = document.getElementById("contentAreaContextMenu"); for (let testid = 0; testid < checks.length; testid++) { - let menuPosition = yield ContentTask.spawn(gBrowser.selectedBrowser, { testid: testid }, function* (arg) { + let menuPosition = yield ContentTask.spawn(gBrowser.selectedBrowser, { testid }, function* (arg) { let range = content.tests[arg.testid](); // Get the range of the selection and determine its coordinates. These diff --git a/browser/base/content/test/general/browser_restore_isAppTab.js b/browser/base/content/test/general/browser_restore_isAppTab.js index 3e53efd326f7..1e98ae0dc118 100644 --- a/browser/base/content/test/general/browser_restore_isAppTab.js +++ b/browser/base/content/test/general/browser_restore_isAppTab.js @@ -14,7 +14,7 @@ function getMinidumpDirectory() { // This observer is needed so we can clean up all evidence of the crash so // the testrunner thinks things are peachy. var CrashObserver = { - observe: function(subject, topic, data) { + observe(subject, topic, data) { is(topic, 'ipc:content-shutdown', 'Received correct observer topic.'); ok(subject instanceof Ci.nsIPropertyBag2, 'Subject implements nsIPropertyBag2.'); diff --git a/browser/base/content/test/general/browser_sanitize-timespans.js b/browser/base/content/test/general/browser_sanitize-timespans.js index f1096246c35c..813e72f1af7a 100644 --- a/browser/base/content/test/general/browser_sanitize-timespans.js +++ b/browser/base/content/test/general/browser_sanitize-timespans.js @@ -31,7 +31,7 @@ function promiseDownloadRemoved(list) { let deferred = Promise.defer(); let view = { - onDownloadRemoved: function(download) { + onDownloadRemoved(download) { list.removeView(view); deferred.resolve(); } @@ -58,11 +58,11 @@ function countEntries(name, message, check) { let count; FormHistory.count(obj, { handleResult: result => count = result, - handleError: function(error) { + handleError(error) { deferred.reject(error) throw new Error("Error occurred searching form history: " + error); }, - handleCompletion: function(reason) { + handleCompletion(reason) { if (!reason) { check(count, message); deferred.resolve(); @@ -493,11 +493,11 @@ function* setupFormHistory() { let results = []; FormHistory.search(terms, params, { handleResult: result => results.push(result), - handleError: function(error) { + handleError(error) { deferred.reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion: function(reason) { deferred.resolve(results); } + handleCompletion(reason) { deferred.resolve(results); } }); return deferred.promise; } @@ -505,11 +505,11 @@ function* setupFormHistory() { function update(changes) { let deferred = Promise.defer(); - FormHistory.update(changes, { handleError: function(error) { + FormHistory.update(changes, { handleError(error) { deferred.reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion: function(reason) { deferred.resolve(); } + handleCompletion(reason) { deferred.resolve(); } }); return deferred.promise; } diff --git a/browser/base/content/test/general/browser_sanitizeDialog.js b/browser/base/content/test/general/browser_sanitizeDialog.js index e7708aede954..7b469e76eeb4 100644 --- a/browser/base/content/test/general/browser_sanitizeDialog.js +++ b/browser/base/content/test/general/browser_sanitizeDialog.js @@ -572,7 +572,7 @@ add_task(function* test_offline_cache() { // Check if the cache has been deleted var size = -1; var visitor = { - onCacheStorageInfo: function(aEntryCount, aConsumption, aCapacity, aDiskDirectory) + onCacheStorageInfo(aEntryCount, aConsumption, aCapacity, aDiskDirectory) { size = aConsumption; } @@ -583,8 +583,8 @@ add_task(function* test_offline_cache() { }; var cacheListener = { - onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable: function(entry, isnew, unused, status) { + onCacheEntryCheck() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, + onCacheEntryAvailable(entry, isnew, unused, status) { is(status, Cr.NS_OK); var stream = entry.openOutputStream(0); var content = "content"; @@ -648,7 +648,7 @@ WindowHelper.prototype = { /** * "Presses" the dialog's OK button. */ - acceptDialog: function() { + acceptDialog() { is(this.win.document.documentElement.getButton("accept").disabled, false, "Dialog's OK button should not be disabled"); this.win.document.documentElement.acceptDialog(); @@ -657,7 +657,7 @@ WindowHelper.prototype = { /** * "Presses" the dialog's Cancel button. */ - cancelDialog: function() { + cancelDialog() { this.win.document.documentElement.cancelDialog(); }, @@ -669,7 +669,7 @@ WindowHelper.prototype = { * @param aShouldBeShown * True if you expect the details to be shown and false if hidden */ - checkDetails: function(aShouldBeShown) { + checkDetails(aShouldBeShown) { let button = this.getDetailsButton(); let list = this.getItemList(); let hidden = list.hidden || list.collapsed; @@ -700,7 +700,7 @@ WindowHelper.prototype = { * @param aCheckState * True if the checkbox should be checked, false otherwise */ - checkPrefCheckbox: function(aPrefName, aCheckState) { + checkPrefCheckbox(aPrefName, aCheckState) { var pref = "privacy.cpd." + aPrefName; var cb = this.win.document.querySelectorAll( "#itemList > [preference='" + pref + "']"); @@ -712,7 +712,7 @@ WindowHelper.prototype = { /** * Makes sure all the checkboxes are checked. */ - _checkAllCheckboxesCustom: function(check) { + _checkAllCheckboxesCustom(check) { var cb = this.win.document.querySelectorAll("#itemList > [preference]"); ok(cb.length > 1, "found checkboxes for preferences"); for (var i = 0; i < cb.length; ++i) { @@ -722,39 +722,39 @@ WindowHelper.prototype = { } }, - checkAllCheckboxes: function() { + checkAllCheckboxes() { this._checkAllCheckboxesCustom(true); }, - uncheckAllCheckboxes: function() { + uncheckAllCheckboxes() { this._checkAllCheckboxesCustom(false); }, /** * @return The details progressive disclosure button */ - getDetailsButton: function() { + getDetailsButton() { return this.win.document.getElementById("detailsExpander"); }, /** * @return The dialog's duration dropdown */ - getDurationDropdown: function() { + getDurationDropdown() { return this.win.document.getElementById("sanitizeDurationChoice"); }, /** * @return The item list hidden by the details progressive disclosure button */ - getItemList: function() { + getItemList() { return this.win.document.getElementById("itemList"); }, /** * @return The clear-everything warning box */ - getWarningPanel: function() { + getWarningPanel() { return this.win.document.getElementById("sanitizeEverythingWarningBox"); }, @@ -762,7 +762,7 @@ WindowHelper.prototype = { * @return True if the "Everything" warning panel is visible (as opposed to * the tree) */ - isWarningPanelVisible: function() { + isWarningPanelVisible() { return !this.getWarningPanel().hidden; }, @@ -774,7 +774,7 @@ WindowHelper.prototype = { * caller is expected to call waitForAsyncUpdates at some point; if false is * returned, waitForAsyncUpdates is called automatically. */ - open: function() { + open() { let wh = this; function windowObserver(aSubject, aTopic, aData) { @@ -835,7 +835,7 @@ WindowHelper.prototype = { * @param aDurVal * One of the Sanitizer.TIMESPAN_* values */ - selectDuration: function(aDurVal) { + selectDuration(aDurVal) { this.getDurationDropdown().value = aDurVal; if (aDurVal === Sanitizer.TIMESPAN_EVERYTHING) { is(this.isWarningPanelVisible(), true, @@ -850,7 +850,7 @@ WindowHelper.prototype = { /** * Toggles the details progressive disclosure button. */ - toggleDetails: function() { + toggleDetails() { this.getDetailsButton().click(); } }; @@ -898,11 +898,11 @@ function promiseAddFormEntryWithMinutesAgo(aMinutesAgo) { return new Promise((resolve, reject) => FormHistory.update({ op: "add", fieldname: name, value: "dummy", firstUsed: timestamp }, - { handleError: function(error) { + { handleError(error) { reject(); throw new Error("Error occurred updating form history: " + error); }, - handleCompletion: function(reason) { + handleCompletion(reason) { resolve(name); } }) @@ -918,11 +918,11 @@ function formNameExists(name) let count = 0; FormHistory.count({ fieldname: name }, { handleResult: result => count = result, - handleError: function(error) { + handleError(error) { reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion: function(reason) { + handleCompletion(reason) { if (!reason) { resolve(count); } diff --git a/browser/base/content/test/general/browser_save_link_when_window_navigates.js b/browser/base/content/test/general/browser_save_link_when_window_navigates.js index 2da54eb92351..103985ac9f6f 100644 --- a/browser/base/content/test/general/browser_save_link_when_window_navigates.js +++ b/browser/base/content/test/general/browser_save_link_when_window_navigates.js @@ -90,13 +90,13 @@ function triggerSave(aWindow, aCallback) { var windowObserver = { - setCallback: function(aCallback) { + setCallback(aCallback) { if (this._callback) { ok(false, "Should only be dealing with one callback at a time."); } this._callback = aCallback; }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic != "domwindowopened") { return; } diff --git a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js index 92fb7bd0392f..6da92c10e478 100644 --- a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js +++ b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js @@ -15,17 +15,17 @@ function createTemporarySaveDirectory() { function promiseNoCacheEntry(filename) { return new Promise((resolve, reject) => { Visitor.prototype = { - onCacheStorageInfo: function(num, consumption) + onCacheStorageInfo(num, consumption) { info("disk storage contains " + num + " entries"); }, - onCacheEntryInfo: function(uri) + onCacheEntryInfo(uri) { let urispec = uri.asciiSpec; info(urispec); is(urispec.includes(filename), false, "web content present in disk cache"); }, - onCacheEntryVisitCompleted: function() + onCacheEntryVisitCompleted() { resolve(); } diff --git a/browser/base/content/test/general/browser_tabfocus.js b/browser/base/content/test/general/browser_tabfocus.js index 96b6b315388b..42552caa5ae4 100644 --- a/browser/base/content/test/general/browser_tabfocus.js +++ b/browser/base/content/test/general/browser_tabfocus.js @@ -53,7 +53,7 @@ function* getFocusedElementForBrowser(browser, dontCheckExtraFocus = false) // additional focus related properties. This is needed as both URLs are // loaded using the same child process and share focus managers. browser.messageManager.sendAsyncMessage("Browser:GetFocusedElement", - { dontCheckExtraFocus : dontCheckExtraFocus }); + { dontCheckExtraFocus }); }); } var focusedWindow = {}; @@ -113,7 +113,7 @@ function focusInChild() } } - sendSyncMessage("Browser:GetCurrentFocus", { details : details }); + sendSyncMessage("Browser:GetCurrentFocus", { details }); }); } @@ -122,7 +122,7 @@ function focusElementInChild(elementid, type) let browser = (elementid.indexOf("1") >= 0) ? browser1 : browser2; if (gMultiProcessBrowser) { browser.messageManager.sendAsyncMessage("Browser:ChangeFocus", - { id: elementid, type: type }); + { id: elementid, type }); } else { browser.contentDocument.getElementById(elementid)[type](); diff --git a/browser/base/content/test/general/browser_tabopen_reflows.js b/browser/base/content/test/general/browser_tabopen_reflows.js index 4eb6c77ab1ab..eed2eecb1417 100644 --- a/browser/base/content/test/general/browser_tabopen_reflows.js +++ b/browser/base/content/test/general/browser_tabopen_reflows.js @@ -113,7 +113,7 @@ add_task(function*() { }); var observer = { - reflow: function(start, end) { + reflow(start, end) { // Gather information about the current code path. let path = (new Error().stack).split("\n").slice(1).map(line => { return line.replace(/:\d+:\d+$/, ""); @@ -136,7 +136,7 @@ var observer = { ok(false, "unexpected uninterruptible reflow '" + pathWithLineNumbers + "'"); }, - reflowInterruptible: function(start, end) { + reflowInterruptible(start, end) { // We're not interested in interruptible reflows. }, diff --git a/browser/base/content/test/general/browser_trackingUI_4.js b/browser/base/content/test/general/browser_trackingUI_4.js index 234b790acb44..ba0478f7f852 100644 --- a/browser/base/content/test/general/browser_trackingUI_4.js +++ b/browser/base/content/test/general/browser_trackingUI_4.js @@ -28,7 +28,7 @@ function waitForSecurityChange(numChanges = 1) { return new Promise(resolve => { let n = 0; let listener = { - onSecurityChange: function() { + onSecurityChange() { n = n + 1; info("Received onSecurityChange event " + n + " of " + numChanges); if (n >= numChanges) { diff --git a/browser/base/content/test/general/browser_trackingUI_6.js b/browser/base/content/test/general/browser_trackingUI_6.js index be47263ba3c1..33a337231f1e 100644 --- a/browser/base/content/test/general/browser_trackingUI_6.js +++ b/browser/base/content/test/general/browser_trackingUI_6.js @@ -4,7 +4,7 @@ function waitForSecurityChange(numChanges = 1) { return new Promise(resolve => { let n = 0; let listener = { - onSecurityChange: function() { + onSecurityChange() { n = n + 1; info("Received onSecurityChange event " + n + " of " + numChanges); if (n >= numChanges) { diff --git a/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js b/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js index eedc7116b30c..2afedba0dac9 100644 --- a/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js +++ b/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js @@ -1,7 +1,7 @@ function wait_while_tab_is_busy() { return new Promise(resolve => { let progressListener = { - onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) { gBrowser.removeProgressListener(this); setTimeout(resolve, 0); diff --git a/browser/base/content/test/general/browser_web_channel.js b/browser/base/content/test/general/browser_web_channel.js index f1bcd4711bd7..ab7eaaf21f8d 100644 --- a/browser/base/content/test/general/browser_web_channel.js +++ b/browser/base/content/test/general/browser_web_channel.js @@ -20,7 +20,7 @@ const HTTP_REDIRECTED_IFRAME_PATH = "http://example.org"; var gTests = [ { desc: "WebChannel generic message", - run: function* () { + *run() { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("generic", Services.io.newURI(HTTP_PATH, null, null)); @@ -38,7 +38,7 @@ var gTests = [ }, { desc: "WebChannel generic message in a private window.", - run: function* () { + *run() { let promiseTestDone = new Promise(function(resolve, reject) { let channel = new WebChannel("generic", Services.io.newURI(HTTP_PATH, null, null)); channel.listen(function(id, message, target) { @@ -58,7 +58,7 @@ var gTests = [ }, { desc: "WebChannel two way communication", - run: function* () { + *run() { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("twoway", Services.io.newURI(HTTP_PATH, null, null)); @@ -85,7 +85,7 @@ var gTests = [ }, { desc: "WebChannel two way communication in an iframe", - run: function* () { + *run() { let parentChannel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); let iframeChannel = new WebChannel("twoway", Services.io.newURI(HTTP_IFRAME_PATH, null, null)); let promiseTestDone = new Promise(function(resolve, reject) { @@ -108,7 +108,7 @@ var gTests = [ }); }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?iframe" }, function* () { yield promiseTestDone; @@ -119,7 +119,7 @@ var gTests = [ }, { desc: "WebChannel response to a redirected iframe", - run: function* () { + *run() { /** * This test checks that WebChannel responses are only sent * to an iframe if the iframe has not redirected to another origin. @@ -172,7 +172,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?iframe_pre_redirect" }, function* () { yield promiseTestDone; @@ -183,7 +183,7 @@ var gTests = [ }, { desc: "WebChannel multichannel", - run: function* () { + *run() { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("multichannel", Services.io.newURI(HTTP_PATH, null, null)); @@ -200,7 +200,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send, using system principal", - run: function* () { + *run() { let channel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); // an unsolicted message is sent from Chrome->Content which is then @@ -230,7 +230,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send, using target origin's principal", - run: function* () { + *run() { let targetURI = Services.io.newURI(HTTP_PATH, null, null); let channel = new WebChannel("echo", targetURI); @@ -263,7 +263,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send with principal mismatch", - run: function* () { + *run() { let targetURI = Services.io.newURI(HTTP_PATH, null, null); let channel = new WebChannel("echo", targetURI); @@ -284,7 +284,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?unsolicited" }, function* (targetBrowser) { @@ -314,7 +314,7 @@ var gTests = [ }, { desc: "WebChannel non-window target", - run: function* () { + *run() { /** * This test ensures messages can be received from and responses * sent to non-window elements. @@ -350,7 +350,7 @@ var gTests = [ }, { desc: "WebChannel disallows non-string message from non-whitelisted origin", - run: function* () { + *run() { /** * This test ensures that non-string messages can't be sent via WebChannels. * We create a page (on a non-whitelisted origin) which should send us two @@ -377,7 +377,7 @@ var gTests = [ }, { desc: "WebChannel allows both string and non-string message from whitelisted origin", - run: function* () { + *run() { /** * Same process as above, but we whitelist the origin before loading the page, * and expect to get *both* messages back (each exactly once). @@ -419,7 +419,7 @@ var gTests = [ }, { desc: "WebChannel errors handling the message are delivered back to content", - run: function* () { + *run() { const ERRNO_UNKNOWN_ERROR = 999; // WebChannel.jsm doesn't export this. // The channel where we purposely fail responding to a command. @@ -455,7 +455,7 @@ var gTests = [ }, { desc: "WebChannel errors due to an invalid channel are delivered back to content", - run: function* () { + *run() { const ERRNO_NO_SUCH_CHANNEL = 2; // WebChannel.jsm doesn't export this. // The channel where we see the response when the content sees the error let echoChannel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); diff --git a/browser/base/content/test/general/browser_windowactivation.js b/browser/base/content/test/general/browser_windowactivation.js index cac9e8866d6c..4759bb68b80c 100644 --- a/browser/base/content/test/general/browser_windowactivation.js +++ b/browser/base/content/test/general/browser_windowactivation.js @@ -109,8 +109,8 @@ function reallyRunTests() { function sendGetBackgroundRequest(ifChanged) { - browser1.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged: ifChanged }); - browser2.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged: ifChanged }); + browser1.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged }); + browser2.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged }); } function runOtherWindowTests() { @@ -177,7 +177,7 @@ function childFunction() if (oldColor != color || !ifChanged) { expectingResponse = false; oldColor = color; - sendAsyncMessage("Test:BackgroundColorChanged", { color: color }); + sendAsyncMessage("Test:BackgroundColorChanged", { color }); } }, 20); } diff --git a/browser/base/content/test/general/browser_windowopen_reflows.js b/browser/base/content/test/general/browser_windowopen_reflows.js index 8d82b715a5d4..c5b3d15f3065 100644 --- a/browser/base/content/test/general/browser_windowopen_reflows.js +++ b/browser/base/content/test/general/browser_windowopen_reflows.js @@ -73,7 +73,7 @@ function test() { } var observer = { - reflow: function(start, end) { + reflow(start, end) { // Gather information about the current code path. let stack = new Error().stack; let path = stack.split("\n").slice(1).map(line => { @@ -99,7 +99,7 @@ var observer = { ok(false, "unexpected uninterruptible reflow '" + pathWithLineNumbers + "'"); }, - reflowInterruptible: function(start, end) { + reflowInterruptible(start, end) { // We're not interested in interruptible reflows. }, diff --git a/browser/base/content/test/general/contentSearchUI.js b/browser/base/content/test/general/contentSearchUI.js index bbb9a2d85b87..87851f65c4e3 100644 --- a/browser/base/content/test/general/contentSearchUI.js +++ b/browser/base/content/test/general/contentSearchUI.js @@ -15,7 +15,7 @@ addMessageListener(TEST_MSG, msg => { var messageHandlers = { - init: function() { + init() { Services.search.currentEngine = Services.search.getEngineByName(ENGINE_NAME); let input = content.document.querySelector("input"); gController = @@ -29,19 +29,19 @@ var messageHandlers = { }); }, - key: function(arg) { + key(arg) { let keyName = typeof(arg) == "string" ? arg : arg.key; content.synthesizeKey(keyName, arg.modifiers || {}); let wait = arg.waitForSuggestions ? waitForSuggestions : cb => cb(); wait(ack.bind(null, "key")); }, - startComposition: function(arg) { + startComposition(arg) { content.synthesizeComposition({ type: "compositionstart", data: "" }); ack("startComposition"); }, - changeComposition: function(arg) { + changeComposition(arg) { let data = typeof(arg) == "string" ? arg : arg.data; content.synthesizeCompositionChange({ composition: { @@ -56,31 +56,31 @@ var messageHandlers = { wait(ack.bind(null, "changeComposition")); }, - commitComposition: function() { + commitComposition() { content.synthesizeComposition({ type: "compositioncommitasis" }); ack("commitComposition"); }, - focus: function() { + focus() { gController.input.focus(); ack("focus"); }, - blur: function() { + blur() { gController.input.blur(); ack("blur"); }, - waitForSearch: function() { + waitForSearch() { waitForContentSearchEvent("Search", aData => ack("waitForSearch", aData)); }, - waitForSearchSettings: function() { + waitForSearchSettings() { waitForContentSearchEvent("ManageEngines", aData => ack("waitForSearchSettings", aData)); }, - mousemove: function(itemIndex) { + mousemove(itemIndex) { let row; if (itemIndex == -1) { row = gController._table.firstChild; @@ -102,7 +102,7 @@ var messageHandlers = { content.synthesizeMouseAtCenter(row, event); }, - click: function(arg) { + click(arg) { let eltIdx = typeof(arg) == "object" ? arg.eltIdx : arg; let row; if (eltIdx == -1) { @@ -121,12 +121,12 @@ var messageHandlers = { ack("click"); }, - addInputValueToFormHistory: function() { + addInputValueToFormHistory() { gController.addInputValueToFormHistory(); ack("addInputValueToFormHistory"); }, - addDuplicateOneOff: function() { + addDuplicateOneOff() { let btn = gController._oneOffButtons[gController._oneOffButtons.length - 1]; let newBtn = btn.cloneNode(true); btn.parentNode.appendChild(newBtn); @@ -134,12 +134,12 @@ var messageHandlers = { ack("addDuplicateOneOff"); }, - removeLastOneOff: function() { + removeLastOneOff() { gController._oneOffButtons.pop().remove(); ack("removeLastOneOff"); }, - reset: function() { + reset() { // Reset both the input and suggestions by select all + delete. If there was // no text entered, this won't have any effect, so also escape to ensure the // suggestions table is closed. diff --git a/browser/base/content/test/general/head.js b/browser/base/content/test/general/head.js index 7becbbf91ceb..3bdd3f6fb710 100644 --- a/browser/base/content/test/general/head.js +++ b/browser/base/content/test/general/head.js @@ -307,9 +307,9 @@ function waitForAsyncUpdates(aCallback, aScope, aArguments) { let commit = db.createAsyncStatement("COMMIT"); commit.executeAsync({ - handleResult: function() {}, - handleError: function() {}, - handleCompletion: function(aReason) { + handleResult() {}, + handleError() {}, + handleCompletion(aReason) { aCallback.apply(scope, args); } }); @@ -418,7 +418,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows } let progressListener = { - onStateChange: function(webProgress, req, flags, status) { + onStateChange(webProgress, req, flags, status) { dump("waitForDocLoadAndStopIt: onStateChange " + flags.toString(16) + ": " + req.name + "\n"); if (webProgress.isTopLevel && @@ -470,7 +470,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows function waitForDocLoadComplete(aBrowser = gBrowser) { return new Promise(resolve => { let listener = { - onStateChange: function(webProgress, req, flags, status) { + onStateChange(webProgress, req, flags, status) { let docStop = Ci.nsIWebProgressListener.STATE_IS_NETWORK | Ci.nsIWebProgressListener.STATE_STOP; info("Saw state " + flags.toString(16) + " and status " + status.toString(16)); @@ -918,12 +918,12 @@ function promiseNewSearchEngine(basename) { info("Waiting for engine to be added: " + basename); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => Services.search.removeEngine(engine)); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { Assert.ok(false, "addEngine failed with error code " + errCode); reject(); }, @@ -966,7 +966,7 @@ function isSecurityState(expectedState) { function promiseOnBookmarkItemAdded(aExpectedURI) { return new Promise((resolve, reject) => { let bookmarksObserver = { - onItemAdded: function(aItemId, aFolderId, aIndex, aItemType, aURI) { + onItemAdded(aItemId, aFolderId, aIndex, aItemType, aURI) { info("Added a bookmark to " + aURI.spec); PlacesUtils.bookmarks.removeObserver(bookmarksObserver); if (aURI.equals(aExpectedURI)) { @@ -976,12 +976,12 @@ function promiseOnBookmarkItemAdded(aExpectedURI) { reject(new Error("Added an unexpected bookmark")); } }, - onBeginUpdateBatch: function() {}, - onEndUpdateBatch: function() {}, - onItemRemoved: function() {}, - onItemChanged: function() {}, - onItemVisited: function() {}, - onItemMoved: function() {}, + onBeginUpdateBatch() {}, + onEndUpdateBatch() {}, + onItemRemoved() {}, + onItemChanged() {}, + onItemVisited() {}, + onItemMoved() {}, QueryInterface: XPCOMUtils.generateQI([ Ci.nsINavBookmarkObserver, ]) @@ -1006,7 +1006,7 @@ function* loadBadCertPage(url) { // When the certificate exception dialog has opened, click the button to add // an exception. let certExceptionDialogObserver = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "cert-exception-ui-ready") { Services.obs.removeObserver(this, "cert-exception-ui-ready"); let certExceptionDialog = getCertExceptionDialog(EXCEPTION_DIALOG_URI); @@ -1073,7 +1073,7 @@ function setupRemoteClientsFixture(fixture) { Object.getOwnPropertyDescriptor(gFxAccounts, "remoteClients").get; Object.defineProperty(gFxAccounts, "remoteClients", { - get: function() { return fixture; } + get() { return fixture; } }); return oldRemoteClientsGetter; } diff --git a/browser/base/content/test/general/offlineByDefault.js b/browser/base/content/test/general/offlineByDefault.js index 72f7e52a01bc..fe6418f84f25 100644 --- a/browser/base/content/test/general/offlineByDefault.js +++ b/browser/base/content/test/general/offlineByDefault.js @@ -1,7 +1,7 @@ var offlineByDefault = { defaultValue: false, prefBranch: SpecialPowers.Cc["@mozilla.org/preferences-service;1"].getService(SpecialPowers.Ci.nsIPrefBranch), - set: function(allow) { + set(allow) { try { this.defaultValue = this.prefBranch.getBoolPref("offline-apps.allow_by_default"); } catch (e) { @@ -9,7 +9,7 @@ var offlineByDefault = { } this.prefBranch.setBoolPref("offline-apps.allow_by_default", allow); }, - reset: function() { + reset() { this.prefBranch.setBoolPref("offline-apps.allow_by_default", this.defaultValue); } } diff --git a/browser/base/content/test/general/parsingTestHelpers.jsm b/browser/base/content/test/general/parsingTestHelpers.jsm index 69c764483ec8..fc8b620300a9 100644 --- a/browser/base/content/test/general/parsingTestHelpers.jsm +++ b/browser/base/content/test/general/parsingTestHelpers.jsm @@ -86,7 +86,7 @@ function iterateOverPath(path, extensions) { try { // Iterate through the directory yield iterator.forEach(pathEntryIterator); - resolve({files: files, subdirs: subdirs}); + resolve({files, subdirs}); } catch (ex) { reject(ex); } finally { diff --git a/browser/base/content/test/newtab/browser_newtab_bug722273.js b/browser/base/content/test/newtab/browser_newtab_bug722273.js index 9a61a09f6491..1a6c9a401756 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug722273.js +++ b/browser/base/content/test/newtab/browser_newtab_bug722273.js @@ -38,13 +38,13 @@ function promiseAddFakeVisits() { let place = { uri: makeURI(URL), title: "fake site", - visits: visits + visits }; return new Promise((resolve, reject) => { PlacesUtils.asyncHistory.updatePlaces(place, { handleError: () => reject(new Error("Couldn't add visit")), - handleResult: function() {}, - handleCompletion: function() { + handleResult() {}, + handleCompletion() { NewTabUtils.links.populateCache(function() { NewTabUtils.allPages.update(); resolve(); diff --git a/browser/base/content/test/newtab/browser_newtab_bug725996.js b/browser/base/content/test/newtab/browser_newtab_bug725996.js index e0de809c8f86..253ef4bddc08 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug725996.js +++ b/browser/base/content/test/newtab/browser_newtab_bug725996.js @@ -9,7 +9,7 @@ add_task(function* () { yield* checkGrid("0,1,2,3,4,5,6,7,8"); function doDrop(data) { - return ContentTask.spawn(gBrowser.selectedBrowser, { data: data }, function*(args) { + return ContentTask.spawn(gBrowser.selectedBrowser, { data }, function*(args) { let dataTransfer = new content.DataTransfer("dragstart", false); dataTransfer.mozSetDataAt("text/x-moz-url", args.data, 0); let event = content.document.createEvent("DragEvent"); diff --git a/browser/base/content/test/newtab/browser_newtab_bug991210.js b/browser/base/content/test/newtab/browser_newtab_bug991210.js index f51360563964..6e0d0fe73c12 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug991210.js +++ b/browser/base/content/test/newtab/browser_newtab_bug991210.js @@ -7,10 +7,10 @@ add_task(function* () { // add a test provider that waits for load let afterLoadProvider = { - getLinks: function(callback) { + getLinks(callback) { this.callback = callback; }, - addObserver: function() {}, + addObserver() {}, }; NewTabUtils.links.addProvider(afterLoadProvider); diff --git a/browser/base/content/test/newtab/browser_newtab_drag_drop.js b/browser/base/content/test/newtab/browser_newtab_drag_drop.js index da9d89de7459..bb38b8e82be3 100644 --- a/browser/base/content/test/newtab/browser_newtab_drag_drop.js +++ b/browser/base/content/test/newtab/browser_newtab_drag_drop.js @@ -76,7 +76,7 @@ add_task(function* () { function doDragEvent(sourceIndex, dropIndex) { return ContentTask.spawn(gBrowser.selectedBrowser, - { sourceIndex: sourceIndex, dropIndex: dropIndex }, function*(args) { + { sourceIndex, dropIndex }, function*(args) { let dataTransfer = new content.DataTransfer("dragstart", false); let event = content.document.createEvent("DragEvent"); event.initDragEvent("dragstart", true, true, content, 0, 0, 0, 0, 0, diff --git a/browser/base/content/test/newtab/browser_newtab_search.js b/browser/base/content/test/newtab/browser_newtab_search.js index 17f98bb71e3c..06339b52bed6 100644 --- a/browser/base/content/test/newtab/browser_newtab_search.js +++ b/browser/base/content/test/newtab/browser_newtab_search.js @@ -211,12 +211,12 @@ function promiseNewSearchEngine({name: basename, numLogos}) { let addEnginePromise = new Promise((resolve, reject) => { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); gNewEngines.push(engine); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/newtab/head.js b/browser/base/content/test/newtab/head.js index ab72161c5362..0c0ff02c1a0b 100644 --- a/browser/base/content/test/newtab/head.js +++ b/browser/base/content/test/newtab/head.js @@ -220,8 +220,8 @@ function fillHistory(aLinks) { PlacesUtils.asyncHistory.updatePlaces(place, { handleError: () => ok(false, "couldn't add visit to history"), - handleResult: function() {}, - handleCompletion: function() { + handleResult() {}, + handleCompletion() { if (--numLinks == 0) { resolve(); } diff --git a/browser/base/content/test/plugins/blocklist_proxy.js b/browser/base/content/test/plugins/blocklist_proxy.js index d0aa0e8e48e6..4eb281e03f13 100644 --- a/browser/base/content/test/plugins/blocklist_proxy.js +++ b/browser/base/content/test/plugins/blocklist_proxy.js @@ -19,7 +19,7 @@ var BlocklistProxy = { Ci.nsIBlocklistService, Ci.nsITimerCallback]), - init: function() { + init() { if (!this._uuid) { this._uuid = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator) @@ -30,7 +30,7 @@ var BlocklistProxy = { } }, - uninit: function() { + uninit() { if (this._uuid) { Cm.nsIComponentRegistrar.unregisterFactory(this._uuid, this); Cm.nsIComponentRegistrar.registerFactory(Components.ID(kBlocklistServiceUUID), @@ -41,33 +41,33 @@ var BlocklistProxy = { } }, - notify: function(aTimer) { + notify(aTimer) { }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { }, - isAddonBlocklisted: function(aAddon, aAppVersion, aToolkitVersion) { + isAddonBlocklisted(aAddon, aAppVersion, aToolkitVersion) { return false; }, - getAddonBlocklistState: function(aAddon, aAppVersion, aToolkitVersion) { + getAddonBlocklistState(aAddon, aAppVersion, aToolkitVersion) { return 0; // STATE_NOT_BLOCKED }, - getPluginBlocklistState: function(aPluginTag, aAppVersion, aToolkitVersion) { + getPluginBlocklistState(aPluginTag, aAppVersion, aToolkitVersion) { return 0; // STATE_NOT_BLOCKED }, - getAddonBlocklistURL: function(aAddon, aAppVersion, aToolkitVersion) { + getAddonBlocklistURL(aAddon, aAppVersion, aToolkitVersion) { return ""; }, - getPluginBlocklistURL: function(aPluginTag) { + getPluginBlocklistURL(aPluginTag) { return ""; }, - getPluginInfoURL: function(aPluginTag) { + getPluginInfoURL(aPluginTag) { return ""; }, } diff --git a/browser/base/content/test/plugins/browser_bug797677.js b/browser/base/content/test/plugins/browser_bug797677.js index f1bd15b7716f..dd972c91e623 100644 --- a/browser/base/content/test/plugins/browser_bug797677.js +++ b/browser/base/content/test/plugins/browser_bug797677.js @@ -22,7 +22,7 @@ add_task(function* () { let consoleService = Cc["@mozilla.org/consoleservice;1"] .getService(Ci.nsIConsoleService); let errorListener = { - observe: function(aMessage) { + observe(aMessage) { if (aMessage.message.includes("NS_ERROR_FAILURE")) gConsoleErrors++; } diff --git a/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js b/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js index c834b17215bc..31e741eb3205 100644 --- a/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js +++ b/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js @@ -68,7 +68,7 @@ function preparePlugin(browser, pluginFallbackState) { // Somehow, I'm able to get away with overriding the getter for // this XPCOM object. Probably because I've got chrome privledges. Object.defineProperty(plugin, "pluginFallbackType", { - get: function() { + get() { return contentPluginFallbackState; } }); @@ -162,7 +162,7 @@ add_task(function* testChromeHearsPluginCrashFirst() { // actually crashing the plugin again. We hack around this by overriding // the pluginFallbackType again. Object.defineProperty(plugin, "pluginFallbackType", { - get: function() { + get() { return Ci.nsIObjectLoadingContent.PLUGIN_CRASHED; }, }); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification.js b/browser/base/content/test/popupNotifications/browser_popupNotification.js index 860179d68463..044a58939f86 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification.js @@ -17,37 +17,37 @@ function test() { var tests = [ { id: "Test#1", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.mainActionClicked, "mainAction was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.secondaryActionClicked, "secondaryAction was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2b", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions.push({ label: "Extra Secondary Action", @@ -56,18 +56,18 @@ var tests = [ }); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 1); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.extraSecondaryActionClicked, "extra secondary action was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2c", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions.push({ label: "Extra Secondary Action", @@ -80,26 +80,26 @@ var tests = [ }); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 2); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.extraSecondaryActionClicked, "extra secondary action was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#3", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -108,7 +108,7 @@ var tests = [ // test opening a notification for a background browser // Note: test 4 to 6 share a tab. { id: "Test#4", - run: function* () { + *run() { let tab = gBrowser.addTab("http://example.com/"); yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); isnot(gBrowser.selectedTab, tab, "new tab isn't selected"); @@ -125,18 +125,18 @@ var tests = [ }, // now select that browser and test to see that the notification appeared { id: "Test#5", - run: function() { + run() { this.oldSelectedTab = gBrowser.selectedTab; gBrowser.selectedTab = gBrowser.tabs[gBrowser.tabs.length - 1]; }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, wrongBrowserNotificationObject); is(PopupNotifications.isPanelOpen, true, "isPanelOpen getter doesn't lie"); // switch back to the old browser gBrowser.selectedTab = this.oldSelectedTab; }, - onHidden: function(popup) { + onHidden(popup) { // actually remove the notification to prevent it from reappearing ok(wrongBrowserNotificationObject.dismissalCallbackTriggered, "dismissal callback triggered due to tab switch"); wrongBrowserNotification.remove(); @@ -146,7 +146,7 @@ var tests = [ }, // test that the removed notification isn't shown on browser re-select { id: "Test#6", - run: function* () { + *run() { let promiseTopic = promiseTopicObserved("PopupNotifications-updateNotShowing"); gBrowser.selectedTab = gBrowser.tabs[gBrowser.tabs.length - 1]; yield promiseTopic; @@ -158,24 +158,24 @@ var tests = [ // Test that two notifications with the same ID result in a single displayed // notification. { id: "Test#7", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); // Show the same notification twice this.notification1 = showNotification(this.notifyObj); this.notification2 = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); this.notification2.remove(); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, // Test that two notifications with different IDs are displayed { id: "Test#8", - run: function() { + run() { this.testNotif1 = new BasicNotification(this.id); this.testNotif1.message += " 1"; showNotification(this.testNotif1); @@ -184,7 +184,7 @@ var tests = [ this.testNotif2.id += "-2"; showNotification(this.testNotif2); }, - onShown: function(popup) { + onShown(popup) { is(popup.childNodes.length, 2, "two notifications are shown"); // Trigger the main command for the first notification, and the secondary // for the second. Need to do mainCommand first since the secondaryCommand @@ -193,7 +193,7 @@ var tests = [ is(popup.childNodes.length, 1, "only one notification left"); triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.testNotif1.mainActionClicked, "main action #1 was clicked"); ok(!this.testNotif1.secondaryActionClicked, "secondary action #1 wasn't clicked"); ok(!this.testNotif1.dismissalCallbackTriggered, "dismissal callback #1 wasn't called"); @@ -206,16 +206,16 @@ var tests = [ // Test notification without mainAction or secondaryActions, it should fall back // to a default button that dismisses the notification in place of the main action. { id: "Test#9", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction = null; this.notifyObj.secondaryActions = null; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -225,17 +225,17 @@ var tests = [ // to a default button that dismisses the notification in place of the main action // and ignore the passed secondaryActions. { id: "Test#10", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction = null; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { let notification = popup.childNodes[0]; is(notification.getAttribute("secondarybuttonhidden"), "true", "secondary button is hidden"); triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -243,7 +243,7 @@ var tests = [ }, // Test two notifications with different anchors { id: "Test#11", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.firstNotification = showNotification(this.notifyObj); this.notifyObj2 = new BasicNotification(this.id); @@ -252,14 +252,14 @@ var tests = [ // Second showNotification() overrides the first this.secondNotification = showNotification(this.notifyObj2); }, - onShown: function(popup) { + onShown(popup) { // This also checks that only one element is shown. checkPopup(popup, this.notifyObj2); is(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor shouldn't be visible"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { // Remove the notifications this.firstNotification.remove(); this.secondNotification.remove(); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_2.js b/browser/base/content/test/popupNotifications/browser_popupNotification_2.js index 4366d7ed7b37..21df05a55c3f 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_2.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_2.js @@ -14,16 +14,16 @@ function test() { var tests = [ // Test optional params { id: "Test#1", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions = undefined; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -31,19 +31,19 @@ var tests = [ }, // Test that icons appear { id: "Test#2", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.id = "geolocation"; this.notifyObj.anchorID = "geo-notification-icon"; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); isnot(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor should be visible"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { let icon = document.getElementById("geo-notification-icon"); isnot(icon.boxObject.width, 0, "geo anchor should be visible after dismissal"); @@ -55,7 +55,7 @@ var tests = [ // Test that persistence allows the notification to persist across reloads { id: "Test#3", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -64,7 +64,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); @@ -72,7 +72,7 @@ var tests = [ this.complete = true; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.complete, "Should only have hidden the notification after 3 page loads"); ok(this.notifyObj.removedCallbackTriggered, "removal callback triggered"); gBrowser.removeTab(gBrowser.selectedTab); @@ -81,7 +81,7 @@ var tests = [ }, // Test that a timeout allows the notification to persist across reloads { id: "Test#4", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -91,7 +91,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); @@ -100,7 +100,7 @@ var tests = [ this.complete = true; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.complete, "Should only have hidden the notification after the timeout was passed"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -110,7 +110,7 @@ var tests = [ // Test that setting persistWhileVisible allows a visible notification to // persist across location changes { id: "Test#5", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -119,7 +119,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); @@ -128,7 +128,7 @@ var tests = [ this.complete = true; dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.complete, "Should only have hidden the notification after it was dismissed"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -138,7 +138,7 @@ var tests = [ // Test that nested icon nodes correctly activate popups { id: "Test#6", - run: function() { + run() { // Add a temporary box as the anchor with a button this.box = document.createElement("box"); PopupNotifications.iconBox.appendChild(this.box); @@ -160,18 +160,18 @@ var tests = [ // amount. EventUtils.synthesizeMouse(button, 4, 4, {}); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification.remove(); this.box.parentNode.removeChild(this.box); } }, // Test that popupnotifications without popups have anchor icons shown { id: "Test#7", - run: function* () { + *run() { let notifyObj = new BasicNotification(this.id); notifyObj.anchorID = "geo-notification-icon"; notifyObj.addOptions({neverShow: true}); @@ -185,16 +185,16 @@ var tests = [ }, // Test notification close button { id: "Test#9", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; EventUtils.synthesizeMouseAtCenter(notification.closebutton, {}); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -202,17 +202,17 @@ var tests = [ }, // Test notification when chrome is hidden { id: "Test#10", - run: function() { + run() { window.locationbar.visible = false; this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); is(popup.anchorNode.className, "tabbrowser-tab", "notification anchored to tab"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js b/browser/base/content/test/popupNotifications/browser_popupNotification_3.js index 9476cc5e60ad..74a917afa9fb 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_3.js @@ -14,25 +14,25 @@ function test() { var tests = [ // Test notification is removed when dismissed if removeOnDismissal is true { id: "Test#1", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.addOptions({ removeOnDismissal: true }); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, // Test multiple notification icons are shown { id: "Test#2", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -43,7 +43,7 @@ var tests = [ this.notifyObj2.anchorID = "geo-notification-icon"; this.notification2 = showNotification(this.notifyObj2); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj2); // check notifyObj1 anchor icon is showing @@ -55,7 +55,7 @@ var tests = [ dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification1.remove(); ok(this.notifyObj1.removedCallbackTriggered, "removed callback triggered"); @@ -65,7 +65,7 @@ var tests = [ }, // Test that multiple notification icons are removed when switching tabs { id: "Test#3", - run: function* () { + *run() { // show the notification on old tab. this.notifyObjOld = new BasicNotification(this.id); this.notifyObjOld.anchorID = "default-notification-icon"; @@ -80,7 +80,7 @@ var tests = [ this.notifyObjNew.anchorID = "geo-notification-icon"; this.notificationNew = showNotification(this.notifyObjNew); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObjNew); // check notifyObjOld anchor icon is removed @@ -92,7 +92,7 @@ var tests = [ dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notificationNew.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -102,14 +102,14 @@ var tests = [ }, // test security delay - too early { id: "Test#4", - run: function() { + run() { // Set the security delay to 100s PopupNotifications.buttonDelay = 100000; this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); @@ -119,21 +119,21 @@ var tests = [ }); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked because it was too soon"); ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); } }, // test security delay - after delay { id: "Test#5", - run: function() { + run() { // Set the security delay to 10ms PopupNotifications.buttonDelay = 10; this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); // Wait until after the delay to trigger the main action @@ -142,7 +142,7 @@ var tests = [ }, 500); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.mainActionClicked, "mainAction was clicked after the delay"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback was not triggered"); PopupNotifications.buttonDelay = PREF_SECURITY_DELAY_INITIAL; @@ -150,7 +150,7 @@ var tests = [ }, // reload removes notification { id: "Test#6", - run: function* () { + *run() { yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); let notifyObj = new BasicNotification(this.id); notifyObj.options.eventCallback = function(eventName) { @@ -167,7 +167,7 @@ var tests = [ }, // location change in background tab removes notification { id: "Test#7", - run: function* () { + *run() { let oldSelectedTab = gBrowser.selectedTab; let newTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); gBrowser.selectedTab = oldSelectedTab; @@ -192,7 +192,7 @@ var tests = [ }, // Popup notification anchor shouldn't disappear when a notification with the same ID is re-added in a background tab { id: "Test#8", - run: function* () { + *run() { yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); let originalTab = gBrowser.selectedTab; let bgTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -227,7 +227,7 @@ var tests = [ }, // location change in an embedded frame should not remove a notification { id: "Test#9", - run: function* () { + *run() { yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html;charset=utf8,"); this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.eventCallback = function(eventName) { @@ -237,7 +237,7 @@ var tests = [ }; showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { let self = this; let progressListener = { onLocationChange: function onLocationChange() { @@ -259,11 +259,11 @@ var tests = [ content.document.getElementById("iframe") .setAttribute("src", "http://example.org/"); }, - onHidden: function() {} + onHidden() {} }, // Popup Notifications should catch exceptions from callbacks { id: "Test#10", - run: function() { + run() { this.testNotif1 = new BasicNotification(this.id); this.testNotif1.message += " 1"; this.notification1 = showNotification(this.testNotif1); @@ -285,11 +285,11 @@ var tests = [ }; this.notification2 = showNotification(this.testNotif2); }, - onShown: function(popup) { + onShown(popup) { is(popup.childNodes.length, 2, "two notifications are shown"); dismissNotification(popup); }, - onHidden: function() { + onHidden() { this.notification1.remove(); this.notification2.remove(); } diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_4.js b/browser/base/content/test/popupNotifications/browser_popupNotification_4.js index 466670cf1d33..4780d52afcb3 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_4.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_4.js @@ -14,41 +14,41 @@ function test() { var tests = [ // Popup Notifications main actions should catch exceptions from callbacks { id: "Test#1", - run: function() { + run() { this.testNotif = new ErrorNotification(this.id); showNotification(this.testNotif); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.testNotif); triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.testNotif.mainActionClicked, "main action has been triggered"); } }, // Popup Notifications secondary actions should catch exceptions from callbacks { id: "Test#2", - run: function() { + run() { this.testNotif = new ErrorNotification(this.id); showNotification(this.testNotif); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.testNotif); triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.testNotif.secondaryActionClicked, "secondary action has been triggered"); } }, // Existing popup notification shouldn't disappear when adding a dismissed notification { id: "Test#3", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; this.notification1 = showNotification(this.notifyObj1); }, - onShown: function(popup) { + onShown(popup) { // Now show a dismissed notification, and check that it doesn't clobber // the showing one. this.notifyObj2 = new BasicNotification(this.id); @@ -67,14 +67,14 @@ var tests = [ dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification1.remove(); this.notification2.remove(); } }, // Showing should be able to modify the popup data { id: "Test#4", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); let normalCallback = this.notifyObj.options.eventCallback; this.notifyObj.options.eventCallback = function(eventName) { @@ -85,18 +85,18 @@ var tests = [ }; showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { // checkPopup checks for the matching label. Note that this assumes that // this.notifyObj.mainAction is the same as notification.mainAction, // which could be a problem if we ever decided to deep-copy. checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden: function() { } + onHidden() { } }, // Moving a tab to a new window should remove non-swappable notifications. { id: "Test#5", - run: function* () { + *run() { yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); let notifyObj = new BasicNotification(this.id); @@ -124,7 +124,7 @@ var tests = [ }, // Moving a tab to a new window should preserve swappable notifications. { id: "Test#6", - run: function* () { + *run() { yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); let notifyObj = new BasicNotification(this.id); let originalCallback = notifyObj.options.eventCallback; @@ -165,16 +165,16 @@ var tests = [ }, // the main action callback can keep the notification. { id: "Test#8", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction.dismiss = true; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); ok(!this.notifyObj.removedCallbackTriggered, "removed callback wasn't triggered"); this.notification.remove(); @@ -182,16 +182,16 @@ var tests = [ }, // a secondary action callback can keep the notification. { id: "Test#9", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions[0].dismiss = true; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); ok(!this.notifyObj.removedCallbackTriggered, "removed callback wasn't triggered"); this.notification.remove(); @@ -199,7 +199,7 @@ var tests = [ }, // returning true in the showing callback should dismiss the notification. { id: "Test#10", - run: function() { + run() { let notifyObj = new BasicNotification(this.id); let originalCallback = notifyObj.options.eventCallback; notifyObj.options.eventCallback = function(eventName) { diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_5.js b/browser/base/content/test/popupNotifications/browser_popupNotification_5.js index 99cb6b824447..83c0aebe6e02 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_5.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_5.js @@ -16,11 +16,11 @@ var gNotification; var tests = [ // panel updates should fire the showing and shown callbacks again. { id: "Test#1", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); this.notifyObj.showingCallbackTriggered = false; @@ -35,11 +35,11 @@ var tests = [ this.notification.remove(); }, - onHidden: function() { } + onHidden() { } }, // A first dismissed notification shouldn't stop _update from showing a second notification { id: "Test#2", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -55,16 +55,16 @@ var tests = [ this.notification2.dismissed = false; PopupNotifications._update(); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj2); this.notification1.remove(); this.notification2.remove(); }, - onHidden: function(popup) { } + onHidden(popup) { } }, // The anchor icon should be shown for notifications in background windows. { id: "Test#3", - run: function* () { + *run() { let notifyObj = new BasicNotification(this.id); notifyObj.options.dismissed = true; @@ -84,7 +84,7 @@ var tests = [ // Test that persistent doesn't allow the notification to persist after // navigation. { id: "Test#4", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -93,7 +93,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); @@ -105,7 +105,7 @@ var tests = [ this.complete = true; triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.complete, "Should have hidden the notification after navigation"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -115,7 +115,7 @@ var tests = [ // Test that persistent allows the notification to persist until explicitly // dismissed. { id: "Test#5", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -124,7 +124,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; // Notification should persist after attempt to dismiss by clicking on the @@ -136,7 +136,7 @@ var tests = [ this.complete = true; triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.complete, "Should have hidden the notification after clicking Not Now"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -146,16 +146,16 @@ var tests = [ // Test that persistent panels are still open after switching to another tab // and back. { id: "Test#6a", - run: function* () { + *run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.persistent = true; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); }, - onHidden: function(popup) { + onHidden(popup) { ok(true, "Should have hidden the notification after tab switch"); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -164,7 +164,7 @@ var tests = [ // Second part of the previous test that compensates for the limitation in // runNextTest that expects a single onShown/onHidden invocation per test. { id: "Test#6b", - run: function* () { + *run() { let id = PopupNotifications.panel.firstChild.getAttribute("popupid"); ok(id.endsWith("Test#6a"), "Should have found the notification from Test6a"); ok(PopupNotifications.isPanelOpen, "Should have shown the popup again after getting back to the tab"); @@ -176,7 +176,7 @@ var tests = [ // Test that persistent panels are still open after switching to another // window and back. { id: "Test#7", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -213,7 +213,7 @@ var tests = [ }, // Test that only the first persistent notification is shown on update { id: "Test#8", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -228,16 +228,16 @@ var tests = [ PopupNotifications._update(); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj1); this.notification1.remove(); this.notification2.remove(); }, - onHidden: function(popup) { } + onHidden(popup) { } }, // Test that persistent notifications are shown stacked by anchor on update { id: "Test#9", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -258,7 +258,7 @@ var tests = [ PopupNotifications._update(); }, - onShown: function(popup) { + onShown(popup) { let notifications = popup.childNodes; is(notifications.length, 2, "two notifications displayed"); let [notification1, notification2] = notifications; @@ -269,6 +269,6 @@ var tests = [ this.notification2.remove(); this.notification3.remove(); }, - onHidden: function(popup) { } + onHidden(popup) { } }, ]; diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js b/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js index 0516164d8236..41b55db04b2a 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js @@ -37,25 +37,25 @@ var gNotification; var tests = [ // Test that passing the checkbox field shows the checkbox. { id: "show_checkbox", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", }; gNotification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; checkCheckbox(notification.checkbox, "This is a checkbox"); triggerMainCommand(popup); }, - onHidden: function() { } + onHidden() { } }, // Test checkbox being checked by default { id: "checkbox_checked", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "Check this", @@ -63,18 +63,18 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; checkCheckbox(notification.checkbox, "Check this", true); triggerMainCommand(popup); }, - onHidden: function() { } + onHidden() { } }, // Test checkbox passing the checkbox state on mainAction { id: "checkbox_passCheckboxChecked_mainAction", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction.callback = ({checkboxChecked}) => this.mainActionChecked = checkboxChecked; this.notifyObj.options.checkbox = { @@ -82,7 +82,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -92,14 +92,14 @@ var tests = [ checkCheckbox(checkbox, "This is a checkbox", true); triggerMainCommand(popup); }, - onHidden: function() { + onHidden() { is(this.mainActionChecked, true, "mainAction callback is passed the correct checkbox value"); } }, // Test checkbox passing the checkbox state on secondaryAction { id: "checkbox_passCheckboxChecked_secondaryAction", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions = [{ label: "Test Secondary", @@ -111,7 +111,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -121,14 +121,14 @@ var tests = [ checkCheckbox(checkbox, "This is a checkbox", true); triggerSecondaryCommand(popup, 0); }, - onHidden: function() { + onHidden() { is(this.secondaryActionChecked, true, "secondaryAction callback is passed the correct checkbox value"); } }, // Test checkbox preserving its state through re-opening the doorhanger { id: "checkbox_reopen", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", @@ -139,7 +139,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -148,7 +148,7 @@ var tests = [ EventUtils.synthesizeMouseAtCenter(checkbox, {}); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { let icon = document.getElementById("default-notification-icon"); EventUtils.synthesizeMouseAtCenter(icon, {}); let notification = popup.childNodes[0]; @@ -165,11 +165,11 @@ var tests = [ [true, false].forEach(function(checked) { tests.push( { id: `checkbox_disableMainAction_${state}_${checked ? 'checked' : 'unchecked'}`, - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", - checked: checked, + checked, [state]: { disableMainAction: true, warningLabel: "Testing disable", @@ -177,7 +177,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -200,7 +200,7 @@ var tests = [ } triggerMainCommand(popup); }, - onHidden: function() { } + onHidden() { } } ); }); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js b/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js index 1065ac6aacef..30ce48bddead 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js @@ -15,7 +15,7 @@ var tests = [ // Test that popupnotifications are anchored to the identity icon on // about:blank, where anchor icons are hidden. { id: "Test#1", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"); @@ -23,7 +23,7 @@ var tests = [ this.notifyObj.anchorID = "geo-notification-icon"; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); is(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor shouldn't be visible"); @@ -31,7 +31,7 @@ var tests = [ "notification anchored to identity icon"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -40,7 +40,7 @@ var tests = [ // Test that popupnotifications are anchored to the identity icon after // navigation to about:blank. { id: "Test#2", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -51,7 +51,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { yield promiseTabLoadEvent(gBrowser.selectedTab, "about:blank"); checkPopup(popup, this.notifyObj); @@ -61,7 +61,7 @@ var tests = [ "notification anchored to identity icon"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -70,7 +70,7 @@ var tests = [ // Test that dismissed popupnotifications cannot be opened on about:blank, but // can be opened after navigation. { id: "Test#3", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"); @@ -92,11 +92,11 @@ var tests = [ EventUtils.synthesizeMouse(document.getElementById("geo-notification-icon"), 0, 0, {}); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -106,7 +106,7 @@ var tests = [ // editing the URL in the location bar, and restored to their anchors when the // URL is reverted. { id: "Test#4", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); diff --git a/browser/base/content/test/social/browser_aboutHome_activation.js b/browser/base/content/test/social/browser_aboutHome_activation.js index 9b3d599ba0eb..5d7dada0f9bc 100644 --- a/browser/base/content/test/social/browser_aboutHome_activation.js +++ b/browser/base/content/test/social/browser_aboutHome_activation.js @@ -57,7 +57,7 @@ var gTests = [ { desc: "Test activation with enable panel", - snippet: snippet, + snippet, panel: true }, diff --git a/browser/base/content/test/social/browser_addons.js b/browser/base/content/test/social/browser_addons.js index c57314282013..c5bf44dd6c1b 100644 --- a/browser/base/content/test/social/browser_addons.js +++ b/browser/base/content/test/social/browser_addons.js @@ -57,26 +57,26 @@ function installListener(next, aManifest) { }); return { - onInstalling: function(addon) { + onInstalling(addon) { is(expectEvent, "onInstalling", "install started"); is(addon.manifest.origin, aManifest.origin, "provider about to be installed"); ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs"); expectEvent = "onInstalled"; }, - onInstalled: function(addon) { + onInstalled(addon) { is(addon.manifest.origin, aManifest.origin, "provider installed"); ok(addon.installDate.getTime() > 0, "addon has installDate"); ok(addon.updateDate.getTime() > 0, "addon has updateDate"); ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs"); expectEvent = "onUninstalling"; }, - onUninstalling: function(addon) { + onUninstalling(addon) { is(expectEvent, "onUninstalling", "uninstall started"); is(addon.manifest.origin, aManifest.origin, "provider about to be uninstalled"); ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs"); expectEvent = "onUninstalled"; }, - onUninstalled: function(addon) { + onUninstalled(addon) { is(expectEvent, "onUninstalled", "provider has been uninstalled"); is(addon.manifest.origin, aManifest.origin, "provider uninstalled"); ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs"); @@ -86,25 +86,25 @@ function installListener(next, aManifest) { } var tests = { - testHTTPInstallFailure: function(next) { + testHTTPInstallFailure(next) { let installFrom = "http://example.com"; is(SocialService.getOriginActivationType(installFrom), "foreign", "testing foriegn install"); let data = { origin: installFrom, url: installFrom + "/activate", - manifest: manifest, - window: window + manifest, + window } Social.installProvider(data, function(addonManifest) { ok(!addonManifest, "unable to install provider over http"); next(); }); }, - testAddonEnableToggle: function(next) { + testAddonEnableToggle(next) { let expectEvent; let prefname = getManifestPrefname(manifest); let listener = { - onEnabled: function(addon) { + onEnabled(addon) { is(expectEvent, "onEnabled", "provider onEnabled"); ok(!addon.userDisabled, "provider enabled"); executeSoon(function() { @@ -112,11 +112,11 @@ var tests = { addon.userDisabled = true; }); }, - onEnabling: function(addon) { + onEnabling(addon) { is(expectEvent, "onEnabling", "provider onEnabling"); expectEvent = "onEnabled"; }, - onDisabled: function(addon) { + onDisabled(addon) { is(expectEvent, "onDisabled", "provider onDisabled"); ok(addon.userDisabled, "provider disabled"); AddonManager.removeAddonListener(listener); @@ -124,7 +124,7 @@ var tests = { Services.prefs.clearUserPref(prefname); executeSoon(next); }, - onDisabling: function(addon) { + onDisabling(addon) { is(expectEvent, "onDisabling", "provider onDisabling"); expectEvent = "onDisabled"; } @@ -148,7 +148,7 @@ var tests = { next(); }); }, - testProviderEnableToggle: function(next) { + testProviderEnableToggle(next) { // enable and disabel a provider from the SocialService interface, check // that the addon manager is updated @@ -156,22 +156,22 @@ var tests = { let prefname = getManifestPrefname(manifest); let listener = { - onEnabled: function(addon) { + onEnabled(addon) { is(expectEvent, "onEnabled", "provider onEnabled"); is(addon.manifest.origin, manifest.origin, "provider enabled"); ok(!addon.userDisabled, "provider !userDisabled"); }, - onEnabling: function(addon) { + onEnabling(addon) { is(expectEvent, "onEnabling", "provider onEnabling"); is(addon.manifest.origin, manifest.origin, "provider about to be enabled"); expectEvent = "onEnabled"; }, - onDisabled: function(addon) { + onDisabled(addon) { is(expectEvent, "onDisabled", "provider onDisabled"); is(addon.manifest.origin, manifest.origin, "provider disabled"); ok(addon.userDisabled, "provider userDisabled"); }, - onDisabling: function(addon) { + onDisabling(addon) { is(expectEvent, "onDisabling", "provider onDisabling"); is(addon.manifest.origin, manifest.origin, "provider about to be disabled"); expectEvent = "onDisabled"; @@ -190,7 +190,7 @@ var tests = { }); }); }, - testDirectoryInstall: function(next) { + testDirectoryInstall(next) { AddonManager.addAddonListener(installListener(next, manifest2)); BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown").then(() => { @@ -205,7 +205,7 @@ var tests = { origin: manifest2.origin, url: manifest2.origin + "/directory", manifest: manifest2, - window: window + window } Social.installProvider(data, function(addonManifest) { Services.prefs.clearUserPref("social.directories"); diff --git a/browser/base/content/test/social/browser_blocklist.js b/browser/base/content/test/social/browser_blocklist.js index 074583498fc6..9a340b633738 100644 --- a/browser/base/content/test/social/browser_blocklist.js +++ b/browser/base/content/test/social/browser_blocklist.js @@ -66,7 +66,7 @@ function test() { } var tests = { - testSimpleBlocklist: function(next) { + testSimpleBlocklist(next) { // this really just tests adding and clearing our blocklist for later tests setAndUpdateBlocklist(blocklistURL).then(() => { ok(Services.blocklist.isAddonBlocklisted(SocialService.createWrapper(manifest_bad)), "blocking 'blocked'"); @@ -77,7 +77,7 @@ var tests = { }); }); }, - testAddingNonBlockedProvider: function(next) { + testAddingNonBlockedProvider(next) { function finishTest(isgood) { ok(isgood, "adding non-blocked provider ok"); Services.prefs.clearUserPref("social.manifest.good"); @@ -103,7 +103,7 @@ var tests = { } }); }, - testAddingBlockedProvider: function(next) { + testAddingBlockedProvider(next) { function finishTest(good) { ok(good, "Unable to add blocklisted provider"); Services.prefs.clearUserPref("social.manifest.blocked"); @@ -124,7 +124,7 @@ var tests = { } }); }, - testInstallingBlockedProvider: function(next) { + testInstallingBlockedProvider(next) { function finishTest(good) { ok(good, "Unable to install blocklisted provider"); resetBlocklist().then(next); @@ -138,7 +138,7 @@ var tests = { origin: manifest_bad.origin, url: activationURL, manifest: manifest_bad, - window: window + window } Social.installProvider(data, function(addonManifest) { finishTest(false); @@ -148,10 +148,10 @@ var tests = { } }); }, - testBlockingExistingProvider: function(next) { + testBlockingExistingProvider(next) { let listener = { _window: null, - onOpenWindow: function(aXULWindow) { + onOpenWindow(aXULWindow) { Services.wm.removeListener(this); this._window = aXULWindow; let domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -177,8 +177,8 @@ var tests = { }); }, false); }, - onCloseWindow: function(aXULWindow) { }, - onWindowTitleChange: function(aXULWindow, aNewTitle) { } + onCloseWindow(aXULWindow) { }, + onWindowTitleChange(aXULWindow, aNewTitle) { } }; Services.wm.addListener(listener); diff --git a/browser/base/content/test/social/browser_share.js b/browser/base/content/test/social/browser_share.js index 91de49b16857..74414b7dd86e 100644 --- a/browser/base/content/test/social/browser_share.js +++ b/browser/base/content/test/social/browser_share.js @@ -135,7 +135,7 @@ function hasoptions(testOptions, options) { } var tests = { - testShareDisabledOnActivation: function(next) { + testShareDisabledOnActivation(next) { // starting on about:blank page, share should be visible but disabled when // adding provider is(gBrowser.currentURI.spec, "about:blank"); @@ -157,7 +157,7 @@ var tests = { SocialService.disableProvider(manifest.origin, next); }); }, - testShareEnabledOnActivation: function(next) { + testShareEnabledOnActivation(next) { // starting from *some* page, share should be visible and enabled when // activating provider // initialize the button into the navbar @@ -180,7 +180,7 @@ var tests = { }); }); }, - testSharePage: function(next) { + testSharePage(next) { let testTab; let testIndex = 0; let testData = corpus[testIndex++]; @@ -222,7 +222,7 @@ var tests = { } executeSoon(runOneTest); }, - testShareMicroformats: function(next) { + testShareMicroformats(next) { // initialize the button into the navbar CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR); // ensure correct state @@ -305,7 +305,7 @@ var tests = { }); }); }, - testSharePanelActivation: function(next) { + testSharePanelActivation(next) { let testTab; // cleared in the cleanup function Services.prefs.setCharPref("social.directories", "https://example.com"); @@ -352,7 +352,7 @@ var tests = { SocialShare.sharePage(); }); }, - testSharePanelDialog: function(next) { + testSharePanelDialog(next) { let testTab; // initialize the button into the navbar CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR); diff --git a/browser/base/content/test/social/browser_social_activation.js b/browser/base/content/test/social/browser_social_activation.js index 02c9b924f93f..63b8b938e996 100644 --- a/browser/base/content/test/social/browser_social_activation.js +++ b/browser/base/content/test/social/browser_social_activation.js @@ -186,7 +186,7 @@ function test() { } var tests = { - testActivationWrongOrigin: function(next) { + testActivationWrongOrigin(next) { // At this stage none of our providers exist, so we expect failure. Services.prefs.setBoolPref("social.remote-install.enabled", false); activateProvider(gTestDomains[0], function() { @@ -199,7 +199,7 @@ var tests = { }); }, - testIFrameActivation: function(next) { + testIFrameActivation(next) { activateIFrameProvider(gTestDomains[0], function() { is(SocialUI.enabled, false, "SocialUI is not enabled"); let panel = document.getElementById("servicesInstall-notification"); @@ -209,7 +209,7 @@ var tests = { }); }, - testActivationFirstProvider: function(next) { + testActivationFirstProvider(next) { // first up we add a manifest entry for a single provider. activateOneProvider(gProviders[0], false, function() { // we deactivated leaving no providers left, so Social is disabled. @@ -218,7 +218,7 @@ var tests = { }); }, - testActivationMultipleProvider: function(next) { + testActivationMultipleProvider(next) { // The trick with this test is to make sure that Social.providers[1] is // the current provider when doing the undo - this makes sure that the // Social code doesn't fallback to Social.providers[0], which it will @@ -237,7 +237,7 @@ var tests = { }); }, - testAddonManagerDoubleInstall: function(next) { + testAddonManagerDoubleInstall(next) { // Create a new tab and load about:addons let addonsTab = gBrowser.addTab(); gBrowser.selectedTab = addonsTab; diff --git a/browser/base/content/test/social/social_crash_content_helper.js b/browser/base/content/test/social/social_crash_content_helper.js index 4698b6957b4f..1a876c3d6a14 100644 --- a/browser/base/content/test/social/social_crash_content_helper.js +++ b/browser/base/content/test/social/social_crash_content_helper.js @@ -14,11 +14,11 @@ var crash = function() { // this will crash when called. var TestHelper = { - init: function() { + init() { addMessageListener("social-test:crash", this); }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "social-test:crash": privateNoteIntentionalCrash(); diff --git a/browser/base/content/test/urlbar/Panel.jsm b/browser/base/content/test/urlbar/Panel.jsm index ee1fd2ed93c9..2e5eccadf5cc 100644 --- a/browser/base/content/test/urlbar/Panel.jsm +++ b/browser/base/content/test/urlbar/Panel.jsm @@ -105,8 +105,8 @@ this.Panel.prototype = { let url = controller.getValueAt(idx); let action = this.urlbar._parseActionUrl(url); this._emit("result", { - url: url, - action: action, + url, + action, image: controller.getImageAt(idx), title: controller.getCommentAt(idx), type: controller.getStyleAt(idx), diff --git a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js b/browser/base/content/test/urlbar/browser_autocomplete_no_title.js index 8d608550b313..49e8f4609c9b 100644 --- a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js +++ b/browser/base/content/test/urlbar/browser_autocomplete_no_title.js @@ -2,7 +2,7 @@ add_task(function*() { let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla"); let uri = NetUtil.newURI("http://bug1060642.example.com/beards/are/pretty/great"); - yield PlacesTestUtils.addVisits([{uri: uri, title: ""}]); + yield PlacesTestUtils.addVisits([{uri, title: ""}]); yield promiseAutocompleteResultPopup("bug1060642"); ok(gURLBar.popup.richlistbox.children.length > 1, "Should get at least 2 results"); diff --git a/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js b/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js index 8a69b4b44c54..b6440b327bc2 100644 --- a/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js +++ b/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js @@ -10,7 +10,7 @@ add_task(function*() { PlacesUtils.bookmarks.DEFAULT_INDEX, `test ${tagName}`); PlacesUtils.tagging.tagURI(uri, [tagName]); - yield PlacesTestUtils.addVisits([{uri: uri, title: `Test page with tag ${tagName}`}]); + yield PlacesTestUtils.addVisits([{uri, title: `Test page with tag ${tagName}`}]); } // We use different tags for each part of the test, as otherwise the diff --git a/browser/base/content/test/urlbar/browser_bug556061.js b/browser/base/content/test/urlbar/browser_bug556061.js index 4c6ac5bf5230..d57e92c372d1 100644 --- a/browser/base/content/test/urlbar/browser_bug556061.js +++ b/browser/base/content/test/urlbar/browser_bug556061.js @@ -28,7 +28,7 @@ function cleanup() { var tests = [ { expected: testURL, - setup: function() { + setup() { gURLBar.value = testActionURL; gURLBar.valueIsTyped = true; is(gURLBar.value, testActionURL, "gURLBar starts with the correct real value"); @@ -39,37 +39,37 @@ var tests = [ gURLBar.select(); goDoCommand("cmd_copy"); }, - success: function() { + success() { is(gURLBar.value, testActionURL, "gURLBar.value didn't change when copying"); } }, { expected: testURL.substring(0, 10), - setup: function() { + setup() { // Set selectionStart/End manually and make sure it matches the substring gURLBar.selectionStart = 0; gURLBar.selectionEnd = 10; goDoCommand("cmd_copy"); }, - success: function() { + success() { is(gURLBar.value, testActionURL, "gURLBar.value didn't change when copying"); } }, { expected: testURL, - setup: function() { + setup() { // Setup for cut test... // Select all gURLBar.select(); goDoCommand("cmd_cut"); }, - success: function() { + success() { is(gURLBar.value, "", "gURLBar.value is now empty"); } }, { expected: testURL.substring(testURL.length - 10, testURL.length), - setup: function() { + setup() { // Reset urlbar value gURLBar.value = testActionURL; gURLBar.valueIsTyped = true; @@ -82,7 +82,7 @@ var tests = [ gURLBar.selectionEnd = testURL.length; goDoCommand("cmd_cut"); }, - success: function() { + success() { is(gURLBar.value, testURL.substring(0, testURL.length - 10), "gURLBar.value has the correct value"); } } diff --git a/browser/base/content/test/urlbar/browser_bug623155.js b/browser/base/content/test/urlbar/browser_bug623155.js index dd6ff8c85399..1d355395fcec 100644 --- a/browser/base/content/test/urlbar/browser_bug623155.js +++ b/browser/base/content/test/urlbar/browser_bug623155.js @@ -58,7 +58,7 @@ function test() { } var gWebProgressListener = { - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (aIID.equals(Components.interfaces.nsIWebProgressListener) || aIID.equals(Components.interfaces.nsISupportsWeakReference) || aIID.equals(Components.interfaces.nsISupports)) @@ -75,7 +75,7 @@ var gWebProgressListener = { // onSecurityChange: function() {}, // ---------------------------------------------------------------------------- - onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { if (!aRequest) { // This is bug 673752, or maybe initial "about:blank". return; diff --git a/browser/base/content/test/urlbar/browser_search_favicon.js b/browser/base/content/test/urlbar/browser_search_favicon.js index a8e6dbbcd957..4ab7bfd6ec73 100644 --- a/browser/base/content/test/urlbar/browser_search_favicon.js +++ b/browser/base/content/test/urlbar/browser_search_favicon.js @@ -23,7 +23,7 @@ add_task(function*() { Services.search.currentEngine = gEngine; let uri = NetUtil.newURI("http://s.example.com/search?q=foo&client=1"); - yield PlacesTestUtils.addVisits({ uri: uri, title: "Foo - SearchEngine Search" }); + yield PlacesTestUtils.addVisits({ uri, title: "Foo - SearchEngine Search" }); yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla"); diff --git a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js b/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js index 6fde02895311..5b5fd3e6d1e9 100644 --- a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js +++ b/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js @@ -171,12 +171,12 @@ function checkAutocompleteResults(aExpected, aCallback) searchParam: "enable-actions", popupOpen: false, minResultsForPopup: 0, - invalidate: function() {}, + invalidate() {}, disableAutoComplete: false, completeDefaultIndex: false, get popup() { return this; }, - onSearchBegin: function() {}, - onSearchComplete: function() + onSearchBegin() {}, + onSearchComplete() { info("Found " + gController.matchCount + " matches."); // Check to see the expected uris and titles match up (in any order) @@ -202,9 +202,9 @@ function checkAutocompleteResults(aExpected, aCallback) executeSoon(aCallback); }, - setSelectedIndex: function() {}, + setSelectedIndex() {}, get searchCount() { return this.searches.length; }, - getSearchAt: function(aIndex) { return this.searches[aIndex]; }, + getSearchAt(aIndex) { return this.searches[aIndex]; }, QueryInterface: XPCOMUtils.generateQI([ Ci.nsIAutoCompleteInput, Ci.nsIAutoCompletePopup, diff --git a/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js b/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js index 05c54ba251f3..102c65efd948 100644 --- a/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js +++ b/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js @@ -184,18 +184,18 @@ function promiseMessage(type, data, numExpectedAcks = 1) { let ackMsgName = "TestMessageAck"; let msgID = gNextMessageID++; gMsgMan.sendAsyncMessage(testMsgName, { - type: type, + type, messageID: msgID, - data: data, + data, }); let ackPromises = []; for (let i = 0; i < numExpectedAcks; i++) { let ackIndex = i; ackPromises.push(new Promise(resolve => { info("Waiting for message ack: " + JSON.stringify({ - type: type, - msgID: msgID, - ackIndex: ackIndex, + type, + msgID, + ackIndex, })); gMsgMan.addMessageListener(ackMsgName, function onMsg(msg) { // Messages have IDs so that an ack can be correctly paired with the @@ -207,9 +207,9 @@ function promiseMessage(type, data, numExpectedAcks = 1) { return; } info("Received message ack: " + JSON.stringify({ - type: type, + type, msgID: msg.data.messageID, - ackIndex: ackIndex, + ackIndex, })); gMsgMan.removeMessageListener(ackMsgName, onMsg); resolve(msg.data.data); diff --git a/browser/base/content/test/urlbar/browser_urlbarCopying.js b/browser/base/content/test/urlbar/browser_urlbarCopying.js index 8c1d262d6d3b..aa7289f4c0c5 100644 --- a/browser/base/content/test/urlbar/browser_urlbarCopying.js +++ b/browser/base/content/test/urlbar/browser_urlbarCopying.js @@ -153,7 +153,7 @@ var tests = [ copyExpected: "data:text/html,(%C3%A9 %25P", }, { - setup: function() { Services.prefs.setBoolPref(decodeURLpref, true); }, + setup() { Services.prefs.setBoolPref(decodeURLpref, true); }, loadURL: "http://example.com/%D0%B1%D0%B8%D0%BE%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D1%8F", expectedURL: toUnicode("example.com/биография"), copyExpected: toUnicode("http://example.com/биография") diff --git a/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js b/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js index 8c28401eae0e..485c9ec0db05 100644 --- a/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js +++ b/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js @@ -188,7 +188,7 @@ function getActionAtIndex(index) { } let [, type, paramStr] = mozActionMatch; return { - type: type, + type, params: JSON.parse(paramStr), }; } diff --git a/browser/base/content/test/urlbar/head.js b/browser/base/content/test/urlbar/head.js index d1288a8db751..cb39ce9262c6 100644 --- a/browser/base/content/test/urlbar/head.js +++ b/browser/base/content/test/urlbar/head.js @@ -46,7 +46,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows } let progressListener = { - onStateChange: function(webProgress, req, flags, status) { + onStateChange(webProgress, req, flags, status) { dump("waitForDocLoadAndStopIt: onStateChange " + flags.toString(16) + ": " + req.name + "\n"); if (webProgress.isTopLevel && @@ -190,12 +190,12 @@ function promiseNewSearchEngine(basename) { info("Waiting for engine to be added: " + basename); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => Services.search.removeEngine(engine)); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { Assert.ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/urlbar/urlbarAddonIframe.js b/browser/base/content/test/urlbar/urlbarAddonIframe.js index d25ab0bc95c4..3f8f9a83aa78 100644 --- a/browser/base/content/test/urlbar/urlbarAddonIframe.js +++ b/browser/base/content/test/urlbar/urlbarAddonIframe.js @@ -45,7 +45,7 @@ function ack(originalEventDetail, ackData = null, ackIndex = 0) { dispatchEvent(new CustomEvent("TestEventAck", { detail: { messageID: originalEventDetail.messageID, - ackIndex: ackIndex, + ackIndex, data: ackData, }, })); diff --git a/browser/base/content/utilityOverlay.js b/browser/base/content/utilityOverlay.js index a8f5e747b2c8..ab7849e6db5c 100644 --- a/browser/base/content/utilityOverlay.js +++ b/browser/base/content/utilityOverlay.js @@ -383,7 +383,7 @@ function openLinkIn(url, where, params) { } targetBrowser.loadURIWithFlags(url, { - flags: flags, + flags, referrerURI: aNoReferrer ? null : aReferrerURI, referrerPolicy: aReferrerPolicy, postData: aPostData, diff --git a/browser/base/content/web-panels.js b/browser/base/content/web-panels.js index ceb0016fdff6..3bf8c726e6fc 100644 --- a/browser/base/content/web-panels.js +++ b/browser/base/content/web-panels.js @@ -13,12 +13,12 @@ function getPanelBrowser() } var panelProgressListener = { - onProgressChange : function(aWebProgress, aRequest, + onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { }, - onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus) + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { if (!aRequest) return; @@ -38,17 +38,17 @@ var panelProgressListener = { } , - onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { UpdateBackForwardCommands(getPanelBrowser().webNavigation); }, - onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { }, - onSecurityChange : function(aWebProgress, aRequest, aState) { + onSecurityChange(aWebProgress, aRequest, aState) { }, - QueryInterface : function(aIID) + QueryInterface(aIID) { if (aIID.equals(Ci.nsIWebProgressListener) || aIID.equals(Ci.nsISupportsWeakReference) || diff --git a/browser/base/content/webrtcIndicator.js b/browser/base/content/webrtcIndicator.js index a8bb64367c48..9b4d78066a44 100644 --- a/browser/base/content/webrtcIndicator.js +++ b/browser/base/content/webrtcIndicator.js @@ -129,7 +129,7 @@ function onFirefoxButtonClick(event) { var PositionHandler = { positionCustomized: false, threshold: 10, - adjustPosition: function() { + adjustPosition() { if (!this.positionCustomized) { // Center the window horizontally on the screen (not the available area). // Until we have moved the window to y=0, 'screen.width' may give a value @@ -150,14 +150,14 @@ var PositionHandler = { this.setXPosition(window.screenX); } }, - setXPosition: function(desiredX) { + setXPosition(desiredX) { // Ensure the indicator isn't moved outside the available area of the screen. desiredX = Math.max(desiredX, screen.availLeft); let maxX = screen.availLeft + screen.availWidth - document.documentElement.clientWidth; window.moveTo(Math.min(desiredX, maxX), screen.availTop); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "mousedown": if (aEvent.button != 0 || aEvent.defaultPrevented) diff --git a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js index 310a94166610..580d29843dc3 100644 --- a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js +++ b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js @@ -98,22 +98,22 @@ function OpenCacheEntry(key, where, flags, lci) CacheListener.prototype = { _appCache: null, - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Components.interfaces.nsICacheEntryOpenCallback) || iid.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_ERROR_NO_INTERFACE; }, - onCacheEntryCheck: function(entry, appCache) { + onCacheEntryCheck(entry, appCache) { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable: function(entry, isnew, appCache, status) { + onCacheEntryAvailable(entry, isnew, appCache, status) { resolve(); }, - run: function() { + run() { let storage = getCacheStorage(where, lci, this._appCache); storage.asyncOpenURI(key, "", flags, this); } diff --git a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js index 9875c8aa1b73..e874494ec462 100644 --- a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js +++ b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js @@ -78,7 +78,7 @@ function allRegistered() { function promiseAllRegistered() { return new Promise(function(resolve) { let listener = { - onRegister: function() { + onRegister() { if (allRegistered()) { swm.removeListener(listener); resolve(); @@ -92,11 +92,11 @@ function promiseAllRegistered() { function promiseUnregister(info) { return new Promise(function(resolve) { swm.unregister(info.principal, { - unregisterSucceeded: function(aState) { + unregisterSucceeded(aState) { ok(aState, "ServiceWorkerRegistration exists"); resolve(); }, - unregisterFailed: function(aState) { + unregisterFailed(aState) { ok(false, "unregister should succeed"); } }, info.scope); diff --git a/browser/components/customizableui/CustomizableUI.jsm b/browser/components/customizableui/CustomizableUI.jsm index a9cef9dd1a34..81f4da46b2da 100644 --- a/browser/components/customizableui/CustomizableUI.jsm +++ b/browser/components/customizableui/CustomizableUI.jsm @@ -170,7 +170,7 @@ XPCOMUtils.defineLazyGetter(this, "log", () => { }); var CustomizableUIInternal = { - initialize: function() { + initialize() { log.debug("Initializing"); this.addListener(this); @@ -323,13 +323,13 @@ var CustomizableUIInternal = { return toolbars; }, - _defineBuiltInWidgets: function() { + _defineBuiltInWidgets() { for (let widgetDefinition of CustomizableWidgets) { this.createBuiltinWidget(widgetDefinition); } }, - _introduceNewBuiltinWidgets: function() { + _introduceNewBuiltinWidgets() { // We should still enter even if gSavedState.currentVersion >= kVersion // because the per-widget pref facility is independent of versioning. if (!gSavedState) { @@ -389,7 +389,7 @@ var CustomizableUIInternal = { * _markObsoleteBuiltinButtonsSeen * when upgrading, ensure obsoleted buttons are in seen state. */ - _markObsoleteBuiltinButtonsSeen: function() { + _markObsoleteBuiltinButtonsSeen() { if (!gSavedState) return; let currentVersion = gSavedState.currentVersion; @@ -405,7 +405,7 @@ var CustomizableUIInternal = { } }, - _placeNewDefaultWidgetsInArea: function(aArea) { + _placeNewDefaultWidgetsInArea(aArea) { let futurePlacedWidgets = gFuturePlacements.get(aArea); let savedPlacements = gSavedState && gSavedState.placements && gSavedState.placements[aArea]; let defaultPlacements = gAreas.get(aArea).get("defaultPlacements"); @@ -459,7 +459,7 @@ var CustomizableUIInternal = { this.saveState(); }, - wrapWidget: function(aWidgetId) { + wrapWidget(aWidgetId) { if (gGroupWrapperCache.has(aWidgetId)) { return gGroupWrapperCache.get(aWidgetId); } @@ -484,7 +484,7 @@ var CustomizableUIInternal = { return wrapper; }, - registerArea: function(aName, aProperties, aInternalCaller) { + registerArea(aName, aProperties, aInternalCaller) { if (typeof aName != "string" || !/^[a-z0-9-_]{1,}$/i.test(aName)) { throw new Error("Invalid area name"); } @@ -563,7 +563,7 @@ var CustomizableUIInternal = { } }, - unregisterArea: function(aName, aDestroyPlacements) { + unregisterArea(aName, aDestroyPlacements) { if (typeof aName != "string" || !/^[a-z0-9-_]{1,}$/i.test(aName)) { throw new Error("Invalid area name"); } @@ -605,7 +605,7 @@ var CustomizableUIInternal = { } }, - registerToolbarNode: function(aToolbar, aExistingChildren) { + registerToolbarNode(aToolbar, aExistingChildren) { let area = aToolbar.id; if (gBuildAreas.has(area) && gBuildAreas.get(area).has(aToolbar)) { return; @@ -677,7 +677,7 @@ var CustomizableUIInternal = { } }, - buildArea: function(aArea, aPlacements, aAreaNode) { + buildArea(aArea, aPlacements, aAreaNode) { let document = aAreaNode.ownerDocument; let window = document.defaultView; let inPrivateWindow = PrivateBrowsingUtils.isWindowPrivate(window); @@ -813,7 +813,7 @@ var CustomizableUIInternal = { } }, - addPanelCloseListeners: function(aPanel) { + addPanelCloseListeners(aPanel) { gELS.addSystemEventListener(aPanel, "click", this, false); gELS.addSystemEventListener(aPanel, "keypress", this, false); let win = aPanel.ownerGlobal; @@ -823,7 +823,7 @@ var CustomizableUIInternal = { gPanelsForWindow.get(win).add(this._getPanelForNode(aPanel)); }, - removePanelCloseListeners: function(aPanel) { + removePanelCloseListeners(aPanel) { gELS.removeSystemEventListener(aPanel, "click", this, false); gELS.removeSystemEventListener(aPanel, "keypress", this, false); let win = aPanel.ownerGlobal; @@ -833,7 +833,7 @@ var CustomizableUIInternal = { } }, - ensureButtonContextMenu: function(aNode, aAreaNode) { + ensureButtonContextMenu(aNode, aAreaNode) { const kPanelItemContextMenu = "customizationPanelItemContextMenu"; let currentContextMenu = aNode.getAttribute("context") || @@ -851,7 +851,7 @@ var CustomizableUIInternal = { } }, - getWidgetProvider: function(aWidgetId) { + getWidgetProvider(aWidgetId) { if (this.isSpecialWidget(aWidgetId)) { return CustomizableUI.PROVIDER_SPECIAL; } @@ -871,7 +871,7 @@ var CustomizableUIInternal = { return CustomizableUI.PROVIDER_XUL; }, - getWidgetNode: function(aWidgetId, aWindow) { + getWidgetNode(aWidgetId, aWindow) { let document = aWindow.document; if (this.isSpecialWidget(aWidgetId)) { @@ -904,7 +904,7 @@ var CustomizableUIInternal = { return [null, null]; }, - registerMenuPanel: function(aPanelContents) { + registerMenuPanel(aPanelContents) { if (gBuildAreas.has(CustomizableUI.AREA_PANEL) && gBuildAreas.get(CustomizableUI.AREA_PANEL).has(aPanelContents)) { return; @@ -935,7 +935,7 @@ var CustomizableUIInternal = { this.registerBuildArea(CustomizableUI.AREA_PANEL, aPanelContents); }, - onWidgetAdded: function(aWidgetId, aArea, aPosition) { + onWidgetAdded(aWidgetId, aArea, aPosition) { this.insertNode(aWidgetId, aArea, aPosition, true); if (!gResetting) { @@ -943,7 +943,7 @@ var CustomizableUIInternal = { } }, - onWidgetRemoved: function(aWidgetId, aArea) { + onWidgetRemoved(aWidgetId, aArea) { let areaNodes = gBuildAreas.get(aArea); if (!areaNodes) { return; @@ -1003,18 +1003,18 @@ var CustomizableUIInternal = { } }, - onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { this.insertNode(aWidgetId, aArea, aNewPosition); if (!gResetting) { this._clearPreviousUIState(); } }, - onCustomizeEnd: function(aWindow) { + onCustomizeEnd(aWindow) { this._clearPreviousUIState(); }, - registerBuildArea: function(aArea, aNode) { + registerBuildArea(aArea, aNode) { // We ensure that the window is registered to have its customization data // cleaned up when unloading. let window = aNode.ownerGlobal; @@ -1039,7 +1039,7 @@ var CustomizableUIInternal = { customizableNode.classList.add("customization-target"); }, - registerBuildWindow: function(aWindow) { + registerBuildWindow(aWindow) { if (!gBuildWindows.has(aWindow)) { gBuildWindows.set(aWindow, new Set()); @@ -1050,7 +1050,7 @@ var CustomizableUIInternal = { } }, - unregisterBuildWindow: function(aWindow) { + unregisterBuildWindow(aWindow) { aWindow.removeEventListener("unload", this); aWindow.removeEventListener("command", this, true); gPanelsForWindow.delete(aWindow); @@ -1093,7 +1093,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWindowClosed", aWindow); }, - setLocationAttributes: function(aNode, aArea) { + setLocationAttributes(aNode, aArea) { let props = gAreas.get(aArea); if (!props) { throw new Error("Expected area " + aArea + " to have a properties Map " + @@ -1109,12 +1109,12 @@ var CustomizableUIInternal = { } }, - removeLocationAttributes: function(aNode) { + removeLocationAttributes(aNode) { aNode.removeAttribute("cui-areatype"); aNode.removeAttribute("cui-anchorid"); }, - insertNode: function(aWidgetId, aArea, aPosition, isNew) { + insertNode(aWidgetId, aArea, aPosition, isNew) { let areaNodes = gBuildAreas.get(aArea); if (!areaNodes) { return; @@ -1134,7 +1134,7 @@ var CustomizableUIInternal = { } }, - insertNodeInWindow: function(aWidgetId, aAreaNode, isNew) { + insertNodeInWindow(aWidgetId, aAreaNode, isNew) { let window = aAreaNode.ownerGlobal; let showInPrivateBrowsing = gPalette.has(aWidgetId) ? gPalette.get(aWidgetId).showInPrivateBrowsing @@ -1166,7 +1166,7 @@ var CustomizableUIInternal = { } }, - findInsertionPoints: function(aNode, aAreaNode) { + findInsertionPoints(aNode, aAreaNode) { let areaId = aAreaNode.id; let props = gAreas.get(areaId); @@ -1191,14 +1191,14 @@ var CustomizableUIInternal = { return [container, null]; }, - insertWidgetBefore: function(aNode, aNextNode, aContainer, aArea) { + insertWidgetBefore(aNode, aNextNode, aContainer, aArea) { this.notifyListeners("onWidgetBeforeDOMChange", aNode, aNextNode, aContainer); this.setLocationAttributes(aNode, aArea); aContainer.insertBefore(aNode, aNextNode); this.notifyListeners("onWidgetAfterDOMChange", aNode, aNextNode, aContainer); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "command": if (!this._originalEventInPanel(aEvent)) { @@ -1216,7 +1216,7 @@ var CustomizableUIInternal = { } }, - _originalEventInPanel: function(aEvent) { + _originalEventInPanel(aEvent) { let e = aEvent.sourceEvent; if (!e) { return false; @@ -1230,14 +1230,14 @@ var CustomizableUIInternal = { return !!panels && panels.has(node); }, - isSpecialWidget: function(aId) { + isSpecialWidget(aId) { return (aId.startsWith(kSpecialWidgetPfx) || aId.startsWith("separator") || aId.startsWith("spring") || aId.startsWith("spacer")); }, - ensureSpecialWidgetId: function(aId) { + ensureSpecialWidgetId(aId) { let nodeType = aId.match(/spring|spacer|separator/)[0]; // If the ID we were passed isn't a generated one, generate one now: if (nodeType == aId) { @@ -1247,7 +1247,7 @@ var CustomizableUIInternal = { return aId; }, - createSpecialWidget: function(aId, aDocument) { + createSpecialWidget(aId, aDocument) { let nodeName = "toolbar" + aId.match(/spring|spacer|separator/)[0]; let node = aDocument.createElementNS(kNSXUL, nodeName); node.id = this.ensureSpecialWidgetId(aId); @@ -1260,7 +1260,7 @@ var CustomizableUIInternal = { /* Find a XUL-provided widget in a window. Don't try to use this * for an API-provided widget or a special widget. */ - findWidgetInWindow: function(aId, aWindow) { + findWidgetInWindow(aId, aWindow) { if (!gBuildWindows.has(aWindow)) { throw new Error("Build window not registered"); } @@ -1322,7 +1322,7 @@ var CustomizableUIInternal = { return null; }, - buildWidget: function(aDocument, aWidget) { + buildWidget(aDocument, aWidget) { if (aDocument.documentURI != kExpectedWindowURL) { throw new Error("buildWidget was called for a non-browser window!"); } @@ -1417,7 +1417,7 @@ var CustomizableUIInternal = { return node; }, - getLocalizedProperty: function(aWidget, aProp, aFormatArgs, aDef) { + getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef) { const kReqStringProps = ["label"]; if (typeof aWidget == "string") { @@ -1456,7 +1456,7 @@ var CustomizableUIInternal = { return def; }, - addShortcut: function(aShortcutNode, aTargetNode = aShortcutNode) { + addShortcut(aShortcutNode, aTargetNode = aShortcutNode) { // Detect if we've already been here before. if (aTargetNode.hasAttribute("shortcut")) return; @@ -1478,7 +1478,7 @@ var CustomizableUIInternal = { aTargetNode.setAttribute("shortcut", ShortcutUtils.prettifyShortcut(shortcut)); }, - handleWidgetCommand: function(aWidget, aNode, aEvent) { + handleWidgetCommand(aWidget, aNode, aEvent) { log.debug("handleWidgetCommand"); if (aWidget.type == "button") { @@ -1509,7 +1509,7 @@ var CustomizableUIInternal = { } }, - handleWidgetClick: function(aWidget, aNode, aEvent) { + handleWidgetClick(aWidget, aNode, aEvent) { log.debug("handleWidgetClick"); if (aWidget.onClick) { try { @@ -1523,7 +1523,7 @@ var CustomizableUIInternal = { } }, - _getPanelForNode: function(aNode) { + _getPanelForNode(aNode) { let panel = aNode; while (panel && panel.localName != "panel") panel = panel.parentNode; @@ -1536,7 +1536,7 @@ var CustomizableUIInternal = { * We also check for being outside of any toolbaritem/toolbarbutton, ie on a blank * part of the menu. */ - _isOnInteractiveElement: function(aEvent) { + _isOnInteractiveElement(aEvent) { function getMenuPopupForDescendant(aNode) { let lastPopup = null; while (aNode && aNode.parentNode && @@ -1652,14 +1652,14 @@ var CustomizableUIInternal = { return inInput || !inItem; }, - hidePanelForNode: function(aNode) { + hidePanelForNode(aNode) { let panel = this._getPanelForNode(aNode); if (panel) { panel.hidePopup(); } }, - maybeAutoHidePanel: function(aEvent) { + maybeAutoHidePanel(aEvent) { if (aEvent.type == "keypress") { if (aEvent.keyCode != aEvent.DOM_VK_RETURN) { return; @@ -1714,7 +1714,7 @@ var CustomizableUIInternal = { this.hidePanelForNode(aEvent.target); }, - getUnusedWidgets: function(aWindowPalette) { + getUnusedWidgets(aWindowPalette) { let window = aWindowPalette.ownerGlobal; let isWindowPrivate = PrivateBrowsingUtils.isWindowPrivate(window); // We use a Set because there can be overlap between the widgets in @@ -1745,7 +1745,7 @@ var CustomizableUIInternal = { return [...widgets]; }, - getPlacementOfWidget: function(aWidgetId, aOnlyRegistered, aDeadAreas) { + getPlacementOfWidget(aWidgetId, aOnlyRegistered, aDeadAreas) { if (aOnlyRegistered && !this.widgetExists(aWidgetId)) { return null; } @@ -1756,14 +1756,14 @@ var CustomizableUIInternal = { } let index = placements.indexOf(aWidgetId); if (index != -1) { - return { area: area, position: index }; + return { area, position: index }; } } return null; }, - widgetExists: function(aWidgetId) { + widgetExists(aWidgetId) { if (gPalette.has(aWidgetId) || this.isSpecialWidget(aWidgetId)) { return true; } @@ -1778,7 +1778,7 @@ var CustomizableUIInternal = { return true; }, - addWidgetToArea: function(aWidgetId, aArea, aPosition, aInitialAdd) { + addWidgetToArea(aWidgetId, aArea, aPosition, aInitialAdd) { if (!gAreas.has(aArea)) { throw new Error("Unknown customization area: " + aArea); } @@ -1852,7 +1852,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetAdded", aWidgetId, aArea, aPosition); }, - removeWidgetFromArea: function(aWidgetId) { + removeWidgetFromArea(aWidgetId) { let oldPlacement = this.getPlacementOfWidget(aWidgetId, false, true); if (!oldPlacement) { return; @@ -1881,7 +1881,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetRemoved", aWidgetId, oldPlacement.area); }, - moveWidgetWithinArea: function(aWidgetId, aPosition) { + moveWidgetWithinArea(aWidgetId, aPosition) { let oldPlacement = this.getPlacementOfWidget(aWidgetId); if (!oldPlacement) { return; @@ -1930,7 +1930,7 @@ var CustomizableUIInternal = { // built lazily - and therefore wouldn't otherwise result in restoring its // state immediately when a browser window opens, which is important for // other consumers of this API. - loadSavedState: function() { + loadSavedState() { let state = null; try { state = Services.prefs.getCharPref(kPrefCustomizationState); @@ -1967,7 +1967,7 @@ var CustomizableUIInternal = { gNewElementCount = gSavedState.newElementCount || 0; }, - restoreStateForArea: function(aArea, aLegacyState) { + restoreStateForArea(aArea, aLegacyState) { let placementsPreexisted = gPlacements.has(aArea); this.beginBatchUpdate(); @@ -2031,7 +2031,7 @@ var CustomizableUIInternal = { } }, - saveState: function() { + saveState() { if (gInBatchStack || !gDirty) { return; } @@ -2061,7 +2061,7 @@ var CustomizableUIInternal = { gDirty = false; }, - serializerHelper: function(aKey, aValue) { + serializerHelper(aKey, aValue) { if (typeof aValue == "object" && aValue.constructor.name == "Map") { let result = {}; for (let [mapKey, mapValue] of aValue) @@ -2076,11 +2076,11 @@ var CustomizableUIInternal = { return aValue; }, - beginBatchUpdate: function() { + beginBatchUpdate() { gInBatchStack++; }, - endBatchUpdate: function(aForceDirty) { + endBatchUpdate(aForceDirty) { gInBatchStack--; if (aForceDirty === true) { gDirty = true; @@ -2092,11 +2092,11 @@ var CustomizableUIInternal = { } }, - addListener: function(aListener) { + addListener(aListener) { gListeners.add(aListener); }, - removeListener: function(aListener) { + removeListener(aListener) { if (aListener == this) { return; } @@ -2104,7 +2104,7 @@ var CustomizableUIInternal = { gListeners.delete(aListener); }, - notifyListeners: function(aEvent, ...aArgs) { + notifyListeners(aEvent, ...aArgs) { if (gRestoring) { return; } @@ -2120,7 +2120,7 @@ var CustomizableUIInternal = { } }, - _dispatchToolboxEventToWindow: function(aEventType, aDetails, aWindow) { + _dispatchToolboxEventToWindow(aEventType, aDetails, aWindow) { let evt = new aWindow.CustomEvent(aEventType, { bubbles: true, cancelable: true, @@ -2129,7 +2129,7 @@ var CustomizableUIInternal = { aWindow.gNavToolbox.dispatchEvent(evt); }, - dispatchToolboxEvent: function(aEventType, aDetails = {}, aWindow = null) { + dispatchToolboxEvent(aEventType, aDetails = {}, aWindow = null) { if (aWindow) { this._dispatchToolboxEventToWindow(aEventType, aDetails, aWindow); return; @@ -2139,7 +2139,7 @@ var CustomizableUIInternal = { } }, - createWidget: function(aProperties) { + createWidget(aProperties) { let widget = this.normalizeWidget(aProperties, CustomizableUI.SOURCE_EXTERNAL); // XXXunf This should probably throw. if (!widget) { @@ -2256,7 +2256,7 @@ var CustomizableUIInternal = { return widget.id; }, - createBuiltinWidget: function(aData) { + createBuiltinWidget(aData) { // This should only ever be called on startup, before any windows are // opened - so we know there's no build areas to handle. Also, builtin // widgets are expected to be (mostly) static, so shouldn't affect the @@ -2291,7 +2291,7 @@ var CustomizableUIInternal = { }, // Returns true if the area will eventually lazily restore (but hasn't yet). - isAreaLazy: function(aArea) { + isAreaLazy(aArea) { if (gPlacements.has(aArea)) { return false; } @@ -2299,7 +2299,7 @@ var CustomizableUIInternal = { }, // XXXunf Log some warnings here, when the data provided isn't up to scratch. - normalizeWidget: function(aData, aSource) { + normalizeWidget(aData, aSource) { let widget = { implementation: aData, source: aSource || CustomizableUI.SOURCE_EXTERNAL, @@ -2400,7 +2400,7 @@ var CustomizableUIInternal = { return widget; }, - wrapWidgetEventHandler: function(aEventName, aWidget) { + wrapWidgetEventHandler(aEventName, aWidget) { if (typeof aWidget.implementation[aEventName] != "function") { aWidget[aEventName] = null; return; @@ -2422,7 +2422,7 @@ var CustomizableUIInternal = { }; }, - destroyWidget: function(aWidgetId) { + destroyWidget(aWidgetId) { let widget = gPalette.get(aWidgetId); if (!widget) { gGroupWrapperCache.delete(aWidgetId); @@ -2489,7 +2489,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetDestroyed", aWidgetId); }, - getCustomizeTargetForArea: function(aArea, aWindow) { + getCustomizeTargetForArea(aArea, aWindow) { let buildAreaNodes = gBuildAreas.get(aArea); if (!buildAreaNodes) { return null; @@ -2504,7 +2504,7 @@ var CustomizableUIInternal = { return null; }, - reset: function() { + reset() { gResetting = true; this._resetUIState(); @@ -2524,7 +2524,7 @@ var CustomizableUIInternal = { gResetting = false; }, - _resetUIState: function() { + _resetUIState() { try { gUIStateBeforeReset.drawInTitlebar = Services.prefs.getBoolPref(kPrefDrawInTitlebar); gUIStateBeforeReset.uiCustomizationState = Services.prefs.getCharPref(kPrefCustomizationState); @@ -2550,7 +2550,7 @@ var CustomizableUIInternal = { } }, - _resetExtraToolbars: function(aFilter = null) { + _resetExtraToolbars(aFilter = null) { let firstWindow = true; // Only need to unregister and persist once for (let [win, ] of gBuildWindows) { let toolbox = win.gNavToolbox; @@ -2572,7 +2572,7 @@ var CustomizableUIInternal = { } }, - _rebuildRegisteredAreas: function() { + _rebuildRegisteredAreas() { for (let [areaId, areaNodes] of gBuildAreas) { let placements = gPlacements.get(areaId); let isFirstChangedToolbar = true; @@ -2595,7 +2595,7 @@ var CustomizableUIInternal = { /** * Undoes a previous reset, restoring the state of the UI to the state prior to the reset. */ - undoReset: function() { + undoReset() { if (gUIStateBeforeReset.uiCustomizationState == null || gUIStateBeforeReset.drawInTitlebar == null) { return; @@ -2627,13 +2627,13 @@ var CustomizableUIInternal = { gUndoResetting = false; }, - _clearPreviousUIState: function() { + _clearPreviousUIState() { Object.getOwnPropertyNames(gUIStateBeforeReset).forEach((prop) => { gUIStateBeforeReset[prop] = null; }); }, - removeExtraToolbar: function(aToolbarId) { + removeExtraToolbar(aToolbarId) { this._resetExtraToolbars(aToolbarId); }, @@ -2641,7 +2641,7 @@ var CustomizableUIInternal = { * @param {String|Node} aWidget - widget ID or a widget node (preferred for performance). * @return {Boolean} whether the widget is removable */ - isWidgetRemovable: function(aWidget) { + isWidgetRemovable(aWidget) { let widgetId; let widgetNode; if (typeof aWidget == "string") { @@ -2684,7 +2684,7 @@ var CustomizableUIInternal = { return true; }, - canWidgetMoveToArea: function(aWidgetId, aArea) { + canWidgetMoveToArea(aWidgetId, aArea) { let placement = this.getPlacementOfWidget(aWidgetId); if (placement && placement.area != aArea) { // Special widgets can't move to the menu panel. @@ -2699,7 +2699,7 @@ var CustomizableUIInternal = { return true; }, - ensureWidgetPlacedInWindow: function(aWidgetId, aWindow) { + ensureWidgetPlacedInWindow(aWidgetId, aWindow) { let placement = this.getPlacementOfWidget(aWidgetId); if (!placement) { return false; @@ -2799,7 +2799,7 @@ var CustomizableUIInternal = { return true; }, - setToolbarVisibility: function(aToolbarId, aIsVisible) { + setToolbarVisibility(aToolbarId, aIsVisible) { // We only persist the attribute the first time. let isFirstChangedToolbar = true; for (let window of CustomizableUI.windows) { @@ -3003,14 +3003,14 @@ this.CustomizableUI = { * or by a window closing. The aReason parameter indicates which of * these is the case. */ - addListener: function(aListener) { + addListener(aListener) { CustomizableUIInternal.addListener(aListener); }, /** * Remove a listener added with addListener * @param aListener the listener object to remove */ - removeListener: function(aListener) { + removeListener(aListener) { CustomizableUIInternal.removeListener(aListener); }, @@ -3036,7 +3036,7 @@ this.CustomizableUI = { * Specify null to ensure that reset/inDefaultArea don't care * about a toolbar's collapsed state */ - registerArea: function(aName, aProperties) { + registerArea(aName, aProperties) { CustomizableUIInternal.registerArea(aName, aProperties); }, /** @@ -3055,7 +3055,7 @@ this.CustomizableUI = { * allow the user to customize it in customize mode, or otherwise deal * with it, until the area has been registered. */ - registerToolbarNode: function(aToolbar, aExistingChildren) { + registerToolbarNode(aToolbar, aExistingChildren) { CustomizableUIInternal.registerToolbarNode(aToolbar, aExistingChildren); }, /** @@ -3063,7 +3063,7 @@ this.CustomizableUI = { * apart from the built-in PanelUI. * @param aPanel the panel DOM node being registered. */ - registerMenuPanel: function(aPanel) { + registerMenuPanel(aPanel) { CustomizableUIInternal.registerMenuPanel(aPanel); }, /** @@ -3087,7 +3087,7 @@ this.CustomizableUI = { * @param aDestroyPlacements whether to destroy the placements information * for the area, too. */ - unregisterArea: function(aName, aDestroyPlacements) { + unregisterArea(aName, aDestroyPlacements) { CustomizableUIInternal.unregisterArea(aName, aDestroyPlacements); }, /** @@ -3112,7 +3112,7 @@ this.CustomizableUI = { * pass a position, the widget will be added to the end * of the area. */ - addWidgetToArea: function(aWidgetId, aArea, aPosition) { + addWidgetToArea(aWidgetId, aArea, aPosition) { CustomizableUIInternal.addWidgetToArea(aWidgetId, aArea, aPosition); }, /** @@ -3124,7 +3124,7 @@ this.CustomizableUI = { * * @param aWidgetId the ID of the widget to remove */ - removeWidgetFromArea: function(aWidgetId) { + removeWidgetFromArea(aWidgetId) { CustomizableUIInternal.removeWidgetFromArea(aWidgetId); }, /** @@ -3142,7 +3142,7 @@ this.CustomizableUI = { * widgets will be interpreted to mean moving the widget to * respectively the first or last position. */ - moveWidgetWithinArea: function(aWidgetId, aPosition) { + moveWidgetWithinArea(aWidgetId, aPosition) { CustomizableUIInternal.moveWidgetWithinArea(aWidgetId, aPosition); }, /** @@ -3161,7 +3161,7 @@ this.CustomizableUI = { * presumably you yourself need to create the widget in all the windows * and need to loop through them anyway. */ - ensureWidgetPlacedInWindow: function(aWidgetId, aWindow) { + ensureWidgetPlacedInWindow(aWidgetId, aWindow) { return CustomizableUIInternal.ensureWidgetPlacedInWindow(aWidgetId, aWindow); }, /** @@ -3176,7 +3176,7 @@ this.CustomizableUI = { * Firefox session, customization state is never saved. Typically, you * would do this using a try...finally block. */ - beginBatchUpdate: function() { + beginBatchUpdate() { CustomizableUIInternal.beginBatchUpdate(); }, /** @@ -3191,7 +3191,7 @@ this.CustomizableUI = { * @param aForceDirty force CustomizableUI to flush to the prefs file when * all batch updates have finished. */ - endBatchUpdate: function(aForceDirty) { + endBatchUpdate(aForceDirty) { CustomizableUIInternal.endBatchUpdate(aForceDirty); }, /** @@ -3267,7 +3267,7 @@ this.CustomizableUI = { * @param aProperties the specifications for the widget. * @return a wrapper around the created widget (see getWidget) */ - createWidget: function(aProperties) { + createWidget(aProperties) { return CustomizableUIInternal.wrapWidget( CustomizableUIInternal.createWidget(aProperties) ); @@ -3283,7 +3283,7 @@ this.CustomizableUI = { * * @param aWidgetId the ID of the widget to destroy */ - destroyWidget: function(aWidgetId) { + destroyWidget(aWidgetId) { CustomizableUIInternal.destroyWidget(aWidgetId); }, /** @@ -3346,7 +3346,7 @@ this.CustomizableUI = { * is no guarantee the widget exists because we cannot know in * advance if a XUL widget exists or not. */ - getWidget: function(aWidgetId) { + getWidget(aWidgetId) { return CustomizableUIInternal.wrapWidget(aWidgetId); }, /** @@ -3363,7 +3363,7 @@ this.CustomizableUI = { * * @return an array of widget wrappers (see getWidget) */ - getUnusedWidgets: function(aWindowPalette) { + getUnusedWidgets(aWindowPalette) { return CustomizableUIInternal.getUnusedWidgets(aWindowPalette).map( CustomizableUIInternal.wrapWidget, CustomizableUIInternal @@ -3380,7 +3380,7 @@ this.CustomizableUI = { * NB: will throw if called too early (before placements have been fetched) * or if the area is not currently known to CustomizableUI. */ - getWidgetIdsInArea: function(aArea) { + getWidgetIdsInArea(aArea) { if (!gAreas.has(aArea)) { throw new Error("Unknown customization area: " + aArea); } @@ -3406,7 +3406,7 @@ this.CustomizableUI = { * NB: will throw if called too early (before placements have been fetched) * or if the area is not currently known to CustomizableUI. */ - getWidgetsInArea: function(aArea) { + getWidgetsInArea(aArea) { return this.getWidgetIdsInArea(aArea).map( CustomizableUIInternal.wrapWidget, CustomizableUIInternal @@ -3430,7 +3430,7 @@ this.CustomizableUI = { * @return TYPE_TOOLBAR or TYPE_MENU_PANEL depending on the area, null if * the area is unknown. */ - getAreaType: function(aArea) { + getAreaType(aArea) { let area = gAreas.get(aArea); return area ? area.get("type") : null; }, @@ -3441,7 +3441,7 @@ this.CustomizableUI = { * @return `true` or `false` depending on the area, null if the area is unknown, * or its collapsed state cannot normally be controlled by the user */ - isToolbarDefaultCollapsed: function(aArea) { + isToolbarDefaultCollapsed(aArea) { let area = gAreas.get(aArea); return area ? area.get("defaultCollapsed") : null; }, @@ -3469,7 +3469,7 @@ this.CustomizableUI = { * @param aWindow the window where you want to fetch the DOM node. * @return the customize target DOM node for aArea in aWindow */ - getCustomizeTargetForArea: function(aArea, aWindow) { + getCustomizeTargetForArea(aArea, aWindow) { return CustomizableUIInternal.getCustomizeTargetForArea(aArea, aWindow); }, /** @@ -3479,7 +3479,7 @@ this.CustomizableUI = { * explicitly requests it. Firefox does this when the user clicks the * "Restore Defaults" button in customize mode. */ - reset: function() { + reset() { CustomizableUIInternal.reset(); }, @@ -3487,7 +3487,7 @@ this.CustomizableUI = { * Undo the previous reset, can only be called immediately after a reset. * @return a promise that will be resolved when the operation is complete. */ - undoReset: function() { + undoReset() { CustomizableUIInternal.undoReset(); }, @@ -3498,7 +3498,7 @@ this.CustomizableUI = { * other consumers. * @param aToolbarId the ID of the toolbar to remove */ - removeExtraToolbar: function(aToolbarId) { + removeExtraToolbar(aToolbarId) { CustomizableUIInternal.removeExtraToolbar(aToolbarId); }, @@ -3532,7 +3532,7 @@ this.CustomizableUI = { * * null // if the widget is not placed anywhere (ie in the palette) */ - getPlacementOfWidget: function(aWidgetId, aOnlyRegistered = true, aDeadAreas = false) { + getPlacementOfWidget(aWidgetId, aOnlyRegistered = true, aDeadAreas = false) { return CustomizableUIInternal.getPlacementOfWidget(aWidgetId, aOnlyRegistered, aDeadAreas); }, /** @@ -3553,7 +3553,7 @@ this.CustomizableUI = { * @return true if the widget can be removed from its area, * false otherwise. */ - isWidgetRemovable: function(aWidgetId) { + isWidgetRemovable(aWidgetId) { return CustomizableUIInternal.isWidgetRemovable(aWidgetId); }, /** @@ -3566,7 +3566,7 @@ this.CustomizableUI = { * @return true if this is possible, false if it is not. The same caveats as * for isWidgetRemovable apply, however, if no windows are open. */ - canWidgetMoveToArea: function(aWidgetId, aArea) { + canWidgetMoveToArea(aWidgetId, aArea) { return CustomizableUIInternal.canWidgetMoveToArea(aWidgetId, aArea); }, /** @@ -3587,7 +3587,7 @@ this.CustomizableUI = { * @param aToolbarId the toolbar whose visibility should be adjusted * @param aIsVisible whether the toolbar should be visible */ - setToolbarVisibility: function(aToolbarId, aIsVisible) { + setToolbarVisibility(aToolbarId, aIsVisible) { CustomizableUIInternal.setToolbarVisibility(aToolbarId, aIsVisible); }, @@ -3614,7 +3614,7 @@ this.CustomizableUI = { * otherwise we'll return the empty string * */ - getLocalizedProperty: function(aWidget, aProp, aFormatArgs, aDef) { + getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef) { return CustomizableUIInternal.getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef); }, @@ -3627,7 +3627,7 @@ this.CustomizableUI = { * attribute will be set. If NULL, the shortcut will be * set on aShortcutNode; */ - addShortcut: function(aShortcutNode, aTargetNode) { + addShortcut(aShortcutNode, aTargetNode) { return CustomizableUIInternal.addShortcut(aShortcutNode, aTargetNode); }, /** @@ -3636,7 +3636,7 @@ this.CustomizableUI = { * * @param aNode a node whose panel should be closed; */ - hidePanelForNode: function(aNode) { + hidePanelForNode(aNode) { CustomizableUIInternal.hidePanelForNode(aNode); }, /** @@ -3645,7 +3645,7 @@ this.CustomizableUI = { * @param aWidgetId the widget ID to check. * @return true if the widget is 'special', false otherwise. */ - isSpecialWidget: function(aWidgetId) { + isSpecialWidget(aWidgetId) { return CustomizableUIInternal.isSpecialWidget(aWidgetId); }, /** @@ -3655,7 +3655,7 @@ this.CustomizableUI = { * * @param aPanel the panel to which listeners should be attached. */ - addPanelCloseListeners: function(aPanel) { + addPanelCloseListeners(aPanel) { CustomizableUIInternal.addPanelCloseListeners(aPanel); }, /** @@ -3665,7 +3665,7 @@ this.CustomizableUI = { * * @param aPanel the panel from which listeners should be removed. */ - removePanelCloseListeners: function(aPanel) { + removePanelCloseListeners(aPanel) { CustomizableUIInternal.removePanelCloseListeners(aPanel); }, /** @@ -3675,7 +3675,7 @@ this.CustomizableUI = { * @param aWidgetId the ID of the widget that is being dragged to an area. * @param aArea the ID of the area to which the widget is being dragged. */ - onWidgetDrag: function(aWidgetId, aArea) { + onWidgetDrag(aWidgetId, aArea) { CustomizableUIInternal.notifyListeners("onWidgetDrag", aWidgetId, aArea); }, /** @@ -3683,7 +3683,7 @@ this.CustomizableUI = { * Customize Mode only, do not use otherwise. * @param aWindow the window entering customize mode */ - notifyStartCustomizing: function(aWindow) { + notifyStartCustomizing(aWindow) { CustomizableUIInternal.notifyListeners("onCustomizeStart", aWindow); }, /** @@ -3691,7 +3691,7 @@ this.CustomizableUI = { * Customize Mode only, do not use otherwise. * @param aWindow the window exiting customize mode */ - notifyEndCustomizing: function(aWindow) { + notifyEndCustomizing(aWindow) { CustomizableUIInternal.notifyListeners("onCustomizeEnd", aWindow); }, @@ -3703,7 +3703,7 @@ this.CustomizableUI = { * @param aDetails optional, the details of the event. * @param aWindow optional, the window in which to send the event. */ - dispatchToolboxEvent: function(aEvent, aDetails = {}, aWindow = null) { + dispatchToolboxEvent(aEvent, aDetails = {}, aWindow = null) { CustomizableUIInternal.dispatchToolboxEvent(aEvent, aDetails, aWindow); }, @@ -3713,7 +3713,7 @@ this.CustomizableUI = { * @param aAreaId the ID of an area to check for overflowable-ness * @return true if the area is overflowable, false otherwise. */ - isAreaOverflowable: function(aAreaId) { + isAreaOverflowable(aAreaId) { let area = gAreas.get(aAreaId); return area ? area.get("type") == this.TYPE_TOOLBAR && area.get("overflowable") : false; @@ -3728,7 +3728,7 @@ this.CustomizableUI = { * menu panel, "palette" if it is in the (visible!) customization * palette, undefined otherwise. */ - getPlaceForItem: function(aElement) { + getPlaceForItem(aElement) { let place; let node = aElement; while (node && !place) { @@ -3748,7 +3748,7 @@ this.CustomizableUI = { * Check if a toolbar is builtin or not. * @param aToolbarId the ID of the toolbar you want to check */ - isBuiltinToolbar: function(aToolbarId) { + isBuiltinToolbar(aToolbarId) { return CustomizableUIInternal._builtinToolbars.has(aToolbarId); }, }; @@ -4038,7 +4038,7 @@ OverflowableToolbar.prototype = { initialized: false, _forceOnOverflow: false, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "browser-delayed-startup-finished" && aSubject == this._toolbar.ownerGlobal) { Services.obs.removeObserver(this, "browser-delayed-startup-finished"); @@ -4046,7 +4046,7 @@ OverflowableToolbar.prototype = { } }, - init: function() { + init() { let doc = this._toolbar.ownerDocument; let window = doc.defaultView; window.addEventListener("resize", this); @@ -4075,7 +4075,7 @@ OverflowableToolbar.prototype = { this.initialized = true; }, - uninit: function() { + uninit() { this._toolbar.removeEventListener("overflow", this._toolbar); this._toolbar.removeEventListener("underflow", this._toolbar); this._toolbar.removeAttribute("overflowable"); @@ -4099,7 +4099,7 @@ OverflowableToolbar.prototype = { CustomizableUIInternal.removePanelCloseListeners(this._panel); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "aftercustomization": this._enable(); @@ -4128,7 +4128,7 @@ OverflowableToolbar.prototype = { } }, - show: function() { + show() { if (this._panel.state == "open") { return Promise.resolve(); } @@ -4151,7 +4151,7 @@ OverflowableToolbar.prototype = { }); }, - _onClickChevron: function(aEvent) { + _onClickChevron(aEvent) { if (this._chevron.open) { this._panel.hidePopup(); this._chevron.open = false; @@ -4160,7 +4160,7 @@ OverflowableToolbar.prototype = { } }, - _onPanelHiding: function(aEvent) { + _onPanelHiding(aEvent) { this._chevron.open = false; this._panel.removeEventListener("dragover", this); this._panel.removeEventListener("dragend", this); @@ -4169,7 +4169,7 @@ OverflowableToolbar.prototype = { gELS.removeSystemEventListener(contextMenu, 'command', this, true); }, - onOverflow: function(aEvent) { + onOverflow(aEvent) { // The rangeParent check is here because of bug 1111986 and ensuring that // overflow events from the bookmarks toolbar items or similar things that // manage their own overflow don't trigger an overflow on the entire toolbar @@ -4202,7 +4202,7 @@ OverflowableToolbar.prototype = { win.UpdateUrlbarSearchSplitterState(); }, - _onResize: function(aEvent) { + _onResize(aEvent) { if (!this._lazyResizeHandler) { this._lazyResizeHandler = new DeferredTask(this._onLazyResize.bind(this), LAZY_RESIZE_INTERVAL_MS); @@ -4210,7 +4210,7 @@ OverflowableToolbar.prototype = { this._lazyResizeHandler.arm(); }, - _moveItemsBackToTheirOrigin: function(shouldMoveAllItems) { + _moveItemsBackToTheirOrigin(shouldMoveAllItems) { let placements = gPlacements.get(this._toolbar.id); while (this._list.firstChild) { let child = this._list.firstChild; @@ -4256,7 +4256,7 @@ OverflowableToolbar.prototype = { } }, - _onLazyResize: function() { + _onLazyResize() { if (!this._enabled) return; @@ -4267,7 +4267,7 @@ OverflowableToolbar.prototype = { } }, - _disable: function() { + _disable() { this._enabled = false; this._moveItemsBackToTheirOrigin(true); if (this._lazyResizeHandler) { @@ -4275,12 +4275,12 @@ OverflowableToolbar.prototype = { } }, - _enable: function() { + _enable() { this._enabled = true; this.onOverflow(); }, - onWidgetBeforeDOMChange: function(aNode, aNextNode, aContainer) { + onWidgetBeforeDOMChange(aNode, aNextNode, aContainer) { if (aContainer != this._target && aContainer != this._list) { return; } @@ -4303,7 +4303,7 @@ OverflowableToolbar.prototype = { } }, - onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer) { + onWidgetAfterDOMChange(aNode, aNextNode, aContainer) { if (aContainer != this._target && aContainer != this._list) { return; } @@ -4358,7 +4358,7 @@ OverflowableToolbar.prototype = { } }, - findOverflowedInsertionPoints: function(aNode) { + findOverflowedInsertionPoints(aNode) { let newNodeCanOverflow = aNode.getAttribute("overflows") != "false"; let areaId = this._toolbar.id; let placements = gPlacements.get(areaId); @@ -4391,7 +4391,7 @@ OverflowableToolbar.prototype = { return [containerForAppending, null]; }, - getContainerFor: function(aNode) { + getContainerFor(aNode) { if (aNode.getAttribute("overflowedItem") == "true") { return this._list; } @@ -4399,7 +4399,7 @@ OverflowableToolbar.prototype = { }, _hideTimeoutId: null, - _showWithTimeout: function() { + _showWithTimeout() { this.show().then(function() { let window = this._toolbar.ownerGlobal; if (this._hideTimeoutId) { diff --git a/browser/components/customizableui/CustomizableWidgets.jsm b/browser/components/customizableui/CustomizableWidgets.jsm index 6b1dc8ea1af6..6f30303afb49 100644 --- a/browser/components/customizableui/CustomizableWidgets.jsm +++ b/browser/components/customizableui/CustomizableWidgets.jsm @@ -178,7 +178,7 @@ const CustomizableWidgets = [ shortcutId: "key_gotoHistory", tooltiptext: "history-panelmenu.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { // Populate our list of history const kMaxResults = 15; let doc = aEvent.target.ownerDocument; @@ -204,7 +204,7 @@ const CustomizableWidgets = [ PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase) .asyncExecuteLegacyQueries([query], 1, options, { - handleResult: function(aResultSet) { + handleResult(aResultSet) { let onItemCommand = function(aItemCommandEvent) { // Only handle the click event for middle clicks, we're using the command // event otherwise. @@ -237,10 +237,10 @@ const CustomizableWidgets = [ } items.appendChild(fragment); }, - handleError: function(aError) { + handleError(aError) { log.debug("History view tried to show but had an error: " + aError); }, - handleCompletion: function(aReason) { + handleCompletion(aReason) { log.debug("History view is being shown!"); }, }); @@ -280,7 +280,7 @@ const CustomizableWidgets = [ } recentlyClosedWindows.appendChild(windowsFragment); }, - onCreated: function(aNode) { + onCreated(aNode) { // Middle clicking recently closed items won't close the panel - cope: let onRecentlyClosedClick = function(aEvent) { if (aEvent.button == 1) { @@ -293,7 +293,7 @@ const CustomizableWidgets = [ recentlyClosedTabs.addEventListener("click", onRecentlyClosedClick); recentlyClosedWindows.addEventListener("click", onRecentlyClosedClick); }, - onViewHiding: function(aEvent) { + onViewHiding(aEvent) { log.debug("History view is being hidden!"); } }, { @@ -466,7 +466,7 @@ const CustomizableWidgets = [ appendTo.appendChild(messageLabel); return messageLabel; }, - _appendClient: function(client, attachFragment) { + _appendClient(client, attachFragment) { let doc = attachFragment.ownerDocument; // Create the element for the remote client. let clientItem = doc.createElementNS(kNSXUL, "label"); @@ -510,7 +510,7 @@ const CustomizableWidgets = [ id: "privatebrowsing-button", shortcutId: "key_privatebrowsing", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(e) { + onCommand(e) { let win = e.target.ownerGlobal; win.OpenBrowserWindow({private: true}); } @@ -519,7 +519,7 @@ const CustomizableWidgets = [ shortcutId: "key_savePage", tooltiptext: "save-page-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; win.saveBrowser(win.gBrowser.selectedBrowser); } @@ -528,7 +528,7 @@ const CustomizableWidgets = [ shortcutId: "key_find", tooltiptext: "find-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; if (win.gFindBar) { win.gFindBar.onFindCommand(); @@ -539,7 +539,7 @@ const CustomizableWidgets = [ shortcutId: "openFileKb", tooltiptext: "open-file-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; win.BrowserOpenFileWindow(); } @@ -548,7 +548,7 @@ const CustomizableWidgets = [ type: "view", viewId: "PanelUI-sidebar", tooltiptext: "sidebar-button.tooltiptext2", - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { // Populate the subview with whatever menuitems are in the // sidebar menu. We skip menu elements, because the menu panel has no way // of dealing with those right now. @@ -565,7 +565,7 @@ const CustomizableWidgets = [ id: "social-share-button", // custom build our button so we can attach to the share command type: "custom", - onBuild: function(aDocument) { + onBuild(aDocument) { let node = aDocument.createElementNS(kNSXUL, "toolbarbutton"); node.setAttribute("id", this.id); node.classList.add("toolbarbutton-1"); @@ -607,7 +607,7 @@ const CustomizableWidgets = [ shortcutId: "key_openAddons", tooltiptext: "add-ons-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; win.BrowserOpenAddonsMgr(); } @@ -616,7 +616,7 @@ const CustomizableWidgets = [ type: "custom", tooltiptext: "zoom-controls.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onBuild: function(aDocument) { + onBuild(aDocument) { const kPanelId = "PanelUI-popup"; let areaType = CustomizableUI.getAreaType(this.currentArea); let inPanel = areaType == CustomizableUI.TYPE_MENU_PANEL; @@ -768,13 +768,13 @@ const CustomizableWidgets = [ container.removeEventListener("TabSelect", updateZoomResetButton); }.bind(this), - onCustomizeStart: function(aWindow) { + onCustomizeStart(aWindow) { if (aWindow.document == aDocument) { updateZoomResetButton(); } }, - onCustomizeEnd: function(aWindow) { + onCustomizeEnd(aWindow) { if (aWindow.document == aDocument) { updateZoomResetButton(); } @@ -796,7 +796,7 @@ const CustomizableWidgets = [ type: "custom", tooltiptext: "edit-controls.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onBuild: function(aDocument) { + onBuild(aDocument) { let buttons = [{ id: "cut-button", command: "cmd_cut", @@ -894,7 +894,7 @@ const CustomizableWidgets = [ viewId: "PanelUI-feeds", tooltiptext: "feed-button.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onClick: function(aEvent) { + onClick(aEvent) { let win = aEvent.target.ownerGlobal; let feeds = win.gBrowser.selectedBrowser.feeds; @@ -908,7 +908,7 @@ const CustomizableWidgets = [ CustomizableUI.hidePanelForNode(aEvent.target); } }, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { let doc = aEvent.target.ownerDocument; let container = doc.getElementById("PanelUI-feeds"); let gotView = doc.defaultView.FeedHandler.buildFeedList(container, true); @@ -920,7 +920,7 @@ const CustomizableWidgets = [ return; } }, - onCreated: function(node) { + onCreated(node) { let win = node.ownerGlobal; let selectedBrowser = win.gBrowser.selectedBrowser; let feeds = selectedBrowser && selectedBrowser.feeds; @@ -935,12 +935,12 @@ const CustomizableWidgets = [ viewId: "PanelUI-characterEncodingView", tooltiptext: "characterencoding-button2.tooltiptext", defaultArea: CustomizableUI.AREA_PANEL, - maybeDisableMenu: function(aDocument) { + maybeDisableMenu(aDocument) { let window = aDocument.defaultView; return !(window.gBrowser && window.gBrowser.selectedBrowser.mayEnableCharacterEncodingMenu); }, - populateList: function(aDocument, aContainerId, aSection) { + populateList(aDocument, aContainerId, aSection) { let containerElem = aDocument.getElementById(aContainerId); containerElem.addEventListener("command", this.onCommand, false); @@ -957,7 +957,7 @@ const CustomizableWidgets = [ containerElem.appendChild(elem); } }, - updateCurrentCharset: function(aDocument) { + updateCurrentCharset(aDocument) { let currentCharset = aDocument.defaultView.gBrowser.selectedBrowser.characterSet; currentCharset = CharsetMenu.foldCharset(currentCharset); @@ -967,7 +967,7 @@ const CustomizableWidgets = [ this._updateElements(elements, currentCharset); }, - updateCurrentDetector: function(aDocument) { + updateCurrentDetector(aDocument) { let detectorContainer = aDocument.getElementById("PanelUI-characterEncodingView-autodetect"); let currentDetector; try { @@ -977,7 +977,7 @@ const CustomizableWidgets = [ this._updateElements(detectorContainer.childNodes, currentDetector); }, - _updateElements: function(aElements, aCurrentItem) { + _updateElements(aElements, aCurrentItem) { if (!aElements.length) { return; } @@ -995,7 +995,7 @@ const CustomizableWidgets = [ } } }, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { let document = aEvent.target.ownerDocument; let autoDetectLabelId = "PanelUI-characterEncodingView-autodetect-label"; @@ -1016,7 +1016,7 @@ const CustomizableWidgets = [ this.updateCurrentDetector(document); this.updateCurrentCharset(document); }, - onCommand: function(aEvent) { + onCommand(aEvent) { let node = aEvent.target; if (!node.hasAttribute || !node.section) { return; @@ -1044,7 +1044,7 @@ const CustomizableWidgets = [ window.BrowserCharsetReload(); } }, - onCreated: function(aNode) { + onCreated(aNode) { const kPanelId = "PanelUI-popup"; let document = aNode.ownerDocument; @@ -1095,7 +1095,7 @@ const CustomizableWidgets = [ }, { id: "email-link-button", tooltiptext: "email-link-button.tooltiptext3", - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.view; win.MailIntegration.sendLinkForBrowser(win.gBrowser.selectedBrowser) } @@ -1104,7 +1104,7 @@ const CustomizableWidgets = [ type: "view", viewId: "PanelUI-containers", hasObserver: false, - onCreated: function(aNode) { + onCreated(aNode) { let doc = aNode.ownerDocument; let win = doc.defaultView; let items = doc.getElementById("PanelUI-containersItems"); @@ -1129,7 +1129,7 @@ const CustomizableWidgets = [ this.hasObserver = true; } }, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { let doc = aEvent.target.ownerDocument; let items = doc.getElementById("PanelUI-containersItems"); @@ -1187,7 +1187,7 @@ const CustomizableWidgets = [ let preferencesButton = { id: "preferences-button", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; win.openPreferences(); } @@ -1209,7 +1209,7 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { type: "view", viewId: "PanelUI-panicView", _sanitizer: null, - _ensureSanitizer: function() { + _ensureSanitizer() { if (!this.sanitizer) { let scope = {}; Services.scriptloader.loadSubScript("chrome://browser/content/sanitize.js", @@ -1219,11 +1219,11 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { this._sanitizer.ignoreTimespan = false; } }, - _getSanitizeRange: function(aDocument) { + _getSanitizeRange(aDocument) { let group = aDocument.getElementById("PanelUI-panic-timeSpan"); return this._Sanitizer.getClearRange(+group.value); }, - forgetButtonCalled: function(aEvent) { + forgetButtonCalled(aEvent) { let doc = aEvent.target.ownerDocument; this._ensureSanitizer(); this._sanitizer.range = this._getSanitizeRange(doc); @@ -1249,18 +1249,18 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { } }); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "command": this.forgetButtonCalled(aEvent); break; } }, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { let forgetButton = aEvent.target.querySelector("#PanelUI-panic-view-button"); forgetButton.addEventListener("command", this); }, - onViewHiding: function(aEvent) { + onViewHiding(aEvent) { let forgetButton = aEvent.target.querySelector("#PanelUI-panic-view-button"); forgetButton.removeEventListener("command", this); }, @@ -1272,12 +1272,12 @@ if (AppConstants.E10S_TESTING_ONLY) { CustomizableWidgets.push({ id: "e10s-button", defaultArea: CustomizableUI.AREA_PANEL, - onBuild: function(aDocument) { + onBuild(aDocument) { let node = aDocument.createElementNS(kNSXUL, "toolbarbutton"); node.setAttribute("label", CustomizableUI.getLocalizedProperty(this, "label")); node.setAttribute("tooltiptext", CustomizableUI.getLocalizedProperty(this, "tooltiptext")); }, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.view; win.OpenBrowserWindow({remote: false}); }, diff --git a/browser/components/customizableui/CustomizeMode.jsm b/browser/components/customizableui/CustomizeMode.jsm index 655756cfb2f5..888708ac65ff 100644 --- a/browser/components/customizableui/CustomizeMode.jsm +++ b/browser/components/customizableui/CustomizeMode.jsm @@ -130,13 +130,13 @@ CustomizeMode.prototype = { return this.window.CustomizationHandler; }, - uninit: function() { + uninit() { if (AppConstants.CAN_DRAW_IN_TITLEBAR) { Services.prefs.removeObserver(kDrawInTitlebarPref, this); } }, - toggle: function() { + toggle() { if (this._handler.isEnteringCustomizeMode || this._handler.isExitingCustomizeMode) { this._wantToBeInCustomizeMode = !this._wantToBeInCustomizeMode; return; @@ -148,7 +148,7 @@ CustomizeMode.prototype = { } }, - _updateLWThemeButtonIcon: function() { + _updateLWThemeButtonIcon() { let lwthemeButton = this.document.getElementById("customization-lwtheme-button"); let lwthemeIcon = this.document.getAnonymousElementByAttribute(lwthemeButton, "class", "button-icon"); @@ -156,7 +156,7 @@ CustomizeMode.prototype = { "url(" + LightweightThemeManager.currentTheme.iconURL + ")" : ""; }, - setTab: function(aTab) { + setTab(aTab) { if (gTab == aTab) { return; } @@ -186,7 +186,7 @@ CustomizeMode.prototype = { } }, - enter: function() { + enter() { this._wantToBeInCustomizeMode = true; if (this._customizing || this._handler.isEnteringCustomizeMode) { @@ -380,7 +380,7 @@ CustomizeMode.prototype = { }.bind(this)); }, - exit: function() { + exit() { this._wantToBeInCustomizeMode = false; if (!this._customizing || this._handler.isExitingCustomizeMode) { @@ -557,7 +557,7 @@ CustomizeMode.prototype = { * phases, there is a "customizing" attribute set on the main-window to simplify * excluding certain styles while in any phase of customize mode. */ - _doTransition: function(aEntering) { + _doTransition(aEntering) { let deck = this.document.getElementById("content-deck"); let customizeTransitionEndPromise = new Promise(resolve => { let customizeTransitionEnd = (aEvent) => { @@ -603,7 +603,7 @@ CustomizeMode.prototype = { return customizeTransitionEndPromise; }, - updateLWTStyling: function(aData) { + updateLWTStyling(aData) { let docElement = this.document.documentElement; if (!aData) { let lwt = docElement._lightweightTheme; @@ -654,7 +654,7 @@ CustomizeMode.prototype = { docElement.style.removeProperty("background-color"); }, - removeLWTStyling: function() { + removeLWTStyling() { let affectedNodes = AppConstants.platform == "macosx" ? ["tab-view-deck", "titlebar"] : ["tab-view-deck"]; @@ -671,11 +671,11 @@ CustomizeMode.prototype = { } }, - _getHeaderImageRef: function(aData) { + _getHeaderImageRef(aData) { return "url(\"" + aData.headerURL.replace(/"/g, '\\"') + "\")"; }, - maybeShowTip: function(aAnchor) { + maybeShowTip(aAnchor) { let shown = false; const kShownPref = "browser.customizemode.tip0.shown"; try { @@ -711,11 +711,11 @@ CustomizeMode.prototype = { Services.prefs.setBoolPref(kShownPref, true); }, - hideTip: function() { + hideTip() { this.tipPanel.hidePopup(); }, - _getCustomizableChildForNode: function(aNode) { + _getCustomizableChildForNode(aNode) { // NB: adjusted from _getCustomizableParent to keep that method fast // (it's used during drags), and avoid multiple DOM loops let areas = CustomizableUI.areas; @@ -746,7 +746,7 @@ CustomizeMode.prototype = { return null; }, - addToToolbar: function(aNode) { + addToToolbar(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -757,7 +757,7 @@ CustomizeMode.prototype = { } }, - addToPanel: function(aNode) { + addToPanel(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -768,7 +768,7 @@ CustomizeMode.prototype = { } }, - removeFromArea: function(aNode) { + removeFromArea(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -779,7 +779,7 @@ CustomizeMode.prototype = { } }, - populatePalette: function() { + populatePalette() { let fragment = this.document.createDocumentFragment(); let toolboxPalette = this.window.gNavToolbox.palette; @@ -805,7 +805,7 @@ CustomizeMode.prototype = { // Would ensure no weird interactions/event handling from original node, // and makes it possible to put this in a lazy-loaded iframe/real tab // while still getting rid of the need for overlays. - makePaletteItem: function(aWidget, aPlace) { + makePaletteItem(aWidget, aPlace) { let widgetNode = aWidget.forWindow(this.window).node; if (!widgetNode) { log.error("Widget with id " + aWidget.id + " does not return a valid node"); @@ -821,7 +821,7 @@ CustomizeMode.prototype = { return wrapper; }, - depopulatePalette: function() { + depopulatePalette() { return Task.spawn(function*() { this.visiblePalette.hidden = true; let paletteChild = this.visiblePalette.firstChild; @@ -851,7 +851,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - isCustomizableItem: function(aNode) { + isCustomizableItem(aNode) { return aNode.localName == "toolbarbutton" || aNode.localName == "toolbaritem" || aNode.localName == "toolbarseparator" || @@ -859,11 +859,11 @@ CustomizeMode.prototype = { aNode.localName == "toolbarspacer"; }, - isWrappedToolbarItem: function(aNode) { + isWrappedToolbarItem(aNode) { return aNode.localName == "toolbarpaletteitem"; }, - deferredWrapToolbarItem: function(aNode, aPlace) { + deferredWrapToolbarItem(aNode, aPlace) { return new Promise(resolve => { dispatchFunction(() => { let wrapper = this.wrapToolbarItem(aNode, aPlace); @@ -872,7 +872,7 @@ CustomizeMode.prototype = { }); }, - wrapToolbarItem: function(aNode, aPlace) { + wrapToolbarItem(aNode, aPlace) { if (!this.isCustomizableItem(aNode)) { return aNode; } @@ -890,7 +890,7 @@ CustomizeMode.prototype = { return wrapper; }, - createOrUpdateWrapper: function(aNode, aPlace, aIsUpdate) { + createOrUpdateWrapper(aNode, aPlace, aIsUpdate) { let wrapper; if (aIsUpdate && aNode.parentNode && aNode.parentNode.localName == "toolbarpaletteitem") { wrapper = aNode.parentNode; @@ -980,7 +980,7 @@ CustomizeMode.prototype = { return wrapper; }, - deferredUnwrapToolbarItem: function(aWrapper) { + deferredUnwrapToolbarItem(aWrapper) { return new Promise(resolve => { dispatchFunction(() => { let item = null; @@ -994,7 +994,7 @@ CustomizeMode.prototype = { }); }, - unwrapToolbarItem: function(aWrapper) { + unwrapToolbarItem(aWrapper) { if (aWrapper.nodeName != "toolbarpaletteitem") { return aWrapper; } @@ -1045,7 +1045,7 @@ CustomizeMode.prototype = { return toolbarItem; }, - _wrapToolbarItem: function*(aArea) { + *_wrapToolbarItem(aArea) { let target = CustomizableUI.getCustomizeTargetForArea(aArea, this.window); if (!target || this.areas.has(target)) { return null; @@ -1061,7 +1061,7 @@ CustomizeMode.prototype = { return target; }, - _wrapToolbarItemSync: function(aArea) { + _wrapToolbarItemSync(aArea) { let target = CustomizableUI.getCustomizeTargetForArea(aArea, this.window); if (!target || this.areas.has(target)) { return null; @@ -1082,13 +1082,13 @@ CustomizeMode.prototype = { return target; }, - _wrapToolbarItems: function*() { + *_wrapToolbarItems() { for (let area of CustomizableUI.areas) { yield this._wrapToolbarItem(area); } }, - _addDragHandlers: function(aTarget) { + _addDragHandlers(aTarget) { aTarget.addEventListener("dragstart", this, true); aTarget.addEventListener("dragover", this, true); aTarget.addEventListener("dragexit", this, true); @@ -1096,7 +1096,7 @@ CustomizeMode.prototype = { aTarget.addEventListener("dragend", this, true); }, - _wrapItemsInArea: function(target) { + _wrapItemsInArea(target) { for (let child of target.children) { if (this.isCustomizableItem(child)) { this.wrapToolbarItem(child, CustomizableUI.getPlaceForItem(child)); @@ -1104,7 +1104,7 @@ CustomizeMode.prototype = { } }, - _removeDragHandlers: function(aTarget) { + _removeDragHandlers(aTarget) { aTarget.removeEventListener("dragstart", this, true); aTarget.removeEventListener("dragover", this, true); aTarget.removeEventListener("dragexit", this, true); @@ -1112,7 +1112,7 @@ CustomizeMode.prototype = { aTarget.removeEventListener("dragend", this, true); }, - _unwrapItemsInArea: function(target) { + _unwrapItemsInArea(target) { for (let toolbarItem of target.children) { if (this.isWrappedToolbarItem(toolbarItem)) { this.unwrapToolbarItem(toolbarItem); @@ -1120,7 +1120,7 @@ CustomizeMode.prototype = { } }, - _unwrapToolbarItems: function() { + _unwrapToolbarItems() { return Task.spawn(function*() { for (let target of this.areas) { for (let toolbarItem of target.children) { @@ -1134,7 +1134,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - _removeExtraToolbarsIfEmpty: function() { + _removeExtraToolbarsIfEmpty() { let toolbox = this.window.gNavToolbox; for (let child of toolbox.children) { if (child.hasAttribute("customindex")) { @@ -1146,7 +1146,7 @@ CustomizeMode.prototype = { } }, - persistCurrentSets: function(aSetBeforePersisting) { + persistCurrentSets(aSetBeforePersisting) { let document = this.document; let toolbars = document.querySelectorAll("toolbar[customizable='true'][currentset]"); for (let toolbar of toolbars) { @@ -1159,7 +1159,7 @@ CustomizeMode.prototype = { } }, - reset: function() { + reset() { this.resetting = true; // Disable the reset button temporarily while resetting: let btn = this.document.getElementById("customization-reset-button"); @@ -1190,7 +1190,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - undoReset: function() { + undoReset() { this.resetting = true; return Task.spawn(function*() { @@ -1214,7 +1214,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - _onToolbarVisibilityChange: function(aEvent) { + _onToolbarVisibilityChange(aEvent) { let toolbar = aEvent.target; if (aEvent.detail.visible && toolbar.getAttribute("customizable") == "true") { toolbar.setAttribute("customizing", "true"); @@ -1225,19 +1225,19 @@ CustomizeMode.prototype = { this.updateLWTStyling(); }, - onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { this._onUIChange(); }, - onWidgetAdded: function(aWidgetId, aArea, aPosition) { + onWidgetAdded(aWidgetId, aArea, aPosition) { this._onUIChange(); }, - onWidgetRemoved: function(aWidgetId, aArea) { + onWidgetRemoved(aWidgetId, aArea) { this._onUIChange(); }, - onWidgetBeforeDOMChange: function(aNodeToChange, aSecondaryNode, aContainer) { + onWidgetBeforeDOMChange(aNodeToChange, aSecondaryNode, aContainer) { if (aContainer.ownerGlobal != this.window || this.resetting) { return; } @@ -1254,7 +1254,7 @@ CustomizeMode.prototype = { } }, - onWidgetAfterDOMChange: function(aNodeToChange, aSecondaryNode, aContainer) { + onWidgetAfterDOMChange(aNodeToChange, aSecondaryNode, aContainer) { if (aContainer.ownerGlobal != this.window || this.resetting) { return; } @@ -1284,7 +1284,7 @@ CustomizeMode.prototype = { } }, - onWidgetDestroyed: function(aWidgetId) { + onWidgetDestroyed(aWidgetId) { let wrapper = this.document.getElementById("wrapper-" + aWidgetId); if (wrapper) { let wasInPanel = wrapper.parentNode == this.panelUIContents; @@ -1295,7 +1295,7 @@ CustomizeMode.prototype = { } }, - onWidgetAfterCreation: function(aWidgetId, aArea) { + onWidgetAfterCreation(aWidgetId, aArea) { // If the node was added to an area, we would have gotten an onWidgetAdded notification, // plus associated DOM change notifications, so only do stuff for the palette: if (!aArea) { @@ -1309,7 +1309,7 @@ CustomizeMode.prototype = { } }, - onAreaNodeRegistered: function(aArea, aContainer) { + onAreaNodeRegistered(aArea, aContainer) { if (aContainer.ownerDocument == this.document) { this._wrapItemsInArea(aContainer); this._addDragHandlers(aContainer); @@ -1318,7 +1318,7 @@ CustomizeMode.prototype = { } }, - onAreaNodeUnregistered: function(aArea, aContainer, aReason) { + onAreaNodeUnregistered(aArea, aContainer, aReason) { if (aContainer.ownerDocument == this.document && aReason == CustomizableUI.REASON_AREA_UNREGISTERED) { this._unwrapItemsInArea(aContainer); this._removeDragHandlers(aContainer); @@ -1327,18 +1327,18 @@ CustomizeMode.prototype = { } }, - openAddonsManagerThemes: function(aEvent) { + openAddonsManagerThemes(aEvent) { aEvent.target.parentNode.parentNode.hidePopup(); this.window.BrowserOpenAddonsMgr('addons://list/theme'); }, - getMoreThemes: function(aEvent) { + getMoreThemes(aEvent) { aEvent.target.parentNode.parentNode.hidePopup(); let getMoreURL = Services.urlFormatter.formatURLPref("lightweightThemes.getMoreURL"); this.window.openUILinkIn(getMoreURL, "tab"); }, - onLWThemesMenuShowing: function(aEvent) { + onLWThemesMenuShowing(aEvent) { const DEFAULT_THEME_ID = "{972ce4c6-7e08-4474-a285-3208198ce6fd}"; const RECENT_LWT_COUNT = 5; @@ -1443,7 +1443,7 @@ CustomizeMode.prototype = { }.bind(this)); }, - _clearLWThemesMenu: function(panel) { + _clearLWThemesMenu(panel) { let footer = this.document.getElementById("customization-lwtheme-menu-footer"); let recommendedLabel = this.document.getElementById("customization-lwtheme-menu-recommended"); for (let element of [footer, recommendedLabel]) { @@ -1457,7 +1457,7 @@ CustomizeMode.prototype = { panel.removeAttribute("height"); }, - _onUIChange: function() { + _onUIChange() { this._changed = true; if (!this.resetting) { this._updateResetButton(); @@ -1467,22 +1467,22 @@ CustomizeMode.prototype = { CustomizableUI.dispatchToolboxEvent("customizationchange"); }, - _updateEmptyPaletteNotice: function() { + _updateEmptyPaletteNotice() { let paletteItems = this.visiblePalette.getElementsByTagName("toolbarpaletteitem"); this.paletteEmptyNotice.hidden = !!paletteItems.length; }, - _updateResetButton: function() { + _updateResetButton() { let btn = this.document.getElementById("customization-reset-button"); btn.disabled = CustomizableUI.inDefaultState; }, - _updateUndoResetButton: function() { + _updateUndoResetButton() { let undoResetButton = this.document.getElementById("customization-undo-reset-button"); undoResetButton.hidden = !CustomizableUI.canUndoReset; }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "toolbarvisibilitychange": this._onToolbarVisibilityChange(aEvent); @@ -1525,7 +1525,7 @@ CustomizeMode.prototype = { } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "nsPref:changed": this._updateResetButton(); @@ -1547,7 +1547,7 @@ CustomizeMode.prototype = { } }, - _updateTitlebarButton: function() { + _updateTitlebarButton() { if (!AppConstants.CAN_DRAW_IN_TITLEBAR) { return; } @@ -1564,7 +1564,7 @@ CustomizeMode.prototype = { } }, - toggleTitlebar: function(aShouldShowTitlebar) { + toggleTitlebar(aShouldShowTitlebar) { if (!AppConstants.CAN_DRAW_IN_TITLEBAR) { return; } @@ -1572,7 +1572,7 @@ CustomizeMode.prototype = { Services.prefs.setBoolPref(kDrawInTitlebarPref, !aShouldShowTitlebar); }, - _onDragStart: function(aEvent) { + _onDragStart(aEvent) { __dumpDragData(aEvent); let item = aEvent.target; while (item && item.localName != "toolbarpaletteitem") { @@ -1629,7 +1629,7 @@ CustomizeMode.prototype = { this._dragInitializeTimeout = this.window.setTimeout(this._initializeDragAfterMove, 0); }, - _onDragOver: function(aEvent) { + _onDragOver(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1726,7 +1726,7 @@ CustomizeMode.prototype = { aEvent.stopPropagation(); }, - _onDragDrop: function(aEvent) { + _onDragDrop(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1779,7 +1779,7 @@ CustomizeMode.prototype = { this._showPanelCustomizationPlaceholders(); }, - _applyDrop: function(aEvent, aTargetArea, aOriginArea, aDraggedItemId, aTargetNode) { + _applyDrop(aEvent, aTargetArea, aOriginArea, aDraggedItemId, aTargetNode) { let document = aEvent.target.ownerDocument; let draggedItem = document.getElementById(aDraggedItemId); draggedItem.hidden = false; @@ -1908,7 +1908,7 @@ CustomizeMode.prototype = { } }, - _onDragExit: function(aEvent) { + _onDragExit(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1929,7 +1929,7 @@ CustomizeMode.prototype = { /** * To workaround bug 460801 we manually forward the drop event here when dragend wouldn't be fired. */ - _onDragEnd: function(aEvent) { + _onDragEnd(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1966,7 +1966,7 @@ CustomizeMode.prototype = { DragPositionManager.stop(); }, - _isUnwantedDragDrop: function(aEvent) { + _isUnwantedDragDrop(aEvent) { // The simulated events generated by synthesizeDragStart/synthesizeDrop in // mochitests are used only for testing whether the right data is being put // into the dataTransfer. Neither cause a real drop to occur, so they don't @@ -1985,7 +1985,7 @@ CustomizeMode.prototype = { mozSourceNode.ownerGlobal != this.window; }, - _setDragActive: function(aItem, aValue, aDraggedItemId, aInToolbar) { + _setDragActive(aItem, aValue, aDraggedItemId, aInToolbar) { if (!aItem) { return; } @@ -2033,7 +2033,7 @@ CustomizeMode.prototype = { } } }, - _cancelDragActive: function(aItem, aNextItem, aNoTransition) { + _cancelDragActive(aItem, aNextItem, aNoTransition) { this._updateToolbarCustomizationOutline(aItem.ownerGlobal); let currentArea = this._getCustomizableParent(aItem); if (!currentArea) { @@ -2069,7 +2069,7 @@ CustomizeMode.prototype = { } }, - _setGridDragActive: function(aDragOverNode, aDraggedItem, aValue) { + _setGridDragActive(aDragOverNode, aDraggedItem, aValue) { let targetArea = this._getCustomizableParent(aDragOverNode); let draggedWrapper = this.document.getElementById("wrapper-" + aDraggedItem.id); let originArea = this._getCustomizableParent(draggedWrapper); @@ -2080,7 +2080,7 @@ CustomizeMode.prototype = { originArea == targetArea); }, - _getDragItemSize: function(aDragOverNode, aDraggedItem) { + _getDragItemSize(aDragOverNode, aDraggedItem) { // Cache it good, cache it real good. if (!this._dragSizeMap) this._dragSizeMap = new WeakMap(); @@ -2140,7 +2140,7 @@ CustomizeMode.prototype = { return size; }, - _getCustomizableParent: function(aElement) { + _getCustomizableParent(aElement) { let areas = CustomizableUI.areas; areas.push(kPaletteId); while (aElement) { @@ -2152,7 +2152,7 @@ CustomizeMode.prototype = { return null; }, - _getDragOverNode: function(aEvent, aAreaElement, aInToolbar, aDraggedItemId) { + _getDragOverNode(aEvent, aAreaElement, aInToolbar, aDraggedItemId) { let expectedParent = aAreaElement.customizationTarget || aAreaElement; // Our tests are stupid. Cope: if (!aEvent.clientX && !aEvent.clientY) { @@ -2200,7 +2200,7 @@ CustomizeMode.prototype = { return targetNode || aEvent.target; }, - _onMouseDown: function(aEvent) { + _onMouseDown(aEvent) { log.debug("_onMouseDown"); if (aEvent.button != 0) { return; @@ -2214,7 +2214,7 @@ CustomizeMode.prototype = { } }, - _onMouseUp: function(aEvent) { + _onMouseUp(aEvent) { log.debug("_onMouseUp"); if (aEvent.button != 0) { return; @@ -2227,7 +2227,7 @@ CustomizeMode.prototype = { } }, - _getWrapper: function(aElement) { + _getWrapper(aElement) { while (aElement && aElement.localName != "toolbarpaletteitem") { if (aElement.localName == "toolbar") return null; @@ -2236,7 +2236,7 @@ CustomizeMode.prototype = { return aElement; }, - _showPanelCustomizationPlaceholders: function() { + _showPanelCustomizationPlaceholders() { let doc = this.document; let contents = this.panelUIContents; let narrowItemsAfterWideItem = 0; @@ -2271,7 +2271,7 @@ CustomizeMode.prototype = { } }, - _removePanelCustomizationPlaceholders: function() { + _removePanelCustomizationPlaceholders() { let contents = this.panelUIContents; let oldPlaceholders = contents.getElementsByClassName(kPlaceholderClass); while (oldPlaceholders.length) { @@ -2288,7 +2288,7 @@ CustomizeMode.prototype = { * outline to. If aToolbarArea is falsy, the outline will be * removed from all toolbar areas. */ - _updateToolbarCustomizationOutline: function(aWindow, aToolbarArea = null) { + _updateToolbarCustomizationOutline(aWindow, aToolbarArea = null) { // Remove the attribute from existing customization targets for (let area of CustomizableUI.areas) { if (CustomizableUI.getAreaType(area) != CustomizableUI.TYPE_TOOLBAR) { @@ -2307,7 +2307,7 @@ CustomizeMode.prototype = { } }, - _findVisiblePreviousSiblingNode: function(aReferenceNode) { + _findVisiblePreviousSiblingNode(aReferenceNode) { while (aReferenceNode && aReferenceNode.localName == "toolbarpaletteitem" && aReferenceNode.firstChild.hidden) { diff --git a/browser/components/customizableui/DragPositionManager.jsm b/browser/components/customizableui/DragPositionManager.jsm index 1b4eb59dc15f..65e2585a5a81 100644 --- a/browser/components/customizableui/DragPositionManager.jsm +++ b/browser/components/customizableui/DragPositionManager.jsm @@ -33,7 +33,7 @@ AreaPositionManager.prototype = { _nodePositionStore: null, _wideCache: null, - update: function(aContainer) { + update(aContainer) { this._nodePositionStore = new WeakMap(); this._wideCache = new Set(); let last = null; @@ -73,7 +73,7 @@ AreaPositionManager.prototype = { * where dy is more heavily weighted by a factor corresponding to the * ratio between the container's width and the height of its elements. */ - find: function(aContainer, aX, aY, aDraggedItemId) { + find(aContainer, aX, aY, aDraggedItemId) { let closest = null; let minCartesian = Number.MAX_VALUE; let containerX = this._containerInfo.left; @@ -130,7 +130,7 @@ AreaPositionManager.prototype = { * they would have if we had inserted something before aBefore. We use CSS * transforms for this, which are CSS transitioned. */ - insertPlaceholder: function(aContainer, aBefore, aWide, aSize, aIsFromThisArea) { + insertPlaceholder(aContainer, aBefore, aWide, aSize, aIsFromThisArea) { let isShifted = false; let shiftDown = aWide; for (let child of aContainer.children) { @@ -185,11 +185,11 @@ AreaPositionManager.prototype = { this._lastPlaceholderInsertion = aBefore; }, - isWide: function(aNode) { + isWide(aNode) { return this._wideCache.has(aNode.id); }, - _checkIfWide: function(aNode) { + _checkIfWide(aNode) { return this._inPanel && aNode && aNode.firstChild && aNode.firstChild.classList.contains(CustomizableUI.WIDE_PANEL_CLASS); }, @@ -201,7 +201,7 @@ AreaPositionManager.prototype = { * @param aNoTransition if truthy, adds a notransition attribute to the node * while resetting the transform. */ - clearPlaceholders: function(aContainer, aNoTransition) { + clearPlaceholders(aContainer, aNoTransition) { for (let child of aContainer.children) { if (aNoTransition) { child.setAttribute("notransition", true); @@ -220,7 +220,7 @@ AreaPositionManager.prototype = { } }, - _getNextPos: function(aNode, aShiftDown, aSize) { + _getNextPos(aNode, aShiftDown, aSize) { // Shifting down is easy: if (this._inPanel && aShiftDown) { return "translate(0, " + aSize.height + "px)"; @@ -228,7 +228,7 @@ AreaPositionManager.prototype = { return this._diffWithNext(aNode, aSize); }, - _diffWithNext: function(aNode, aSize) { + _diffWithNext(aNode, aSize) { let xDiff; let yDiff = null; let nodeBounds = this._lazyStoreGet(aNode); @@ -306,7 +306,7 @@ AreaPositionManager.prototype = { * @param aNodeBounds the bounding rect info of this node * @param aFirstNodeInRow the first node in aNode's row */ - _moveNextBasedOnPrevious: function(aNode, aNodeBounds, aFirstNodeInRow) { + _moveNextBasedOnPrevious(aNode, aNodeBounds, aFirstNodeInRow) { let next = this._getVisibleSiblingForDirection(aNode, "previous"); let otherBounds = this._lazyStoreGet(next); let side = this._dir == "ltr" ? "left" : "right"; @@ -328,7 +328,7 @@ AreaPositionManager.prototype = { * @param aNode the node whose position info we want * @return the position info */ - _lazyStoreGet: function(aNode) { + _lazyStoreGet(aNode) { let rect = this._nodePositionStore.get(aNode); if (!rect) { // getBoundingClientRect() returns a DOMRect that is live, meaning that @@ -352,7 +352,7 @@ AreaPositionManager.prototype = { return rect; }, - _firstInRow: function(aNode) { + _firstInRow(aNode) { // XXXmconley: I'm not entirely sure why we need to take the floor of these // values - it looks like, periodically, we're getting fractional pixels back // from lazyStoreGet. I've filed bug 994247 to investigate. @@ -368,7 +368,7 @@ AreaPositionManager.prototype = { return rv; }, - _getVisibleSiblingForDirection: function(aNode, aDirection) { + _getVisibleSiblingForDirection(aNode, aDirection) { let rv = aNode; do { rv = rv[aDirection + "Sibling"]; @@ -378,7 +378,7 @@ AreaPositionManager.prototype = { } var DragPositionManager = { - start: function(aWindow) { + start(aWindow) { let areas = CustomizableUI.areas.filter((area) => CustomizableUI.getAreaType(area) != "toolbar"); areas = areas.map((area) => CustomizableUI.getCustomizeTargetForArea(area, aWindow)); areas.push(aWindow.document.getElementById(kPaletteId)); @@ -392,7 +392,7 @@ var DragPositionManager = { } }, - add: function(aWindow, aArea, aContainer) { + add(aWindow, aArea, aContainer) { if (CustomizableUI.getAreaType(aArea) != "toolbar") { return; } @@ -400,7 +400,7 @@ var DragPositionManager = { gManagers.set(aContainer, new AreaPositionManager(aContainer)); }, - remove: function(aWindow, aArea, aContainer) { + remove(aWindow, aArea, aContainer) { if (CustomizableUI.getAreaType(aArea) != "toolbar") { return; } @@ -408,11 +408,11 @@ var DragPositionManager = { gManagers.delete(aContainer); }, - stop: function() { + stop() { gManagers = new WeakMap(); }, - getManagerForArea: function(aArea) { + getManagerForArea(aArea) { return gManagers.get(aArea); } }; diff --git a/browser/components/customizableui/PanelWideWidgetTracker.jsm b/browser/components/customizableui/PanelWideWidgetTracker.jsm index 768cebbca73e..a9b38c23eb26 100644 --- a/browser/components/customizableui/PanelWideWidgetTracker.jsm +++ b/browser/components/customizableui/PanelWideWidgetTracker.jsm @@ -22,33 +22,33 @@ var gSeenWidgets = new Set(); var PanelWideWidgetTracker = { // Listeners used to validate panel contents whenever they change: - onWidgetAdded: function(aWidgetId, aArea, aPosition) { + onWidgetAdded(aWidgetId, aArea, aPosition) { if (aArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); let moveForward = this.shouldMoveForward(aWidgetId, aPosition); this.adjustWidgets(aWidgetId, moveForward); } }, - onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { if (aArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); let moveForward = this.shouldMoveForward(aWidgetId, aNewPosition); this.adjustWidgets(aWidgetId, moveForward); } }, - onWidgetRemoved: function(aWidgetId, aPrevArea) { + onWidgetRemoved(aWidgetId, aPrevArea) { if (aPrevArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); this.adjustWidgets(aWidgetId, false); } }, - onWidgetReset: function(aWidgetId) { + onWidgetReset(aWidgetId) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); }, // Listener to keep abreast of any new nodes. We use the DOM one because // we need access to the actual node's classlist, so we can't use the ones above. // Furthermore, onWidgetCreated only fires for API-based widgets, not for XUL ones. - onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer) { + onWidgetAfterDOMChange(aNode, aNextNode, aContainer) { if (!gSeenWidgets.has(aNode.id)) { if (aNode.classList.contains(CustomizableUI.WIDE_PANEL_CLASS)) { gWideWidgets.add(aNode.id); @@ -57,11 +57,11 @@ var PanelWideWidgetTracker = { } }, // When widgets get destroyed, we remove them from our sets of stuff we care about: - onWidgetDestroyed: function(aWidgetId) { + onWidgetDestroyed(aWidgetId) { gSeenWidgets.delete(aWidgetId); gWideWidgets.delete(aWidgetId); }, - shouldMoveForward: function(aWidgetId, aPosition) { + shouldMoveForward(aWidgetId, aPosition) { let currentWidgetAtPosition = gPanelPlacements[aPosition + 1]; let rv = gWideWidgets.has(currentWidgetAtPosition) && !gWideWidgets.has(aWidgetId); // We might now think we can move forward, but for that we need at least 2 more small @@ -83,7 +83,7 @@ var PanelWideWidgetTracker = { } return rv; }, - adjustWidgets: function(aWidgetId, aMoveForwards) { + adjustWidgets(aWidgetId, aMoveForwards) { if (this.adjusting) { return; } @@ -104,7 +104,7 @@ var PanelWideWidgetTracker = { // This function is called whenever an item gets moved in the menu panel. It // adjusts the position of widgets within the panel to prevent "gaps" between // wide widgets that could be filled up with single column widgets - adjustPosition: function(aWidgetId, aMoveForwards) { + adjustPosition(aWidgetId, aMoveForwards) { // Make sure that there are n % columns = 0 narrow buttons before the widget. let placementIndex = gPanelPlacements.indexOf(aWidgetId); let prevSiblingCount = 0; @@ -144,7 +144,7 @@ var PanelWideWidgetTracker = { * "public-only" if it's not shown in private windows * "real" if it does exist and is shown even in private windows */ - checkWidgetStatus: function(aWidgetId) { + checkWidgetStatus(aWidgetId) { let widgetWrapper = CustomizableUI.getWidget(aWidgetId); // This widget might not actually exist: if (!widgetWrapper) { @@ -164,7 +164,7 @@ var PanelWideWidgetTracker = { return "real"; }, - init: function() { + init() { // Initialize our local placements copy and register the listener gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); CustomizableUI.addListener(this); diff --git a/browser/components/customizableui/ScrollbarSampler.jsm b/browser/components/customizableui/ScrollbarSampler.jsm index 44736e4c4e08..5a2bfd3e07d7 100644 --- a/browser/components/customizableui/ScrollbarSampler.jsm +++ b/browser/components/customizableui/ScrollbarSampler.jsm @@ -14,7 +14,7 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm"); var gSystemScrollbarWidth = null; this.ScrollbarSampler = { - getSystemScrollbarWidth: function() { + getSystemScrollbarWidth() { if (gSystemScrollbarWidth !== null) { return Promise.resolve(gSystemScrollbarWidth); } @@ -27,11 +27,11 @@ this.ScrollbarSampler = { }); }, - resetSystemScrollbarWidth: function() { + resetSystemScrollbarWidth() { gSystemScrollbarWidth = null; }, - _sampleSystemScrollbarWidth: function() { + _sampleSystemScrollbarWidth() { let hwin = Services.appShell.hiddenDOMWindow; let hdoc = hwin.document.documentElement; let iframe = hwin.document.createElementNS("http://www.w3.org/1999/xhtml", diff --git a/browser/components/customizableui/content/panelUI.js b/browser/components/customizableui/content/panelUI.js index 112e2e72f935..173f788b0011 100644 --- a/browser/components/customizableui/content/panelUI.js +++ b/browser/components/customizableui/content/panelUI.js @@ -37,7 +37,7 @@ const PanelUI = { }, _initialized: false, - init: function() { + init() { for (let [k, v] of Object.entries(this.kElements)) { // Need to do fresh let-bindings per iteration let getKey = k; @@ -57,13 +57,13 @@ const PanelUI = { }, _eventListenersAdded: false, - _ensureEventListenersAdded: function() { + _ensureEventListenersAdded() { if (this._eventListenersAdded) return; this._addEventListeners(); }, - _addEventListeners: function() { + _addEventListeners() { for (let event of this.kEvents) { this.panel.addEventListener(event, this); } @@ -72,7 +72,7 @@ const PanelUI = { this._eventListenersAdded = true; }, - uninit: function() { + uninit() { for (let event of this.kEvents) { this.panel.removeEventListener(event, this); } @@ -92,7 +92,7 @@ const PanelUI = { * @param aMainView * The mainView node to put back into place. */ - setMainView: function(aMainView) { + setMainView(aMainView) { this._ensureEventListenersAdded(); this.multiView.setMainView(aMainView); }, @@ -103,7 +103,7 @@ const PanelUI = { * * @param aEvent the event that triggers the toggle. */ - toggle: function(aEvent) { + toggle(aEvent) { // Don't show the panel if the window is in customization mode, // since this button doubles as an exit path for the user in this case. if (document.documentElement.hasAttribute("customizing")) { @@ -124,7 +124,7 @@ const PanelUI = { * * @param aEvent the event (if any) that triggers showing the menu. */ - show: function(aEvent) { + show(aEvent) { return new Promise(resolve => { this.ensureReady().then(() => { if (this.panel.state == "open" || @@ -170,7 +170,7 @@ const PanelUI = { /** * If the menu panel is being shown, hide it. */ - hide: function() { + hide() { if (document.documentElement.hasAttribute("customizing")) { return; } @@ -178,7 +178,7 @@ const PanelUI = { this.panel.hidePopup(); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { // Ignore context menus and menu button menus showing and hiding: if (aEvent.type.startsWith("popup") && aEvent.target != this.panel) { @@ -221,7 +221,7 @@ const PanelUI = { * * @return a Promise that resolves once the panel is ready to roll. */ - ensureReady: function(aCustomizing = false) { + ensureReady(aCustomizing = false) { if (this._readyPromise) { return this._readyPromise; } @@ -282,7 +282,7 @@ const PanelUI = { * Switch the panel to the main view if it's not already * in that view. */ - showMainView: function() { + showMainView() { this._ensureEventListenersAdded(); this.multiView.showMainView(); }, @@ -291,7 +291,7 @@ const PanelUI = { * Switch the panel to the help view if it's not already * in that view. */ - showHelpView: function(aAnchor) { + showHelpView(aAnchor) { this._ensureEventListenersAdded(); this.multiView.showSubView("PanelUI-helpView", aAnchor); }, @@ -410,15 +410,15 @@ const PanelUI = { * affect the hiding/showing animations of single-subview panels (tempPanel * in the showSubView method). */ - disableSingleSubviewPanelAnimations: function() { + disableSingleSubviewPanelAnimations() { this._disableAnimations = true; }, - enableSingleSubviewPanelAnimations: function() { + enableSingleSubviewPanelAnimations() { this._disableAnimations = false; }, - onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer, aWasRemoval) { + onWidgetAfterDOMChange(aNode, aNextNode, aContainer, aWasRemoval) { if (aContainer != this.contents) { return; } @@ -427,7 +427,7 @@ const PanelUI = { } }, - onWidgetBeforeDOMChange: function(aNode, aNextNode, aContainer, aIsRemoval) { + onWidgetBeforeDOMChange(aNode, aNextNode, aContainer, aIsRemoval) { if (aContainer != this.contents) { return; } @@ -442,7 +442,7 @@ const PanelUI = { * Signal that we're about to make a lot of changes to the contents of the * panels all at once. For performance, we ignore the mutations. */ - beginBatchUpdate: function() { + beginBatchUpdate() { this._ensureEventListenersAdded(); this.multiView.ignoreMutations = true; }, @@ -452,12 +452,12 @@ const PanelUI = { * attention to mutations. This automatically synchronizes the multiview * container with whichever view is displayed if the panel is open. */ - endBatchUpdate: function(aReason) { + endBatchUpdate(aReason) { this._ensureEventListenersAdded(); this.multiView.ignoreMutations = false; }, - _adjustLabelsForAutoHyphens: function(aNode) { + _adjustLabelsForAutoHyphens(aNode) { let toolbarButtons = aNode ? [aNode] : this.contents.querySelectorAll(".toolbarbutton-1"); for (let node of toolbarButtons) { @@ -477,12 +477,12 @@ const PanelUI = { * Sets the anchor node into the open or closed state, depending * on the state of the panel. */ - _updatePanelButton: function() { + _updatePanelButton() { this.menuButton.open = this.panel.state == "open" || this.panel.state == "showing"; }, - _onHelpViewShow: function(aEvent) { + _onHelpViewShow(aEvent) { // Call global menu setup function buildHelpMenu(); @@ -515,7 +515,7 @@ const PanelUI = { items.appendChild(fragment); }, - _updateQuitTooltip: function() { + _updateQuitTooltip() { if (AppConstants.platform == "win") { return; } @@ -535,7 +535,7 @@ const PanelUI = { }, _overlayScrollListenerBoundFn: null, - _overlayScrollListener: function(aMQL) { + _overlayScrollListener(aMQL) { ScrollbarSampler.resetSystemScrollbarWidth(); this._scrollWidth = null; }, diff --git a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js b/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js index 22fbb5c0c227..5545c3fd0e9c 100644 --- a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js +++ b/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js @@ -12,7 +12,7 @@ function simulateItemDragAndEnd(aToDrag, aTarget) { var [result, dataTransfer] = EventUtils.synthesizeDragOver(aToDrag.parentNode, aTarget); EventUtils.synthesizeDropAfterDragOver(result, dataTransfer, aTarget); // Send dragend to move dragging item back to initial place. - EventUtils.sendDragEvent({ type: "dragend", dataTransfer: dataTransfer }, + EventUtils.sendDragEvent({ type: "dragend", dataTransfer }, aToDrag.parentNode); } finally { ds.endDragSession(true); diff --git a/browser/components/customizableui/test/browser_877006_missing_view.js b/browser/components/customizableui/test/browser_877006_missing_view.js index a1495c1feda4..b16775d5bb17 100644 --- a/browser/components/customizableui/test/browser_877006_missing_view.js +++ b/browser/components/customizableui/test/browser_877006_missing_view.js @@ -12,7 +12,7 @@ add_task(function testAddbrokenViewWidget() { type: 'view', viewId: 'idontexist', /* Empty handler so we try to attach it maybe? */ - onViewShowing: function() { + onViewShowing() { } }; diff --git a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js index 61adac9826f3..d19eed775e60 100644 --- a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js +++ b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js @@ -15,7 +15,7 @@ add_task(function*() { for (let i = 0; i < kTestWidgetCount; i++) { let id = kTestWidgetPfx + i; widgetIds.push(id); - let spec = {id: id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i}; + let spec = {id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } for (let i = kTestWidgetCount; i < kTestWidgetCount * 2; i++) { diff --git a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js b/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js index c2006bef048d..45b90d9e7a0a 100644 --- a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js +++ b/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js @@ -14,7 +14,7 @@ add_task(function*() { let privateWindow = null; let observerWindowOpened = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { privateWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow); privateWindow.addEventListener("load", function newWindowHandler() { diff --git a/browser/components/customizableui/test/browser_947914_button_newWindow.js b/browser/components/customizableui/test/browser_947914_button_newWindow.js index 47162ee86147..9c3f08c93abe 100644 --- a/browser/components/customizableui/test/browser_947914_button_newWindow.js +++ b/browser/components/customizableui/test/browser_947914_button_newWindow.js @@ -13,7 +13,7 @@ add_task(function*() { let newWindow = null; let observerWindowOpened = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { newWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow); newWindow.addEventListener("load", function newWindowHandler() { diff --git a/browser/components/customizableui/test/browser_973641_button_addon.js b/browser/components/customizableui/test/browser_973641_button_addon.js index 796bf3d0ecad..8d7198dc1646 100755 --- a/browser/components/customizableui/test/browser_973641_button_addon.js +++ b/browser/components/customizableui/test/browser_973641_button_addon.js @@ -14,7 +14,7 @@ add_task(function*() { let widgetSpec = { id: kButton, type: 'button', - onClick: function() { + onClick() { gBrowser.selectedTab = gBrowser.addTab("about:addons"); } }; diff --git a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js b/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js index 3bfa8c25d57f..d6ed3c205278 100644 --- a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js +++ b/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js @@ -20,7 +20,7 @@ add_task(function*() { let id = kTestWidgetPrefix + i; widgetIds.push(id); if (testWidgetExists[i]) { - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } } @@ -57,7 +57,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -106,7 +106,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -156,7 +156,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -207,7 +207,7 @@ add_task(function*() { for (let i = 5; i >= 0; i--) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar", 0); } @@ -215,7 +215,7 @@ add_task(function*() { for (let i = 10; i < 15; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -269,8 +269,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated(node) { node.style.minWidth = "200px"; if (id == (kTestWidgetPrefix + nonOverflowableId)) { node.setAttribute("overflows", false); @@ -325,8 +325,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { node.style.minWidth = "100px"; }}; + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated(node) { node.style.minWidth = "100px"; }}; info("Creating: " + id); CustomizableUI.createWidget(spec); } @@ -374,8 +374,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { node.style.minWidth = "200px"; }}; + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated(node) { node.style.minWidth = "200px"; }}; info("Creating: " + id); CustomizableUI.createWidget(spec); } diff --git a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js b/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js index 15197ac86f12..fafbc93592c1 100644 --- a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js +++ b/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js @@ -14,7 +14,7 @@ add_task(function* addOverflowingToolbar() { for (let i = 0; i < 10; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } diff --git a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js index 9a7227a47b6b..1f27e604ae3d 100644 --- a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js +++ b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js @@ -13,7 +13,7 @@ add_task(function* testAddOnBeforeCreatedWidget() { id: kWidgetId, type: 'view', viewId: kWidgetId + 'idontexistyet', - onBeforeCreated: function(doc) { + onBeforeCreated(doc) { let view = doc.createElement("panelview"); view.id = kWidgetId + 'idontexistyet'; let label = doc.createElement("label"); @@ -23,7 +23,7 @@ add_task(function* testAddOnBeforeCreatedWidget() { document.getElementById("PanelUI-multiView").appendChild(view); onBeforeCreatedCalled = true; }, - onViewShowing: function() { + onViewShowing() { viewShownDeferred.resolve(); } }; diff --git a/browser/components/customizableui/test/browser_987492_window_api.js b/browser/components/customizableui/test/browser_987492_window_api.js index 104a14ba6d98..2fccd1b5b82f 100644 --- a/browser/components/customizableui/test/browser_987492_window_api.js +++ b/browser/components/customizableui/test/browser_987492_window_api.js @@ -16,7 +16,7 @@ add_task(function* testOneWindow() { add_task(function* testOpenCloseWindow() { let newWindow = null; let openListener = { - onWindowOpened: function(window) { + onWindowOpened(window) { newWindow = window; } } @@ -39,7 +39,7 @@ add_task(function* testOpenCloseWindow() { let closedWindow = null; let closeListener = { - onWindowClosed: function(window) { + onWindowClosed(window) { closedWindow = window; } } diff --git a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js b/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js index 4d292a929c67..a8790f539869 100644 --- a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js +++ b/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js @@ -65,7 +65,7 @@ add_task(function*() { otherTB.setAttribute("customizable", "true"); let wasInformedCorrectlyOfAreaAppearing = false; let listener = { - onAreaNodeRegistered: function(aArea, aNode) { + onAreaNodeRegistered(aArea, aNode) { if (aNode == otherTB) { wasInformedCorrectlyOfAreaAppearing = true; } @@ -99,14 +99,14 @@ add_task(function*() { // (and therefore onAreaNodeRegistered) one, causing the test to fail. let windowCloseDeferred = Promise.defer(); listener = { - onAreaNodeUnregistered: function(aArea, aNode, aReason) { + onAreaNodeUnregistered(aArea, aNode, aReason) { if (aArea == TOOLBARID) { is(aNode, otherTB, "Should be informed about other toolbar"); is(aReason, CustomizableUI.REASON_WINDOW_CLOSED, "Reason should be correct."); wasInformedCorrectlyOfAreaDisappearing = (aReason === CustomizableUI.REASON_WINDOW_CLOSED); } }, - onWindowClosed: function(aWindow) { + onWindowClosed(aWindow) { if (aWindow == otherWin) { windowCloseDeferred.resolve(aWindow); } else { @@ -133,7 +133,7 @@ add_task(function*() { CustomizableUI.removeListener(listener); wasInformedCorrectlyOfAreaDisappearing = false; listener = { - onAreaNodeUnregistered: function(aArea, aNode, aReason) { + onAreaNodeUnregistered(aArea, aNode, aReason) { if (aArea == TOOLBARID) { is(aNode, toolbar, "Should be informed about this window's toolbar"); is(aReason, CustomizableUI.REASON_AREA_UNREGISTERED, "Reason for final removal should be correct."); diff --git a/browser/components/migration/360seProfileMigrator.js b/browser/components/migration/360seProfileMigrator.js index 42347d542a68..83e2880b132b 100644 --- a/browser/components/migration/360seProfileMigrator.js +++ b/browser/components/migration/360seProfileMigrator.js @@ -209,7 +209,7 @@ function Qihoo360seProfileMigrator() { Qihoo360seProfileMigrator.prototype = Object.create(MigratorPrototype); Object.defineProperty(Qihoo360seProfileMigrator.prototype, "sourceProfiles", { - get: function() { + get() { if ("__sourceProfiles" in this) return this.__sourceProfiles; diff --git a/browser/components/migration/ChromeProfileMigrator.js b/browser/components/migration/ChromeProfileMigrator.js index 2446f713ca20..ee99db3ca626 100644 --- a/browser/components/migration/ChromeProfileMigrator.js +++ b/browser/components/migration/ChromeProfileMigrator.js @@ -246,7 +246,7 @@ function GetBookmarksResource(aProfileFolder) { return { type: MigrationUtils.resourceTypes.BOOKMARKS, - migrate: function(aCallback) { + migrate(aCallback) { return Task.spawn(function* () { let gotErrors = false; let errorGatherer = function() { gotErrors = true }; @@ -341,12 +341,12 @@ function GetHistoryResource(aProfileFolder) { yield new Promise((resolve, reject) => { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult: function() { + handleResult() { // Importing any entry is considered a successful import. this._success = true; }, - handleError: function() {}, - handleCompletion: function() { + handleError() {}, + handleCompletion() { if (this._success) { resolve(); } else { diff --git a/browser/components/migration/ESEDBReader.jsm b/browser/components/migration/ESEDBReader.jsm index a01bee53f73b..ad842356b338 100644 --- a/browser/components/migration/ESEDBReader.jsm +++ b/browser/components/migration/ESEDBReader.jsm @@ -354,7 +354,7 @@ ESEDB.prototype = { return true; }, - tableItems: function*(tableName, columns) { + *tableItems(tableName, columns) { if (!this._opened) { throw new Error("The database was closed!"); } diff --git a/browser/components/migration/EdgeProfileMigrator.js b/browser/components/migration/EdgeProfileMigrator.js index 189932bed8aa..f2d83d433348 100644 --- a/browser/components/migration/EdgeProfileMigrator.js +++ b/browser/components/migration/EdgeProfileMigrator.js @@ -107,7 +107,7 @@ EdgeTypedURLMigrator.prototype = { return this._typedURLs.size > 0; }, - migrate: function(aCallback) { + migrate(aCallback) { let typedURLs = this._typedURLs; let places = []; for (let [urlString, time] of typedURLs) { @@ -140,12 +140,12 @@ EdgeTypedURLMigrator.prototype = { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult: function() { + handleResult() { // Importing any entry is considered a successful import. this._success = true; }, - handleError: function() {}, - handleCompletion: function() { + handleError() {}, + handleCompletion() { aCallback(this._success); } }); diff --git a/browser/components/migration/FirefoxProfileMigrator.js b/browser/components/migration/FirefoxProfileMigrator.js index 526c82938f6d..485719ae90bf 100644 --- a/browser/components/migration/FirefoxProfileMigrator.js +++ b/browser/components/migration/FirefoxProfileMigrator.js @@ -62,7 +62,7 @@ function sorter(a, b) { } Object.defineProperty(FirefoxProfileMigrator.prototype, "sourceProfiles", { - get: function() { + get() { return [...this._getAllProfiles().keys()].map(x => ({id: x, name: x})).sort(sorter); } }); @@ -117,7 +117,7 @@ FirefoxProfileMigrator.prototype._getResourcesInternal = function(sourceProfileD } return { type: aMigrationType, - migrate: function(aCallback) { + migrate(aCallback) { for (let file of files) { file.copyTo(currentProfileDir, ""); } @@ -143,7 +143,7 @@ FirefoxProfileMigrator.prototype._getResourcesInternal = function(sourceProfileD if (sessionFile) { session = { type: types.SESSION, - migrate: function(aCallback) { + migrate(aCallback) { sessionCheckpoints.copyTo(currentProfileDir, "sessionCheckpoints.json"); let newSessionFile = currentProfileDir.clone(); newSessionFile.append("sessionstore.js"); diff --git a/browser/components/migration/IEProfileMigrator.js b/browser/components/migration/IEProfileMigrator.js index b1ff92a69f65..97582208358a 100644 --- a/browser/components/migration/IEProfileMigrator.js +++ b/browser/components/migration/IEProfileMigrator.js @@ -76,9 +76,9 @@ History.prototype = { let lastVisitTime = entry.get("time") || (Date.now() * 1000); places.push( - { uri: uri, - title: title, - visits: [{ transitionType: transitionType, + { uri, + title, + visits: [{ transitionType, visitDate: lastVisitTime }] } ); @@ -92,12 +92,12 @@ History.prototype = { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult: function() { + handleResult() { // Importing any entry is considered a successful import. this._success = true; }, - handleError: function() {}, - handleCompletion: function() { + handleError() {}, + handleCompletion() { aCallback(this._success); } }); @@ -320,8 +320,8 @@ IE7FormPasswords.prototype = { fileTimeToSecondsSinceEpoch(currentLoginItem.hiDateTime, currentLoginItem.loDateTime) * 1000; let currentResult = { - creation: creation, - url: url, + creation, + url, }; // The username is UTF-16 and null-terminated. currentResult.username = diff --git a/browser/components/migration/MSMigrationUtils.jsm b/browser/components/migration/MSMigrationUtils.jsm index c36ef21bffdb..989e6bb541be 100644 --- a/browser/components/migration/MSMigrationUtils.jsm +++ b/browser/components/migration/MSMigrationUtils.jsm @@ -874,7 +874,7 @@ WindowsVaultFormPasswords.prototype = { var MSMigrationUtils = { MIGRATION_TYPE_IE: 1, MIGRATION_TYPE_EDGE: 2, - CtypesKernelHelpers: CtypesKernelHelpers, + CtypesKernelHelpers, getBookmarksMigrator(migrationType = this.MIGRATION_TYPE_IE) { return new Bookmarks(migrationType); }, diff --git a/browser/components/migration/MigrationUtils.jsm b/browser/components/migration/MigrationUtils.jsm index 8a966960634f..01f607f646a4 100644 --- a/browser/components/migration/MigrationUtils.jsm +++ b/browser/components/migration/MigrationUtils.jsm @@ -295,7 +295,6 @@ this.MigratorPrototype = { } notify("Migration:Started"); for (let [migrationType, itemResources] of resourcesGroupedByItems) { - notify("Migration:ItemBeforeMigrate", migrationType); let itemSuccess = false; diff --git a/browser/components/migration/SafariProfileMigrator.js b/browser/components/migration/SafariProfileMigrator.js index 664eb13beca8..2d782d5a448d 100644 --- a/browser/components/migration/SafariProfileMigrator.js +++ b/browser/components/migration/SafariProfileMigrator.js @@ -220,7 +220,7 @@ History.prototype = { places.push({ uri: NetUtil.newURI(entry.get("")), title: entry.get("title"), visits: [{ transitionType: transType, - visitDate: visitDate }] }); + visitDate }] }); } catch (ex) { // Safari's History file may contain malformed URIs which @@ -232,12 +232,12 @@ History.prototype = { if (places.length > 0) { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult: function() { + handleResult() { // Importing any entry is considered a successful import. this._success = true; }, - handleError: function() {}, - handleCompletion: function() { + handleError() {}, + handleCompletion() { aCallback(this._success); } }); diff --git a/browser/components/migration/content/migration.js b/browser/components/migration/content/migration.js index 3691232069da..908c9b965482 100644 --- a/browser/components/migration/content/migration.js +++ b/browser/components/migration/content/migration.js @@ -22,7 +22,7 @@ var MigrationWizard = { /* exported MigrationWizard */ _migrator: null, _autoMigrate: null, - init: function() + init() { let os = Services.obs; os.addObserver(this, "Migration:Started", false); @@ -58,7 +58,7 @@ var MigrationWizard = { /* exported MigrationWizard */ this.onImportSourcePageShow(); }, - uninit: function() + uninit() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); @@ -71,7 +71,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 1 - Import Source - onImportSourcePageShow: function() + onImportSourcePageShow() { // Show warning message to close the selected browser when needed function toggleCloseBrowserWarning() { @@ -137,7 +137,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportSourcePageAdvanced: function() + onImportSourcePageAdvanced() { var newSource = document.getElementById("importSourceGroup").selectedItem.id; @@ -183,7 +183,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 2 - [Profile Selection] - onSelectProfilePageShow: function() + onSelectProfilePageShow() { // Disabling this for now, since we ask about import sources in automigration // too and don't want to disable the back button @@ -210,7 +210,7 @@ var MigrationWizard = { /* exported MigrationWizard */ profiles.selectedItem = this._selectedProfile ? document.getElementById(this._selectedProfile.id) : profiles.firstChild; }, - onSelectProfilePageRewound: function() + onSelectProfilePageRewound() { var profiles = document.getElementById("profiles"); this._selectedProfile = this._migrator.sourceProfiles.find( @@ -218,7 +218,7 @@ var MigrationWizard = { /* exported MigrationWizard */ ) || null; }, - onSelectProfilePageAdvanced: function() + onSelectProfilePageAdvanced() { var profiles = document.getElementById("profiles"); this._selectedProfile = this._migrator.sourceProfiles.find( @@ -231,7 +231,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 3 - ImportItems - onImportItemsPageShow: function() + onImportItemsPageShow() { var dataSources = document.getElementById("dataSources"); while (dataSources.hasChildNodes()) @@ -252,13 +252,13 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportItemsPageRewound: function() + onImportItemsPageRewound() { this._wiz.canAdvance = true; this.onImportItemsPageAdvanced(); }, - onImportItemsPageAdvanced: function() + onImportItemsPageAdvanced() { var dataSources = document.getElementById("dataSources"); this._itemsFlags = 0; @@ -269,7 +269,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportItemCommand: function() + onImportItemCommand() { var items = document.getElementById("dataSources"); var checkboxes = items.getElementsByTagName("checkbox"); @@ -286,7 +286,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 4 - Home Page Selection - onHomePageMigrationPageShow: function() + onHomePageMigrationPageShow() { // only want this on the first run if (!this._autoMigrate) { @@ -338,7 +338,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onHomePageMigrationPageAdvanced: function() + onHomePageMigrationPageAdvanced() { // we might not have a selectedItem if we're in fallback mode try { @@ -349,7 +349,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 5 - Migrating - onMigratingPageShow: function() + onMigratingPageShow() { this._wiz.getButton("cancel").disabled = true; this._wiz.canRewind = false; @@ -363,7 +363,7 @@ var MigrationWizard = { /* exported MigrationWizard */ setTimeout(() => this.onMigratingMigrate(), 0); }, - onMigratingMigrate: function() + onMigratingMigrate() { this._migrator.migrate(this._itemsFlags, this._autoMigrate, this._selectedProfile); @@ -383,7 +383,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - _listItems: function(aID) + _listItems(aID) { var items = document.getElementById(aID); while (items.hasChildNodes()) @@ -409,7 +409,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { var label; switch (aTopic) { @@ -514,7 +514,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onDonePageShow: function() + onDonePageShow() { this._wiz.getButton("cancel").disabled = true; this._wiz.canRewind = false; diff --git a/browser/components/migration/tests/unit/test_automigration.js b/browser/components/migration/tests/unit/test_automigration.js index 34e90d00d900..3a19dcbc3f62 100644 --- a/browser/components/migration/tests/unit/test_automigration.js +++ b/browser/components/migration/tests/unit/test_automigration.js @@ -215,7 +215,7 @@ add_task(function* checkUndoRemoval() { let frecencyUpdatePromise = new Promise(resolve => { let expectedChanges = 2; let observer = { - onFrecencyChanged: function() { + onFrecencyChanged() { if (!--expectedChanges) { PlacesUtils.history.removeObserver(observer); resolve(); @@ -561,31 +561,31 @@ add_task(function* checkUndoVisitsState() { ]); let wrongMethodDeferred = PromiseUtils.defer(); let observer = { - onBeginUpdateBatch: function() {}, - onEndUpdateBatch: function() {}, - onVisit: function(uri) { + onBeginUpdateBatch() {}, + onEndUpdateBatch() {}, + onVisit(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onVisit " + uri.spec)); }, - onTitleChanged: function(uri) { + onTitleChanged(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onTitleChanged " + uri.spec)); }, - onClearHistory: function() { + onClearHistory() { wrongMethodDeferred.reject("Unexpected call to onClearHistory"); }, - onPageChanged: function(uri) { + onPageChanged(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onPageChanged " + uri.spec)); }, - onFrecencyChanged: function(aURI) { + onFrecencyChanged(aURI) { do_print("frecency change"); Assert.ok(frecencyChangesExpected.has(aURI.spec), "Should be expecting frecency change for " + aURI.spec); frecencyChangesExpected.get(aURI.spec).resolve(); }, - onManyFrecenciesChanged: function() { + onManyFrecenciesChanged() { do_print("Many frecencies changed"); wrongMethodDeferred.reject(new Error("This test can't deal with onManyFrecenciesChanged to be called")); }, - onDeleteURI: function(aURI) { + onDeleteURI(aURI) { do_print("delete uri"); Assert.ok(uriDeletedExpected.has(aURI.spec), "Should be expecting uri deletion for " + aURI.spec); diff --git a/browser/components/newtab/NewTabURL.jsm b/browser/components/newtab/NewTabURL.jsm index 5000eae2e9ae..9c8b78dd571a 100644 --- a/browser/components/newtab/NewTabURL.jsm +++ b/browser/components/newtab/NewTabURL.jsm @@ -18,7 +18,7 @@ XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", this.NewTabURL = { - get: function() { + get() { return aboutNewTabService.newTabURL; }, @@ -26,11 +26,11 @@ this.NewTabURL = { return aboutNewTabService.overridden; }, - override: function(newURL) { + override(newURL) { aboutNewTabService.newTabURL = newURL; }, - reset: function() { + reset() { aboutNewTabService.resetNewTabURL(); } }; diff --git a/browser/components/newtab/NewTabWebChannel.jsm b/browser/components/newtab/NewTabWebChannel.jsm index 28614ebb7883..8a6973f9e603 100644 --- a/browser/components/newtab/NewTabWebChannel.jsm +++ b/browser/components/newtab/NewTabWebChannel.jsm @@ -188,7 +188,7 @@ NewTabWebChannelImpl.prototype = { try { let msg = JSON.parse(message); - this.emit(msg.type, {data: msg.data, target: target}); + this.emit(msg.type, {data: msg.data, target}); } catch (err) { Cu.reportError(err); } diff --git a/browser/components/newtab/PlacesProvider.jsm b/browser/components/newtab/PlacesProvider.jsm index 2e26729c6435..63e17b88deee 100644 --- a/browser/components/newtab/PlacesProvider.jsm +++ b/browser/components/newtab/PlacesProvider.jsm @@ -248,6 +248,6 @@ Links.prototype = { const gLinks = new Links(); // jshint ignore:line let PlacesProvider = { - LinkChecker: LinkChecker, + LinkChecker, links: gLinks, }; diff --git a/browser/components/nsBrowserGlue.js b/browser/components/nsBrowserGlue.js index f06528712477..255b39c279e1 100644 --- a/browser/components/nsBrowserGlue.js +++ b/browser/components/nsBrowserGlue.js @@ -543,7 +543,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getFormattedString("addonwatch.disable.label", [addon.name]), accessKey: "", // workaround for bug 1192901 - callback: function() { + callback() { done(STATE_USER_PICKED_DISABLE); addon.userDisabled = true; if (addon.pendingOperations == addon.PENDING_NONE) { @@ -554,7 +554,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getFormattedString("addonwatch.restart.label", [brandShortName]), accessKey: win.gNavigatorBundle.getString("addonwatch.restart.accesskey"), - callback: function() { + callback() { let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"] .getService(Ci.nsIAppStartup); appStartup.quit(appStartup.eForceQuit | appStartup.eRestart); @@ -569,7 +569,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("addonwatch.ignoreSession.label"), accessKey: win.gNavigatorBundle.getString("addonwatch.ignoreSession.accesskey"), - callback: function() { + callback() { done(STATE_USER_PICKED_IGNORE_FOR_NOW); AddonWatcher.ignoreAddonForSession(addonId); } @@ -577,7 +577,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("addonwatch.ignorePerm.label"), accessKey: win.gNavigatorBundle.getString("addonwatch.ignorePerm.accesskey"), - callback: function() { + callback() { done(STATE_USER_PICKED_IGNORE_FOREVER); AddonWatcher.ignoreAddonPermanently(addonId); } @@ -672,7 +672,7 @@ BrowserGlue.prototype = { Services.obs.notifyObservers(null, "browser-ui-startup-complete", ""); }, - _checkForOldBuildUpdates: function() { + _checkForOldBuildUpdates() { // check for update if our build is old if (AppConstants.MOZ_UPDATER && Services.prefs.getBoolPref("app.update.enabled") && @@ -724,7 +724,7 @@ BrowserGlue.prototype = { } }, - _trackSlowStartup: function() { + _trackSlowStartup() { if (Services.startup.interrupted || Services.prefs.getBoolPref("browser.slowStartup.notificationDisabled")) return; @@ -767,7 +767,7 @@ BrowserGlue.prototype = { return (Date.now() - profileDate) / ONE_DAY; }), - _showSlowStartupNotification: function(profileAge) { + _showSlowStartupNotification(profileAge) { if (profileAge < 90) // 3 months return; @@ -782,14 +782,14 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("slowStartup.helpButton.label"), accessKey: win.gNavigatorBundle.getString("slowStartup.helpButton.accesskey"), - callback: function() { + callback() { win.openUILinkIn("https://support.mozilla.org/kb/reset-firefox-easily-fix-most-problems", "tab"); } }, { label: win.gNavigatorBundle.getString("slowStartup.disableNotificationButton.label"), accessKey: win.gNavigatorBundle.getString("slowStartup.disableNotificationButton.accesskey"), - callback: function() { + callback() { Services.prefs.setBoolPref("browser.slowStartup.notificationDisabled", true); } } @@ -808,7 +808,7 @@ BrowserGlue.prototype = { * String of either "unused" or "uninstall", specifying the reason * why a profile reset is offered. */ - _resetProfileNotification: function(reason) { + _resetProfileNotification(reason) { let win = RecentWindow.getMostRecentBrowserWindow(); if (!win) return; @@ -833,7 +833,7 @@ BrowserGlue.prototype = { { label: resetBundle.formatStringFromName("refreshProfile.resetButton.label", [productName], 1), accessKey: resetBundle.GetStringFromName("refreshProfile.resetButton.accesskey"), - callback: function() { + callback() { ResetProfile.openConfirmationDialog(win); } }, @@ -845,7 +845,7 @@ BrowserGlue.prototype = { nb.PRIORITY_INFO_LOW, buttons); }, - _notifyUnsignedAddonsDisabled: function() { + _notifyUnsignedAddonsDisabled() { let win = RecentWindow.getMostRecentBrowserWindow(); if (!win) return; @@ -855,7 +855,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("unsignedAddonsDisabled.learnMore.label"), accessKey: win.gNavigatorBundle.getString("unsignedAddonsDisabled.learnMore.accesskey"), - callback: function() { + callback() { win.BrowserOpenAddonsMgr("addons://list/extension?unsigned=true"); } }, @@ -866,7 +866,7 @@ BrowserGlue.prototype = { nb.PRIORITY_WARNING_MEDIUM, buttons); }, - _firstWindowTelemetry: function(aWindow) { + _firstWindowTelemetry(aWindow) { let SCALING_PROBE_NAME = ""; switch (AppConstants.platform) { case "win": @@ -979,7 +979,7 @@ BrowserGlue.prototype = { /** * Application shutdown handler. */ - _onQuitApplicationGranted: function() { + _onQuitApplicationGranted() { // This pref must be set here because SessionStore will use its value // on quit-application. this._setPrefToSaveSession(); @@ -1008,14 +1008,14 @@ BrowserGlue.prototype = { } }, - _initServiceDiscovery: function() { + _initServiceDiscovery() { if (!Services.prefs.getBoolPref("browser.casting.enabled")) { return; } var rokuDevice = { id: "roku:ecp", target: "roku:ecp", - factory: function(aService) { + factory(aService) { Cu.import("resource://gre/modules/RokuApp.jsm"); return new RokuApp(aService); }, @@ -1171,7 +1171,7 @@ BrowserGlue.prototype = { E10SAccessibilityCheck.onWindowsRestored(); }, - _createExtraDefaultProfile: function() { + _createExtraDefaultProfile() { if (!AppConstants.MOZ_DEV_EDITION) { return; } @@ -1391,10 +1391,10 @@ BrowserGlue.prototype = { let buttons = [ { - label: label, + label, accessKey: key, popup: null, - callback: function(aNotificationBar, aButton) { + callback(aNotificationBar, aButton) { win.openUILinkIn(url, "tab"); } } @@ -1694,9 +1694,9 @@ BrowserGlue.prototype = { var buttons = [ { label: buttonText, - accessKey: accessKey, + accessKey, popup: null, - callback: function(aNotificationBar, aButton) { + callback(aNotificationBar, aButton) { win.openUILinkIn(url, "tab"); } } @@ -1709,7 +1709,7 @@ BrowserGlue.prototype = { notification.persistence = -1; // Until user closes it }, - _showSyncStartedDoorhanger: function() { + _showSyncStartedDoorhanger() { let bundle = Services.strings.createBundle("chrome://browser/locale/accounts.properties"); let productName = gBrandBundle.GetStringFromName("brandShortName"); let title = bundle.GetStringFromName("syncStartNotification.title"); @@ -2098,7 +2098,7 @@ BrowserGlue.prototype = { true, url, clickCallback); }), - _hasSystemAlertsService: function() { + _hasSystemAlertsService() { try { return !!Cc["@mozilla.org/system-alerts-service;1"].getService( Ci.nsIAlertsService); @@ -2356,7 +2356,7 @@ BrowserGlue.prototype = { AlertsService.showAlertNotification(null, title, body, true, null, clickCallback); }, - _handleFlashHang: function() { + _handleFlashHang() { ++this._flashHangCount; if (this._flashHangCount < 2) { return; @@ -2388,7 +2388,7 @@ BrowserGlue.prototype = { let buttons = [{ label: win.gNavigatorBundle.getString("flashHang.helpButton.label"), accessKey: win.gNavigatorBundle.getString("flashHang.helpButton.accesskey"), - callback: function() { + callback() { win.openUILinkIn("https://support.mozilla.org/kb/flash-protected-mode-autodisabled", "tab"); } }]; @@ -2509,13 +2509,13 @@ var DefaultBrowserCheck = { _setAsDefaultTimer: null, _setAsDefaultButtonClickStartTime: 0, - closePrompt: function(aNode) { + closePrompt(aNode) { if (this._notification) { this._notification.close(); } }, - setAsDefault: function() { + setAsDefault() { let claimAllTypes = true; let setAsDefaultError = false; if (AppConstants.platform == "win") { @@ -2571,7 +2571,7 @@ var DefaultBrowserCheck = { .add(setAsDefaultError); }, - _createPopup: function(win, notNowStrings, neverStrings) { + _createPopup(win, notNowStrings, neverStrings) { let doc = win.document; let popup = doc.createElement("menupopup"); popup.id = this.OPTIONPOPUP; @@ -2594,7 +2594,7 @@ var DefaultBrowserCheck = { popupset.appendChild(popup); }, - handleEvent: function(event) { + handleEvent(event) { if (event.type == "command") { if (event.target.id == "defaultBrowserNever") { ShellService.shouldCheckDefaultBrowser = false; @@ -2603,7 +2603,7 @@ var DefaultBrowserCheck = { } }, - prompt: function(win) { + prompt(win) { let useNotificationBar = Services.prefs.getBoolPref("browser.defaultbrowser.notificationbar"); let brandBundle = win.document.getElementById("bundle_brand"); @@ -2689,7 +2689,7 @@ var DefaultBrowserCheck = { } }, - _onNotificationEvent: function(eventType) { + _onNotificationEvent(eventType) { if (eventType == "removed") { let doc = this._notification.ownerDocument; let popup = doc.getElementById(this.OPTIONPOPUP); @@ -2705,7 +2705,7 @@ var E10SAccessibilityCheck = { // first window being opening. _wantsPrompt: false, - init: function() { + init() { Services.obs.addObserver(this, "a11y-init-or-shutdown", true); Services.obs.addObserver(this, "quit-application-granted", true); }, @@ -2719,7 +2719,7 @@ var E10SAccessibilityCheck = { return false; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "quit-application-granted": // Tag the profile with a11y load state. We use this in nsAppRunner @@ -2737,7 +2737,7 @@ var E10SAccessibilityCheck = { } }, - onWindowsRestored: function() { + onWindowsRestored() { if (this._wantsPrompt) { this._wantsPrompt = false; this._showE10sAccessibilityWarning(); @@ -2746,7 +2746,7 @@ var E10SAccessibilityCheck = { _warnedAboutAccessibility: false, - _showE10sAccessibilityWarning: function() { + _showE10sAccessibilityWarning() { // We don't prompt about a11y incompat if e10s is off. if (!Services.appinfo.browserTabsRemoteAutostart) { return; @@ -2794,7 +2794,7 @@ var E10SAccessibilityCheck = { let mainAction = { label: win.gNavigatorBundle.getString("e10s.accessibilityNotice.acceptButton.label"), accessKey: win.gNavigatorBundle.getString("e10s.accessibilityNotice.acceptButton.accesskey"), - callback: function() { + callback() { // If the user invoked the button option remove the notification, // otherwise keep the alert icon around in the address bar. notification.remove(); diff --git a/browser/components/originattributes/test/browser/browser_cache.js b/browser/components/originattributes/test/browser/browser_cache.js index 87a0aadd1b42..f1f80d5ccf6a 100644 --- a/browser/components/originattributes/test/browser/browser_cache.js +++ b/browser/components/originattributes/test/browser/browser_cache.js @@ -42,8 +42,8 @@ function cacheDataForContext(loadContextInfo) { let cacheVisitor = { onCacheStorageInfo(num, consumption) {}, onCacheEntryInfo(uri, idEnhance) { - cacheEntries.push({ uri: uri, - idEnhance: idEnhance }); + cacheEntries.push({ uri, + idEnhance }); }, onCacheEntryVisitCompleted() { resolve(cacheEntries); @@ -73,7 +73,7 @@ function observeChannels(onChannel) { // We use a dummy proxy filter to catch all channels, even those that do not // generate an "http-on-modify-request" notification, such as link preconnects. let proxyFilter = { - applyFilter : function(aProxyService, aChannel, aProxy) { + applyFilter(aProxyService, aChannel, aProxy) { // We have the channel; provide it to the callback. onChannel(aChannel); // Pass on aProxy unmodified. @@ -141,7 +141,7 @@ function* doInit(aMode) { function* doTest(aBrowser) { let argObj = { - randomSuffix: randomSuffix, + randomSuffix, urlPrefix: TEST_DOMAIN + TEST_PATH, }; diff --git a/browser/components/places/PlacesUIUtils.jsm b/browser/components/places/PlacesUIUtils.jsm index 45f3226e6ca4..7ab2f9f0391e 100644 --- a/browser/components/places/PlacesUIUtils.jsm +++ b/browser/components/places/PlacesUIUtils.jsm @@ -584,7 +584,7 @@ this.PlacesUIUtils = { * @return a Places Transaction that can be transacted for performing the * move/insert command. */ - getTransactionForData: function(aData, aType, aNewParentGuid, aIndex, aCopy) { + getTransactionForData(aData, aType, aNewParentGuid, aIndex, aCopy) { if (!this.SUPPORTED_FLAVORS.includes(aData.type)) throw new Error(`Unsupported '${aData.type}' data type`); @@ -617,7 +617,7 @@ this.PlacesUIUtils = { let title = aData.type != PlacesUtils.TYPE_UNICODE ? aData.title : aData.uri; return PlacesTransactions.NewBookmark({ uri: NetUtil.newURI(aData.uri) - , title: title + , title , parentGuid: aNewParentGuid , index: aIndex }); }, @@ -797,7 +797,7 @@ this.PlacesUIUtils = { * a node, except the root node of a query. * @return true if the aNode represents a removable entry, false otherwise. */ - canUserRemove: function(aNode) { + canUserRemove(aNode) { let parentNode = aNode.parent; if (!parentNode) { // canUserRemove doesn't accept root nodes. @@ -845,7 +845,7 @@ this.PlacesUIUtils = { * @note livemark "folders" are considered read-only (but see bug 1072833). * @return true if aItemId points to a read-only folder, false otherwise. */ - isContentsReadOnly: function(aNodeOrItemId) { + isContentsReadOnly(aNodeOrItemId) { let itemId; if (typeof(aNodeOrItemId) == "number") { itemId = aNodeOrItemId; @@ -1408,7 +1408,7 @@ this.PlacesUIUtils = { return queryName; }, - shouldShowTabsFromOtherComputersMenuitem: function() { + shouldShowTabsFromOtherComputersMenuitem() { let weaveOK = Weave.Status.checkSetup() != Weave.CLIENT_NOT_CONFIGURED && Weave.Svc.Prefs.get("firstSync", "") != "notReady"; return weaveOK; @@ -1691,7 +1691,7 @@ XPCOMUtils.defineLazyGetter(PlacesUIUtils, "ptm", function() { * boolean value. * @return nsITransaction object. */ - setLoadInSidebar: function(aItemId, aLoadInSidebar) + setLoadInSidebar(aItemId, aLoadInSidebar) { let annoObj = { name: PlacesUIUtils.LOAD_IN_SIDEBAR_ANNO, type: Ci.nsIAnnotationService.TYPE_INT32, @@ -1710,7 +1710,7 @@ XPCOMUtils.defineLazyGetter(PlacesUIUtils, "ptm", function() { * new description. * @return nsITransaction object. */ - editItemDescription: function(aItemId, aDescription) + editItemDescription(aItemId, aDescription) { let annoObj = { name: PlacesUIUtils.DESCRIPTION_ANNO, type: Ci.nsIAnnotationService.TYPE_STRING, diff --git a/browser/components/places/content/bookmarkProperties.js b/browser/components/places/content/bookmarkProperties.js index f1695ffd5af7..42d825ea460d 100644 --- a/browser/components/places/content/bookmarkProperties.js +++ b/browser/components/places/content/bookmarkProperties.js @@ -614,7 +614,7 @@ var BookmarkPropertiesPanel = { let folderGuid = yield PlacesUtils.promiseItemGuid(container); let bm = yield PlacesUtils.bookmarks.fetch({ parentGuid: folderGuid, - index: index + index }); this._itemId = yield PlacesUtils.promiseItemId(bm.guid); diff --git a/browser/components/places/content/browserPlacesViews.js b/browser/components/places/content/browserPlacesViews.js index 3cdb7135ae30..d5170fa7e1c3 100644 --- a/browser/components/places/content/browserPlacesViews.js +++ b/browser/components/places/content/browserPlacesViews.js @@ -135,8 +135,8 @@ PlacesViewBase.prototype = { get selType() { return "single"; }, - selectItems: function() { }, - selectAll: function() { }, + selectItems() { }, + selectAll() { }, get selectedNode() { if (this._contextMenuShown) { @@ -619,12 +619,12 @@ PlacesViewBase.prototype = { } }, - nodeTagsChanged: function() { }, - nodeDateAddedChanged: function() { }, - nodeLastModifiedChanged: function() { }, - nodeKeywordChanged: function() { }, - sortingChanged: function() { }, - batching: function() { }, + nodeTagsChanged() { }, + nodeDateAddedChanged() { }, + nodeLastModifiedChanged() { }, + nodeKeywordChanged() { }, + sortingChanged() { }, + batching() { }, nodeInserted: function PVB_nodeInserted(aParentPlacesNode, aPlacesNode, aIndex) { @@ -1180,7 +1180,7 @@ PlacesToolbar.prototype = { } }, - updateOverflowStatus: function() { + updateOverflowStatus() { if (this._rootElt.scrollLeftMin != this._rootElt.scrollLeftMax) { this._onOverflow(); } else { diff --git a/browser/components/places/content/controller.js b/browser/components/places/content/controller.js index d0e1fab83c32..061ba02e82ee 100644 --- a/browser/components/places/content/controller.js +++ b/browser/components/places/content/controller.js @@ -59,7 +59,7 @@ InsertionPoint.prototype = { return this._index = val; }, - promiseGuid: function() { + promiseGuid() { return PlacesUtils.promiseItemGuid(this.itemId); }, @@ -867,7 +867,7 @@ PlacesController.prototype = { let tag = node.parent.title; if (!tag) tag = PlacesUtils.bookmarks.getItemTitle(tagItemId); - transactions.push(PlacesTransactions.Untag({ uri: uri, tag: tag })); + transactions.push(PlacesTransactions.Untag({ uri, tag })); } else { let txn = new PlacesUntagURITransaction(uri, [tagItemId]); @@ -885,7 +885,7 @@ PlacesController.prototype = { let tag = node.title; let URIs = PlacesUtils.tagging.getURIsForTag(tag); if (PlacesUIUtils.useAsyncTransactions) { - transactions.push(PlacesTransactions.Untag({ tag: tag, uris: URIs })); + transactions.push(PlacesTransactions.Untag({ tag, uris: URIs })); } else { for (var j = 0; j < URIs.length; j++) { @@ -1308,7 +1308,7 @@ PlacesController.prototype = { if (PlacesUIUtils.useAsyncTransactions) { if (ip.isTag) { let uris = items.filter(item => "uri" in item).map(item => NetUtil.newURI(item.uri)); - yield PlacesTransactions.Tag({ uris: uris, tag: ip.tagName }).transact(); + yield PlacesTransactions.Tag({ uris, tag: ip.tagName }).transact(); } else { yield PlacesTransactions.batch(function* () { @@ -1548,7 +1548,7 @@ var PlacesControllerDragHelper = { * A node unwrapped by PlacesUtils.unwrapNodes(). * @return True if the node can be moved, false otherwise. */ - canMoveUnwrappedNode: function(aUnwrappedNode) { + canMoveUnwrappedNode(aUnwrappedNode) { return aUnwrappedNode.id > 0 && !PlacesUtils.isRootItem(aUnwrappedNode.id) && (!aUnwrappedNode.parent || !PlacesUIUtils.isContentsReadOnly(aUnwrappedNode.parent)) && @@ -1637,7 +1637,7 @@ var PlacesControllerDragHelper = { let uri = NetUtil.newURI(unwrapped.uri); let tagItemId = insertionPoint.itemId; if (PlacesUIUtils.useAsyncTransactions) - transactions.push(PlacesTransactions.Tag({ uri: uri, tag: tagName })); + transactions.push(PlacesTransactions.Tag({ uri, tag: tagName })); else transactions.push(new PlacesTagURITransaction(uri, [tagItemId])); } @@ -1679,7 +1679,7 @@ var PlacesControllerDragHelper = { * @param aContainer * The container were we are want to drop */ - disallowInsertion: function(aContainer) { + disallowInsertion(aContainer) { NS_ASSERT(aContainer, "empty container"); // Allow dropping into Tag containers and editable folders. return !PlacesUtils.nodeIsTagQuery(aContainer) && diff --git a/browser/components/places/content/editBookmarkOverlay.js b/browser/components/places/content/editBookmarkOverlay.js index f08b6b36c91d..8df6511d9a73 100644 --- a/browser/components/places/content/editBookmarkOverlay.js +++ b/browser/components/places/content/editBookmarkOverlay.js @@ -393,7 +393,7 @@ var gEditItemOverlay = { this._recentFolders = []; for (let i = 0; i < folderIds.length; i++) { var lastUsed = annos.getItemAnnotation(folderIds[i], LAST_USED_ANNO); - this._recentFolders.push({ folderId: folderIds[i], lastUsed: lastUsed }); + this._recentFolders.push({ folderId: folderIds[i], lastUsed }); } this._recentFolders.sort(function(a, b) { if (b.lastUsed < a.lastUsed) diff --git a/browser/components/places/content/moveBookmarks.js b/browser/components/places/content/moveBookmarks.js index 626b2b904e40..5f4bf0cfc050 100644 --- a/browser/components/places/content/moveBookmarks.js +++ b/browser/components/places/content/moveBookmarks.js @@ -14,7 +14,7 @@ var gMoveBookmarksDialog = { return this._foldersTree; }, - init: function() { + init() { this._nodes = window.arguments[0]; this.foldersTree.place = diff --git a/browser/components/places/content/places.js b/browser/components/places/content/places.js index 7a141354d172..50ebfaf839fa 100644 --- a/browser/components/places/content/places.js +++ b/browser/components/places/content/places.js @@ -32,7 +32,7 @@ var PlacesOrganizer = { "editBMPanel_keywordRow", ], - _initFolderTree: function() { + _initFolderTree() { var leftPaneRoot = PlacesUIUtils.leftPaneFolderId; this._places.place = "place:excludeItems=1&expandQueries=0&folder=" + leftPaneRoot; }, @@ -1250,7 +1250,7 @@ var ContentArea = { let { view, options } = this._specialViews.get(aQueryString); if (typeof view == "function") { view = view(); - this._specialViews.set(aQueryString, { view: view, options: options }); + this._specialViews.set(aQueryString, { view, options }); } return view; } @@ -1356,7 +1356,7 @@ var ContentArea = { return viewOptions; }, - focus: function() { + focus() { this._deck.selectedPanel.focus(); } }; diff --git a/browser/components/places/content/treeView.js b/browser/components/places/content/treeView.js index ece93fd4ff99..81180a7d0b01 100644 --- a/browser/components/places/content/treeView.js +++ b/browser/components/places/content/treeView.js @@ -1135,7 +1135,7 @@ PlacesTreeView.prototype = { this._selection = val; }, - getRowProperties: function() { return ""; }, + getRowProperties() { return ""; }, getCellProperties: function PTV_getCellProperties(aRow, aColumn) { @@ -1217,7 +1217,7 @@ PlacesTreeView.prototype = { return props + " " + properties; }, - getColumnProperties: function(aColumn) { return ""; }, + getColumnProperties(aColumn) { return ""; }, isContainer: function PTV_isContainer(aRow) { // Only leaf nodes aren't listed in the rows array. @@ -1414,7 +1414,7 @@ PlacesTreeView.prototype = { return false; }, - getLevel: function(aRow) { + getLevel(aRow) { return this._getNodeForRow(aRow).indentLevel; }, @@ -1427,8 +1427,8 @@ PlacesTreeView.prototype = { return node.icon; }, - getProgressMode: function(aRow, aColumn) { }, - getCellValue: function(aRow, aColumn) { }, + getProgressMode(aRow, aColumn) { }, + getCellValue(aRow, aColumn) { }, getCellText: function PTV_getCellText(aRow, aColumn) { let node = this._getNodeForRow(aRow); @@ -1717,10 +1717,10 @@ PlacesTreeView.prototype = { } }, - selectionChanged: function() { }, - cycleCell: function(aRow, aColumn) { }, - isSelectable: function(aRow, aColumn) { return false; }, - performAction: function(aAction) { }, - performActionOnRow: function(aAction, aRow) { }, - performActionOnCell: function(aAction, aRow, aColumn) { } + selectionChanged() { }, + cycleCell(aRow, aColumn) { }, + isSelectable(aRow, aColumn) { return false; }, + performAction(aAction) { }, + performActionOnRow(aAction, aRow) { }, + performActionOnCell(aAction, aRow, aColumn) { } }; diff --git a/browser/components/places/tests/browser/browser_423515.js b/browser/components/places/tests/browser/browser_423515.js index 8a67f050cdd5..2eb129cb7783 100644 --- a/browser/components/places/tests/browser/browser_423515.js +++ b/browser/components/places/tests/browser/browser_423515.js @@ -20,11 +20,11 @@ function test() { // add a regular folder, should be moveable tests.push({ - populate: function() { + populate() { this.id = PlacesUtils.bookmarks.createFolder(rootId, "", IDX); }, - validate: function() { + validate() { is(rootNode.childCount, 1, "populate added data to the test root"); is(PlacesControllerDragHelper.canMoveNode(rootNode.getChild(0)), @@ -34,13 +34,13 @@ function test() { // add a regular folder shortcut, should be moveable tests.push({ - populate: function() { + populate() { this.folderId = PlacesUtils.bookmarks.createFolder(rootId, "foo", IDX); this.shortcutId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder=" + this.folderId), IDX, "bar"); }, - validate: function() { + validate() { is(rootNode.childCount, 2, "populated data to the test root"); @@ -62,13 +62,13 @@ function test() { // add a regular query, should be moveable tests.push({ - populate: function() { + populate() { this.bookmarkId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("http://foo.com"), IDX, "foo"); this.queryId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:terms=foo"), IDX, "bar"); }, - validate: function() { + validate() { is(rootNode.childCount, 2, "populated data to the test root"); @@ -90,14 +90,14 @@ function test() { PlacesUtils.tagsFolderId, PlacesUtils.unfiledBookmarksFolderId, PlacesUtils.toolbarFolderId], shortcuts: {}, - populate: function() { + populate() { for (var i = 0; i < this.folders.length; i++) { var id = this.folders[i]; this.shortcuts[id] = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder=" + id), IDX, ""); } }, - validate: function() { + validate() { // test toolbar shortcut node is(rootNode.childCount, this.folders.length, "populated data to the test root"); @@ -138,13 +138,13 @@ function test() { // test that a tag container cannot be moved tests.push({ - populate: function() { + populate() { // tag a uri this.uri = makeURI("http://foo.com"); PlacesUtils.tagging.tagURI(this.uri, ["bar"]); registerCleanupFunction(() => PlacesUtils.tagging.untagURI(this.uri, ["bar"])); }, - validate: function() { + validate() { // get tag root var query = PlacesUtils.history.getNewQuery(); var options = PlacesUtils.history.getNewQueryOptions(); diff --git a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js index 78d667e5f169..aaece0b9f5ed 100644 --- a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js +++ b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js @@ -6,9 +6,9 @@ function makeBookmarkFor(url, keyword) { return Promise.all([ PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid, title: "bookmarklet", - url: url }), - PlacesUtils.keywords.insert({url: url, - keyword: keyword}) + url }), + PlacesUtils.keywords.insert({url, + keyword}) ]); } diff --git a/browser/components/places/tests/browser/browser_bookmarksProperties.js b/browser/components/places/tests/browser/browser_bookmarksProperties.js index 7f7d635afe01..63d1c4f874e0 100644 --- a/browser/components/places/tests/browser/browser_bookmarksProperties.js +++ b/browser/components/places/tests/browser/browser_bookmarksProperties.js @@ -63,7 +63,7 @@ gTests.push({ _itemId: null, _cleanShutdown: false, - setup: function(aCallback) { + setup(aCallback) { // Add a bookmark in unsorted bookmarks folder. this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL)); ok(this._itemId > 0, "Correctly added a bookmark"); @@ -75,14 +75,14 @@ gTests.push({ aCallback(); }, - selectNode: function(tree) { + selectNode(tree) { tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]); PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; tree.selectItems([this._itemId]); is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected"); }, - run: function() { + run() { // open tags autocomplete and press enter var tagsField = this.window.document.getElementById("editBMPanel_tagsField"); var self = this; @@ -97,7 +97,7 @@ gTests.push({ }, true); var popupListener = { - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "popuphidden": // Everything worked fine, we can stop observing the window. @@ -137,12 +137,12 @@ gTests.push({ }); }, - finish: function() { + finish() { SidebarUI.hide(); runNextTest(); }, - cleanup: function() { + cleanup() { // Check tags have not changed. var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); is(tags[0], "testTag", "Tag on node has not changed"); @@ -165,7 +165,7 @@ gTests.push({ _itemId: null, _cleanShutdown: false, - setup: function(aCallback) { + setup(aCallback) { // Add a bookmark in unsorted bookmarks folder. this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL)); ok(this._itemId > 0, "Correctly added a bookmark"); @@ -177,14 +177,14 @@ gTests.push({ aCallback(); }, - selectNode: function(tree) { + selectNode(tree) { tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]); PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; tree.selectItems([this._itemId]); is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected"); }, - run: function() { + run() { // open tags autocomplete and press enter var tagsField = this.window.document.getElementById("editBMPanel_tagsField"); var self = this; @@ -199,7 +199,7 @@ gTests.push({ }, true); var popupListener = { - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "popuphidden": // Everything worked fine. @@ -237,12 +237,12 @@ gTests.push({ EventUtils.synthesizeKey("t", {}, this.window); }, - finish: function() { + finish() { SidebarUI.hide(); runNextTest(); }, - cleanup: function() { + cleanup() { // Check tags have not changed. var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); is(tags[0], "testTag", "Tag on node has not changed"); @@ -264,7 +264,7 @@ gTests.push({ historyView: SIDEBAR_HISTORY_BYLASTVISITED_VIEW, window: null, - setup: function(aCallback) { + setup(aCallback) { // Add a visit. PlacesTestUtils.addVisits( {uri: PlacesUtils._uri(TEST_URL), @@ -272,14 +272,14 @@ gTests.push({ ).then(aCallback); }, - selectNode: function(tree) { + selectNode(tree) { var visitNode = tree.view.nodeForTreeIndex(0); tree.selectNode(visitNode); is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected"); is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked"); }, - run: function() { + run() { // Open folder selector. var foldersExpander = this.window.document.getElementById("editBMPanel_foldersExpander"); var folderTree = this.window.document.getElementById("editBMPanel_folderTree"); @@ -315,12 +315,12 @@ gTests.push({ foldersExpander.doCommand(); }, - finish: function() { + finish() { SidebarUI.hide(); runNextTest(); }, - cleanup: function() { + cleanup() { return PlacesTestUtils.clearHistory(); } }); diff --git a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js b/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js index fbc0b02b6387..95aa6f620946 100644 --- a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js +++ b/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js @@ -144,7 +144,7 @@ var gTests = [ { desc: "Drag a folder on toolbar", - run: function() { + run() { // Create a test folder to be dragged. var folderId = PlacesUtils.bookmarks .createFolder(PlacesUtils.toolbarFolderId, @@ -185,7 +185,7 @@ var gTests = [ { desc: "Drag a bookmark on toolbar", - run: function() { + run() { // Create a test bookmark to be dragged. var itemId = PlacesUtils.bookmarks .insertBookmark(PlacesUtils.toolbarFolderId, diff --git a/browser/components/places/tests/browser/browser_library_batch_delete.js b/browser/components/places/tests/browser/browser_library_batch_delete.js index 531ad9139b48..37f843b6a21b 100644 --- a/browser/components/places/tests/browser/browser_library_batch_delete.js +++ b/browser/components/places/tests/browser/browser_library_batch_delete.js @@ -14,10 +14,10 @@ var gLibrary; gTests.push({ desc: "Create and batch remove bookmarks", - run: function() { + run() { let testURI = makeURI(TEST_URL); PlacesUtils.history.runInBatchMode({ - runBatched: function(aUserData) { + runBatched(aUserData) { // Create a folder in unserted and populate it with bookmarks. let folder = PlacesUtils.bookmarks.createFolder( PlacesUtils.unfiledBookmarksFolderId, "deleteme", @@ -67,7 +67,7 @@ gTests.push({ gTests.push({ desc: "Ensure correct selection and functionality in Library", - run: function() { + run() { let PO = gLibrary.PlacesOrganizer; let ContentTree = gLibrary.ContentTree; // Move selection forth and back. diff --git a/browser/components/places/tests/browser/browser_library_downloads.js b/browser/components/places/tests/browser/browser_library_downloads.js index 77005b6fc6b2..3578b8f2b7cf 100644 --- a/browser/components/places/tests/browser/browser_library_downloads.js +++ b/browser/components/places/tests/browser/browser_library_downloads.js @@ -32,11 +32,11 @@ function test() { }, ] PlacesUtils.asyncHistory.updatePlaces(places, { - handleResult: function() {}, - handleError: function() { + handleResult() {}, + handleError() { ok(false, "gHistory.updatePlaces() failed"); }, - handleCompletion: function() { + handleCompletion() { // Make sure Downloads is present. isnot(win.PlacesOrganizer._places.selectedNode, null, "Downloads is present and selected"); diff --git a/browser/components/places/tests/browser/browser_library_infoBox.js b/browser/components/places/tests/browser/browser_library_infoBox.js index 8189438f3c2e..644e216cdc7c 100644 --- a/browser/components/places/tests/browser/browser_library_infoBox.js +++ b/browser/components/places/tests/browser/browser_library_infoBox.js @@ -16,7 +16,7 @@ var gLibrary; gTests.push({ desc: "Bug 430148 - Remove or hide the more/less button in details pane...", - run: function() { + run() { var PO = gLibrary.PlacesOrganizer; let ContentTree = gLibrary.ContentTree; var infoBoxExpanderWrapper = getAndCheckElmtById("infoBoxExpanderWrapper"); diff --git a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js b/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js index 7cea38f20ce8..2c739c04fc34 100644 --- a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js +++ b/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js @@ -64,7 +64,7 @@ function test() { .getItemAnnotation(items[i], PlacesUIUtils.ORGANIZER_QUERY_ANNO); var query = { name: queryName, - itemId: itemId, + itemId, correctTitle: PlacesUtils.bookmarks.getItemTitle(itemId) } switch (queryName) { case "BookmarksToolbar": diff --git a/browser/components/places/tests/browser/browser_library_middleclick.js b/browser/components/places/tests/browser/browser_library_middleclick.js index 0bde80bc0165..bc1605ce5d84 100644 --- a/browser/components/places/tests/browser/browser_library_middleclick.js +++ b/browser/components/places/tests/browser/browser_library_middleclick.js @@ -18,7 +18,7 @@ var gTabsListener = { _loadedURIs: [], _openTabsCount: 0, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (aEvent.type != "TabOpen") return; @@ -32,7 +32,7 @@ var gTabsListener = { "Tab has been opened in current browser window"); }, - onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, + onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) { var spec = aLocationURI.spec; ok(true, spec); @@ -76,7 +76,7 @@ gTests.push({ URIs: ["about:buildconfig"], _itemId: -1, - setup: function() { + setup() { var bs = PlacesUtils.bookmarks; // Add a new unsorted bookmark. this._itemId = bs.insertBookmark(bs.unfiledBookmarksFolder, @@ -92,11 +92,11 @@ gTests.push({ is(bookmarkNode.uri, this.URIs[0], "Found bookmark in the right pane"); }, - finish: function() { + finish() { setTimeout(runNextTest, 0); }, - cleanup: function() { + cleanup() { PlacesUtils.bookmarks.removeItem(this._itemId); } }); @@ -109,7 +109,7 @@ gTests.push({ URIs: ["about:buildconfig", "about:"], _folderId: -1, - setup: function() { + setup() { var bs = PlacesUtils.bookmarks; // Create a new folder. var folderId = bs.createFolder(bs.unfiledBookmarksFolder, @@ -134,11 +134,11 @@ gTests.push({ is(folderNode.title, "Folder", "Found folder in the right pane"); }, - finish: function() { + finish() { setTimeout(runNextTest, 0); }, - cleanup: function() { + cleanup() { PlacesUtils.bookmarks.removeItem(this._folderId); } }); @@ -152,7 +152,7 @@ gTests.push({ _folderId: -1, _queryId: -1, - setup: function() { + setup() { var bs = PlacesUtils.bookmarks; // Create a new folder. var folderId = bs.createFolder(bs.unfiledBookmarksFolder, @@ -191,11 +191,11 @@ gTests.push({ is(folderNode.title, "Query", "Found query in the right pane"); }, - finish: function() { + finish() { setTimeout(runNextTest, 0); }, - cleanup: function() { + cleanup() { PlacesUtils.bookmarks.removeItem(this._folderId); PlacesUtils.bookmarks.removeItem(this._queryId); } diff --git a/browser/components/places/tests/browser/browser_library_views_liveupdate.js b/browser/components/places/tests/browser/browser_library_views_liveupdate.js index a70e4ef45806..d84c587bb83d 100644 --- a/browser/components/places/tests/browser/browser_library_views_liveupdate.js +++ b/browser/components/places/tests/browser/browser_library_views_liveupdate.js @@ -154,10 +154,10 @@ var bookmarksObserver = { ]), // nsIAnnotationObserver - onItemAnnotationSet: function() {}, - onItemAnnotationRemoved: function() {}, - onPageAnnotationSet: function() {}, - onPageAnnotationRemoved: function() {}, + onItemAnnotationSet() {}, + onItemAnnotationRemoved() {}, + onPageAnnotationSet() {}, + onPageAnnotationRemoved() {}, // nsINavBookmarkObserver onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, aItemType, @@ -191,7 +191,7 @@ var bookmarksObserver = { is(node, null, "Places node not found in left pane"); }, - onItemMoved: function(aItemId, + onItemMoved(aItemId, aOldFolderId, aOldIndex, aNewFolderId, aNewIndex, aItemType) { var node = null; @@ -219,7 +219,7 @@ var bookmarksObserver = { onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {}, onEndUpdateBatch: function PSB_onEndUpdateBatch() {}, - onItemVisited: function() {}, + onItemVisited() {}, onItemChanged: function PSB_onItemChanged(aItemId, aProperty, aIsAnnotationProperty, aNewValue) { if (aProperty == "title") { diff --git a/browser/components/places/tests/browser/browser_sidebarpanels_click.js b/browser/components/places/tests/browser/browser_sidebarpanels_click.js index b1db4e78a02f..48c7fd4e5ef9 100644 --- a/browser/components/places/tests/browser/browser_sidebarpanels_click.js +++ b/browser/components/places/tests/browser/browser_sidebarpanels_click.js @@ -27,7 +27,7 @@ function test() { tests.push({ _itemID: null, - init: function(aCallback) { + init(aCallback) { // Add a bookmark to the Unfiled Bookmarks folder. this._itemID = PlacesUtils.bookmarks.insertBookmark( PlacesUtils.unfiledBookmarksFolderId, PlacesUtils._uri(TEST_URL), @@ -35,12 +35,12 @@ function test() { ); aCallback(); }, - prepare: function() { + prepare() { }, - selectNode: function(tree) { + selectNode(tree) { tree.selectItems([this._itemID]); }, - cleanup: function(aCallback) { + cleanup(aCallback) { PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId); executeSoon(aCallback); }, @@ -50,23 +50,23 @@ function test() { }); tests.push({ - init: function(aCallback) { + init(aCallback) { // Add a history entry. let uri = PlacesUtils._uri(TEST_URL); PlacesTestUtils.addVisits({ - uri: uri, visitDate: Date.now() * 1000, + uri, visitDate: Date.now() * 1000, transition: PlacesUtils.history.TRANSITION_TYPED }).then(aCallback); }, - prepare: function() { + prepare() { sidebar.contentDocument.getElementById("byvisited").doCommand(); }, - selectNode: function(tree) { + selectNode(tree) { tree.selectNode(tree.view.nodeForTreeIndex(0)); is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected"); is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked"); }, - cleanup: function(aCallback) { + cleanup(aCallback) { PlacesTestUtils.clearHistory().then(aCallback); }, sidebarName: HISTORY_SIDEBAR_ID, diff --git a/browser/components/places/tests/browser/browser_views_liveupdate.js b/browser/components/places/tests/browser/browser_views_liveupdate.js index add7984a82d8..a3d8d2ecaba2 100644 --- a/browser/components/places/tests/browser/browser_views_liveupdate.js +++ b/browser/components/places/tests/browser/browser_views_liveupdate.js @@ -192,10 +192,10 @@ var bookmarksObserver = { ]), // nsIAnnotationObserver - onItemAnnotationSet: function() {}, - onItemAnnotationRemoved: function() {}, - onPageAnnotationSet: function() {}, - onPageAnnotationRemoved: function() {}, + onItemAnnotationSet() {}, + onItemAnnotationRemoved() {}, + onPageAnnotationSet() {}, + onPageAnnotationRemoved() {}, // nsINavBookmarkObserver onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, @@ -223,7 +223,7 @@ var bookmarksObserver = { } }, - onItemMoved: function(aItemId, + onItemMoved(aItemId, aOldFolderId, aOldIndex, aNewFolderId, aNewIndex, aItemType) { @@ -242,7 +242,7 @@ var bookmarksObserver = { onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {}, onEndUpdateBatch: function PSB_onEndUpdateBatch() {}, - onItemVisited: function() {}, + onItemVisited() {}, onItemChanged: function PSB_onItemChanged(aItemId, aProperty, aIsAnnotationProperty, aNewValue, diff --git a/browser/components/places/tests/browser/head.js b/browser/components/places/tests/browser/head.js index c6190db4c17c..1bfd71cb59c9 100644 --- a/browser/components/places/tests/browser/head.js +++ b/browser/components/places/tests/browser/head.js @@ -116,9 +116,9 @@ function waitForAsyncUpdates(aCallback, aScope, aArguments) let commit = db.createAsyncStatement("COMMIT"); commit.executeAsync({ - handleResult: function() {}, - handleError: function() {}, - handleCompletion: function(aReason) + handleResult() {}, + handleError() {}, + handleCompletion(aReason) { aCallback.apply(scope, args); } diff --git a/browser/components/places/tests/unit/test_421483.js b/browser/components/places/tests/unit/test_421483.js index a0d1383728e2..ac086a2e3362 100644 --- a/browser/components/places/tests/unit/test_421483.js +++ b/browser/components/places/tests/unit/test_421483.js @@ -79,7 +79,7 @@ add_task(function* move_smart_bookmark_rename_and_restore() { // change title and move into new subfolder yield PlacesUtils.bookmarks.update({ - guid: guid, + guid, parentGuid: subfolder.guid, index: PlacesUtils.bookmarks.DEFAULT_INDEX, title: "new title" diff --git a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js b/browser/components/places/tests/unit/test_PUIU_makeTransaction.js index da8191b0fc23..dcc3645b9119 100644 --- a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js +++ b/browser/components/places/tests/unit/test_PUIU_makeTransaction.js @@ -4,7 +4,7 @@ function waitForBookmarkNotification(aNotification, aCallback, aProperty) { PlacesUtils.bookmarks.addObserver({ - validate: function(aMethodName, aData) + validate(aMethodName, aData) { if (aMethodName == aNotification && (!aProperty || aProperty == aData.property)) { diff --git a/browser/components/places/tests/unit/test_clearHistory_shutdown.js b/browser/components/places/tests/unit/test_clearHistory_shutdown.js index 4bf88b04aa8a..c020bdbd99fb 100644 --- a/browser/components/places/tests/unit/test_clearHistory_shutdown.js +++ b/browser/components/places/tests/unit/test_clearHistory_shutdown.js @@ -133,11 +133,11 @@ function storeCache(aURL, aContent) { return new Promise(resolve => { let storeCacheListener = { - onCacheEntryCheck: function(entry, appcache) { + onCacheEntryCheck(entry, appcache) { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable: function(entry, isnew, appcache, status) { + onCacheEntryAvailable(entry, isnew, appcache, status) { do_check_eq(status, Cr.NS_OK); entry.setMetaDataElement("servertype", "0"); @@ -168,7 +168,7 @@ function checkCache(aURL) { return new Promise(resolve => { let checkCacheListener = { - onCacheEntryAvailable: function(entry, isnew, appcache, status) { + onCacheEntryAvailable(entry, isnew, appcache, status) { do_check_eq(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND); resolve(); } diff --git a/browser/components/preferences/SiteDataManager.jsm b/browser/components/preferences/SiteDataManager.jsm index 8d2be6cb1ed9..6107f2361096 100644 --- a/browser/components/preferences/SiteDataManager.jsm +++ b/browser/components/preferences/SiteDataManager.jsm @@ -54,8 +54,8 @@ this.SiteDataManager = { if (status === Ci.nsIPermissionManager.ALLOW_ACTION || status === Ci.nsIPermissionManager.DENY_ACTION) { this._sites.set(perm.principal.origin, { - perm: perm, - status: status, + perm, + status, quotaUsage: 0, appCacheList: [], diskCacheList: [] @@ -79,7 +79,7 @@ this.SiteDataManager = { for (let site of this._sites.values()) { promises.push(new Promise(resolve => { let callback = { - onUsageResult: function(request) { + onUsageResult(request) { site.quotaUsage = request.usage; resolve(); } @@ -121,7 +121,7 @@ this.SiteDataManager = { if (this._sites.size) { let sites = this._sites; let visitor = { - onCacheEntryInfo: function(uri, idEnhance, dataSize) { + onCacheEntryInfo(uri, idEnhance, dataSize) { for (let site of sites.values()) { if (site.perm.matchesURI(uri, true)) { site.diskCacheList.push({ @@ -132,7 +132,7 @@ this.SiteDataManager = { } } }, - onCacheEntryVisitCompleted: function() { + onCacheEntryVisitCompleted() { resolve(); } }; diff --git a/browser/components/preferences/blocklists.js b/browser/components/preferences/blocklists.js index 208a329d5f82..70ea7f1c43ba 100644 --- a/browser/components/preferences/blocklists.js +++ b/browser/components/preferences/blocklists.js @@ -22,7 +22,7 @@ var gBlocklistManager = { get rowCount() { return this._rowCount; }, - getCellText: function(row, column) { + getCellText(row, column) { if (column.id == "listCol") { let list = gBlocklistManager._blockLists[row]; let desc = list.description ? list.description : ""; @@ -33,21 +33,21 @@ var gBlocklistManager = { return ""; }, - isSeparator: function(index) { return false; }, - isSorted: function() { return false; }, - isContainer: function(index) { return false; }, - setTree: function(tree) {}, - getImageSrc: function(row, column) {}, - getProgressMode: function(row, column) {}, - getCellValue: function(row, column) { + isSeparator(index) { return false; }, + isSorted() { return false; }, + isContainer(index) { return false; }, + setTree(tree) {}, + getImageSrc(row, column) {}, + getProgressMode(row, column) {}, + getCellValue(row, column) { if (column.id == "selectionCol") return gBlocklistManager._blockLists[row].selected; return undefined; }, - cycleHeader: function(column) {}, - getRowProperties: function(row) { return ""; }, - getColumnProperties: function(column) { return ""; }, - getCellProperties: function(row, column) { + cycleHeader(column) {}, + getRowProperties(row) { return ""; }, + getColumnProperties(column) { return ""; }, + getCellProperties(row, column) { if (column.id == "selectionCol") { return "checkmark"; } @@ -56,7 +56,7 @@ var gBlocklistManager = { } }, - onWindowKeyPress: function(event) { + onWindowKeyPress(event) { if (event.keyCode == KeyEvent.DOM_VK_ESCAPE) { window.close(); } else if (event.keyCode == KeyEvent.DOM_VK_RETURN) { @@ -64,13 +64,13 @@ var gBlocklistManager = { } }, - onLoad: function() { + onLoad() { this._bundle = document.getElementById("bundlePreferences"); let params = window.arguments[0]; this.init(params); }, - init: function(params) { + init(params) { if (this._type) { // reusing an open dialog, clear the old observer this.uninit(); @@ -97,9 +97,9 @@ var gBlocklistManager = { this._loadBlockLists(); }, - uninit: function() {}, + uninit() {}, - onListSelected: function() { + onListSelected() { for (let list of this._blockLists) { list.selected = false; } @@ -108,7 +108,7 @@ var gBlocklistManager = { this._updateTree(); }, - onApplyChanges: function() { + onApplyChanges() { let activeList = this._getActiveList(); let selected = null; for (let list of this._blockLists) { @@ -153,7 +153,7 @@ var gBlocklistManager = { window.close(); }, - _loadBlockLists: function() { + _loadBlockLists() { this._blockLists = []; // Load blocklists into a table. @@ -171,7 +171,7 @@ var gBlocklistManager = { this._updateTree(); }, - _createOrUpdateBlockList: function(itemName) { + _createOrUpdateBlockList(itemName) { let branch = Services.prefs.getBranch(LISTS_PREF_BRANCH); let key = branch.getCharPref(itemName); let value = this._bundle.getString(key); @@ -192,13 +192,13 @@ var gBlocklistManager = { return list; }, - _updateTree: function() { + _updateTree() { this._tree = document.getElementById("blocklistsTree"); this._view._rowCount = this._blockLists.length; this._tree.view = this._view; }, - _getActiveList: function() { + _getActiveList() { let trackingTable = Services.prefs.getCharPref(TRACKING_TABLE_PREF); return trackingTable.includes(CONTENT_LIST_ID) ? CONTENT_LIST_ID : BASE_LIST_ID; } diff --git a/browser/components/preferences/connection.js b/browser/components/preferences/connection.js index 9997a1a7490c..128c9caa8549 100644 --- a/browser/components/preferences/connection.js +++ b/browser/components/preferences/connection.js @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gConnectionsDialog = { - beforeAccept: function() + beforeAccept() { var proxyTypePref = document.getElementById("network.proxy.type"); if (proxyTypePref.value == 2) { @@ -52,13 +52,13 @@ var gConnectionsDialog = { return true; }, - checkForSystemProxy: function() + checkForSystemProxy() { if ("@mozilla.org/system-proxy-settings;1" in Components.classes) document.getElementById("systemPref").removeAttribute("hidden"); }, - proxyTypeChanged: function() + proxyTypeChanged() { var proxyTypePref = document.getElementById("network.proxy.type"); @@ -84,7 +84,7 @@ var gConnectionsDialog = { this.updateReloadButton(); }, - updateDNSPref: function() + updateDNSPref() { var socksVersionPref = document.getElementById("network.proxy.socks_version"); var socksDNSPref = document.getElementById("network.proxy.socks_remote_dns"); @@ -94,7 +94,7 @@ var gConnectionsDialog = { return undefined; }, - updateReloadButton: function() + updateReloadButton() { // Disable the "Reload PAC" button if the selected proxy type is not PAC or // if the current value of the PAC textbox does not match the value stored @@ -116,13 +116,13 @@ var gConnectionsDialog = { (proxyTypeCur != 2 || proxyType != 2 || typedURL != pacURL); }, - readProxyType: function() + readProxyType() { this.proxyTypeChanged(); return undefined; }, - updateProtocolPrefs: function() + updateProtocolPrefs() { var proxyTypePref = document.getElementById("network.proxy.type"); var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); @@ -156,7 +156,7 @@ var gConnectionsDialog = { return undefined; }, - readProxyProtocolPref: function(aProtocol, aIsPort) + readProxyProtocolPref(aProtocol, aIsPort) { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) { @@ -168,13 +168,13 @@ var gConnectionsDialog = { return backupPref.hasUserValue ? backupPref.value : undefined; }, - reloadPAC: function() + reloadPAC() { Components.classes["@mozilla.org/network/protocol-proxy-service;1"]. getService().reloadPAC(); }, - doAutoconfigURLFixup: function() + doAutoconfigURLFixup() { var autoURL = document.getElementById("networkProxyAutoconfigURL"); var autoURLPref = document.getElementById("network.proxy.autoconfig_url"); @@ -185,7 +185,7 @@ var gConnectionsDialog = { } catch (ex) {} }, - sanitizeNoProxiesPref: function() + sanitizeNoProxiesPref() { var noProxiesPref = document.getElementById("network.proxy.no_proxies_on"); // replace substrings of ; and \n with commas if they're neither immediately @@ -195,7 +195,7 @@ var gConnectionsDialog = { noProxiesPref.value = noProxiesPref.value.replace(/[;\n]/g, ''); }, - readHTTPProxyServer: function() + readHTTPProxyServer() { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) @@ -203,7 +203,7 @@ var gConnectionsDialog = { return undefined; }, - readHTTPProxyPort: function() + readHTTPProxyPort() { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) diff --git a/browser/components/preferences/cookies.js b/browser/components/preferences/cookies.js index 82abbebb00ef..55b8e6cbb26b 100644 --- a/browser/components/preferences/cookies.js +++ b/browser/components/preferences/cookies.js @@ -21,7 +21,7 @@ var gCookiesWindow = { _tree : null, _bundle : null, - init: function() { + init() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); os.addObserver(this, "cookie-changed", false); @@ -39,14 +39,14 @@ var gCookiesWindow = { } }, - uninit: function() { + uninit() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); os.removeObserver(this, "cookie-changed"); os.removeObserver(this, "perm-changed"); }, - _populateList: function(aInitialLoad) { + _populateList(aInitialLoad) { this._loadCookies(); this._tree.view = this._view; if (aInitialLoad) @@ -69,7 +69,7 @@ var gCookiesWindow = { this._saveState(); }, - _cookieEquals: function(aCookieA, aCookieB, aStrippedHost) { + _cookieEquals(aCookieA, aCookieB, aStrippedHost) { return aCookieA.rawHost == aStrippedHost && aCookieA.name == aCookieB.name && aCookieA.path == aCookieB.path && @@ -77,7 +77,7 @@ var gCookiesWindow = { aCookieB.originAttributes); }, - _isPrivateCookie: function(aCookie) { + _isPrivateCookie(aCookie) { let { userContextId } = aCookie.originAttributes; if (!userContextId) { // Default identity is public. @@ -86,7 +86,7 @@ var gCookiesWindow = { return !ContextualIdentityService.getIdentityFromId(userContextId).public; }, - observe: function(aCookie, aTopic, aData) { + observe(aCookie, aTopic, aData) { if (aTopic != "cookie-changed") return; @@ -123,7 +123,7 @@ var gCookiesWindow = { // and is rather complicated as selection tracking is difficult }, - _handleCookieChanged: function(changedCookie, strippedHost) { + _handleCookieChanged(changedCookie, strippedHost) { var rowIndex = 0; var cookieItem = null; if (!this._view._filtered) { @@ -172,7 +172,7 @@ var gCookiesWindow = { this._updateCookieData(cookieItem); }, - _handleCookieAdded: function(changedCookie, strippedHost) { + _handleCookieAdded(changedCookie, strippedHost) { var rowCountImpact = 0; var addedHost = { value: 0 }; this._addCookie(strippedHost, changedCookie, addedHost); @@ -212,7 +212,7 @@ var gCookiesWindow = { return this._rowCount; }, - _getItemAtIndex: function(aIndex) { + _getItemAtIndex(aIndex) { if (this._filtered) return this._filterSet[aIndex]; @@ -267,7 +267,7 @@ var gCookiesWindow = { return null; }, - _removeItemAtIndex: function(aIndex, aCount) { + _removeItemAtIndex(aIndex, aCount) { let removeCount = aCount === undefined ? 1 : aCount; if (this._filtered) { // remove the cookies from the unfiltered set so that they @@ -306,11 +306,11 @@ var gCookiesWindow = { } }, - _invalidateCache: function(aIndex) { + _invalidateCache(aIndex) { this._cacheValid = Math.min(this._cacheValid, aIndex); }, - getCellText: function(aIndex, aColumn) { + getCellText(aIndex, aColumn) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) @@ -331,10 +331,10 @@ var gCookiesWindow = { _selection: null, get selection() { return this._selection; }, set selection(val) { this._selection = val; return val; }, - getRowProperties: function(aIndex) { return ""; }, - getCellProperties: function(aIndex, aColumn) { return ""; }, - getColumnProperties: function(aColumn) { return ""; }, - isContainer: function(aIndex) { + getRowProperties(aIndex) { return ""; }, + getCellProperties(aIndex, aColumn) { return ""; }, + getColumnProperties(aColumn) { return ""; }, + isContainer(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -342,7 +342,7 @@ var gCookiesWindow = { } return false; }, - isContainerOpen: function(aIndex) { + isContainerOpen(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -350,7 +350,7 @@ var gCookiesWindow = { } return false; }, - isContainerEmpty: function(aIndex) { + isContainerEmpty(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -358,11 +358,11 @@ var gCookiesWindow = { } return false; }, - isSeparator: function(aIndex) { return false; }, - isSorted: function(aIndex) { return false; }, - canDrop: function(aIndex, aOrientation) { return false; }, - drop: function(aIndex, aOrientation) {}, - getParentIndex: function(aIndex) { + isSeparator(aIndex) { return false; }, + isSorted(aIndex) { return false; }, + canDrop(aIndex, aOrientation) { return false; }, + drop(aIndex, aOrientation) {}, + getParentIndex(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); // If an item has no parent index (i.e. it is at the top level) this @@ -374,7 +374,7 @@ var gCookiesWindow = { } return -1; }, - hasNextSibling: function(aParentIndex, aIndex) { + hasNextSibling(aParentIndex, aIndex) { if (!this._filtered) { // |aParentIndex| appears to be bogus, but we can get the real // parent index by getting the entry for |aIndex| and reading the @@ -399,7 +399,7 @@ var gCookiesWindow = { } return aIndex < this.rowCount - 1; }, - hasPreviousSibling: function(aIndex) { + hasPreviousSibling(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -409,7 +409,7 @@ var gCookiesWindow = { } return aIndex > 0; }, - getLevel: function(aIndex) { + getLevel(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return 0; @@ -417,11 +417,11 @@ var gCookiesWindow = { } return 0; }, - getImageSrc: function(aIndex, aColumn) {}, - getProgressMode: function(aIndex, aColumn) {}, - getCellValue: function(aIndex, aColumn) {}, - setTree: function(aTree) {}, - toggleOpenState: function(aIndex) { + getImageSrc(aIndex, aColumn) {}, + getProgressMode(aIndex, aColumn) {}, + getCellValue(aIndex, aColumn) {}, + setTree(aTree) {}, + toggleOpenState(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return; @@ -434,28 +434,28 @@ var gCookiesWindow = { gCookiesWindow._tree.treeBoxObject.invalidateRow(aIndex); } }, - cycleHeader: function(aColumn) {}, - selectionChanged: function() {}, - cycleCell: function(aIndex, aColumn) {}, - isEditable: function(aIndex, aColumn) { + cycleHeader(aColumn) {}, + selectionChanged() {}, + cycleCell(aIndex, aColumn) {}, + isEditable(aIndex, aColumn) { return false; }, - isSelectable: function(aIndex, aColumn) { + isSelectable(aIndex, aColumn) { return false; }, - setCellValue: function(aIndex, aColumn, aValue) {}, - setCellText: function(aIndex, aColumn, aValue) {}, - performAction: function(aAction) {}, - performActionOnRow: function(aAction, aIndex) {}, - performActionOnCell: function(aAction, aindex, aColumn) {} + setCellValue(aIndex, aColumn, aValue) {}, + setCellText(aIndex, aColumn, aValue) {}, + performAction(aAction) {}, + performActionOnRow(aAction, aIndex) {}, + performActionOnCell(aAction, aindex, aColumn) {} }, - _makeStrippedHost: function(aHost) { + _makeStrippedHost(aHost) { var formattedHost = aHost.charAt(0) == "." ? aHost.substring(1, aHost.length) : aHost; return formattedHost.substring(0, 4) == "www." ? formattedHost.substring(4, formattedHost.length) : formattedHost; }, - _addCookie: function(aStrippedHost, aCookie, aHostCount) { + _addCookie(aStrippedHost, aCookie, aHostCount) { if (!(aStrippedHost in this._hosts) || !this._hosts[aStrippedHost]) { this._hosts[aStrippedHost] = { cookies : [], rawHost : aStrippedHost, @@ -470,7 +470,7 @@ var gCookiesWindow = { this._hosts[aStrippedHost].cookies.push(c); }, - _makeCookieObject: function(aStrippedHost, aCookie) { + _makeCookieObject(aStrippedHost, aCookie) { var c = { name : aCookie.name, value : aCookie.value, isDomain : aCookie.isDomain, @@ -485,7 +485,7 @@ var gCookiesWindow = { return c; }, - _loadCookies: function() { + _loadCookies() { var e = this._cm.enumerator; var hostCount = { value: 0 }; this._hosts = {}; @@ -506,7 +506,7 @@ var gCookiesWindow = { this._view._rowCount = hostCount.value; }, - formatExpiresString: function(aExpires) { + formatExpiresString(aExpires) { if (aExpires) { var date = new Date(1000 * aExpires); const locale = Components.classes["@mozilla.org/chrome/chrome-registry;1"] @@ -519,7 +519,7 @@ var gCookiesWindow = { return this._bundle.getString("expireAtEndOfSession"); }, - _getUserContextString: function(aUserContextId) { + _getUserContextString(aUserContextId) { if (parseInt(aUserContextId) == 0) { return this._bundle.getString("defaultUserContextLabel"); } @@ -527,7 +527,7 @@ var gCookiesWindow = { return ContextualIdentityService.getUserContextLabel(aUserContextId); }, - _updateCookieData: function(aItem) { + _updateCookieData(aItem) { var seln = this._view.selection; var ids = ["name", "value", "host", "path", "isSecure", "expires", "userContext"]; var properties; @@ -557,7 +557,7 @@ var gCookiesWindow = { document.getElementById(property).value = properties[property]; }, - onCookieSelected: function() { + onCookieSelected() { var item; var seln = this._tree.view.selection; if (!this._view._filtered) @@ -602,7 +602,7 @@ var gCookiesWindow = { } }, - deleteCookie: function() { + deleteCookie() { // Selection Notes // - Selection always moves to *NEXT* adjacent item unless item // is last child at a given level in which case it moves to *PREVIOUS* @@ -728,7 +728,7 @@ var gCookiesWindow = { } }, - deleteAllCookies: function() { + deleteAllCookies() { if (this._view._filtered) { var rowCount = this._view.rowCount; var deleteItems = []; @@ -747,7 +747,7 @@ var gCookiesWindow = { this.focusFilterBox(); }, - onCookieKeyPress: function(aEvent) { + onCookieKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) { this.deleteCookie(); } else if (AppConstants.platform == "macosx" && @@ -758,7 +758,7 @@ var gCookiesWindow = { _lastSortProperty : "", _lastSortAscending: false, - sort: function(aProperty) { + sort(aProperty) { var ascending = (aProperty == this._lastSortProperty) ? !this._lastSortAscending : true; // Sort the Non-Filtered Host Collections if (aProperty == "rawHost") { @@ -809,7 +809,7 @@ var gCookiesWindow = { this._lastSortProperty = aProperty; }, - clearFilter: function() { + clearFilter() { // Revert to single-select in the tree this._tree.setAttribute("seltype", "single"); @@ -851,13 +851,13 @@ var gCookiesWindow = { this._updateRemoveAllButton(); }, - _cookieMatchesFilter: function(aCookie) { + _cookieMatchesFilter(aCookie) { return aCookie.rawHost.indexOf(this._view._filterValue) != -1 || aCookie.name.indexOf(this._view._filterValue) != -1 || aCookie.value.indexOf(this._view._filterValue) != -1; }, - _filterCookies: function(aFilterValue) { + _filterCookies(aFilterValue) { this._view._filterValue = aFilterValue; var cookies = []; for (let i = 0; i < gCookiesWindow._hostOrder.length; ++i) { // var host in gCookiesWindow._hosts) { @@ -873,7 +873,7 @@ var gCookiesWindow = { _lastSelectedRanges: [], _openIndices: [], - _saveState: function() { + _saveState() { // Save selection var seln = this._view.selection; this._lastSelectedRanges = []; @@ -897,7 +897,7 @@ var gCookiesWindow = { document.getElementById("removeAllCookies").disabled = this._view._rowCount == 0; }, - filter: function() { + filter() { var filter = document.getElementById("filter").value; if (filter == "") { gCookiesWindow.clearFilter(); @@ -930,18 +930,18 @@ var gCookiesWindow = { this._updateRemoveAllButton(); }, - setFilter: function(aFilterString) { + setFilter(aFilterString) { document.getElementById("filter").value = aFilterString; this.filter(); }, - focusFilterBox: function() { + focusFilterBox() { var filter = document.getElementById("filter"); filter.focus(); filter.select(); }, - onWindowKeyPress: function(aEvent) { + onWindowKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); } diff --git a/browser/components/preferences/fonts.js b/browser/components/preferences/fonts.js index e6b2a0acd73d..ac66044a2b80 100644 --- a/browser/components/preferences/fonts.js +++ b/browser/components/preferences/fonts.js @@ -19,7 +19,7 @@ const kFontSizeFmtFixed = "font.size.fixed.%LANG%"; const kFontMinSizeFmt = "font.minimum-size.%LANG%"; var gFontsDialog = { - _selectLanguageGroup: function(aLanguageGroup) + _selectLanguageGroup(aLanguageGroup) { var prefs = [{ format: kDefaultFontType, type: "string", element: "defaultFontType", fonttype: null}, { format: kFontNameFmtSerif, type: "fontname", element: "serif", fonttype: "serif" }, @@ -58,26 +58,26 @@ var gFontsDialog = { } }, - readFontLanguageGroup: function() + readFontLanguageGroup() { var languagePref = document.getElementById("font.language.group"); this._selectLanguageGroup(languagePref.value); return undefined; }, - readUseDocumentFonts: function() + readUseDocumentFonts() { var preference = document.getElementById("browser.display.use_document_fonts"); return preference.value == 1; }, - writeUseDocumentFonts: function() + writeUseDocumentFonts() { var useDocumentFonts = document.getElementById("useDocumentFonts"); return useDocumentFonts.checked ? 1 : 0; }, - onBeforeAccept: function() + onBeforeAccept() { let preferences = document.querySelectorAll("preference[id*='font.minimum-size']"); // It would be good if we could avoid touching languages the pref pages won't use, but diff --git a/browser/components/preferences/in-content/tests/browser_advanced_siteData.js b/browser/components/preferences/in-content/tests/browser_advanced_siteData.js index 043c8aea072d..4b635a2138de 100644 --- a/browser/components/preferences/in-content/tests/browser_advanced_siteData.js +++ b/browser/components/preferences/in-content/tests/browser_advanced_siteData.js @@ -21,13 +21,13 @@ const mockOfflineAppCacheHelper = { originalClear: null, - register: function() { + register() { this.originalClear = OfflineAppCacheHelper.clear; this.clear = sinon.spy(); OfflineAppCacheHelper.clear = this.clear; }, - unregister: function() { + unregister() { OfflineAppCacheHelper.clear = this.originalClear; } }; @@ -55,7 +55,7 @@ function getQuotaUsage(origin) { function getCacheUsage() { return new Promise(resolve => { let obs = { - onNetworkCacheDiskConsumption: function(usage) { + onNetworkCacheDiskConsumption(usage) { resolve(usage); }, QueryInterface: XPCOMUtils.generateQI([ diff --git a/browser/components/preferences/in-content/tests/browser_advanced_update.js b/browser/components/preferences/in-content/tests/browser_advanced_update.js index d9d7aa33ae7a..9a18fcecae6b 100644 --- a/browser/components/preferences/in-content/tests/browser_advanced_update.js +++ b/browser/components/preferences/in-content/tests/browser_advanced_update.js @@ -20,14 +20,14 @@ const mockUpdateManager = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateManager]), - createInstance: function(outer, iiD) { + createInstance(outer, iiD) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } return this.QueryInterface(iiD); }, - register: function() { + register() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); if (!registrar.isCIDRegistered(this._mockClassId)) { this._originalClassId = registrar.contractIDToCID(this.contractId); @@ -37,7 +37,7 @@ const mockUpdateManager = { } }, - unregister: function() { + unregister() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(this._mockClassId, this); registrar.registerFactory(this._originalClassId, "", this.contractId, this._originalFactory); @@ -47,7 +47,7 @@ const mockUpdateManager = { return this._updates.length; }, - getUpdateAt: function(index) { + getUpdateAt(index) { return this._updates[index]; }, diff --git a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js b/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js index 32c1bd726374..40741cccab77 100644 --- a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js +++ b/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js @@ -27,14 +27,14 @@ add_task(function*() { // Simulate a dumb font backend. win.FontBuilder._enumerator = { _list: ["MockedFont1", "MockedFont2", "MockedFont3"], - EnumerateFonts: function(lang, type, list) { + EnumerateFonts(lang, type, list) { return this._list; }, - EnumerateAllFonts: function() { + EnumerateAllFonts() { return this._list; }, - getDefaultFont: function() { return null; }, - getStandardFamilyName: function(name) { return name; }, + getDefaultFont() { return null; }, + getStandardFamilyName(name) { return name; }, }; win.FontBuilder._allFonts = null; win.FontBuilder._langGroupSupported = false; diff --git a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js b/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js index bc2c6d800296..8d0a910f0c14 100644 --- a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js +++ b/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js @@ -35,7 +35,7 @@ function openPreferencesViaHash(aPane) { let win = gBrowser.contentWindow; let selectedPane = win.history.state; gBrowser.removeCurrentTab(); - deferred.resolve({selectedPane: selectedPane}); + deferred.resolve({selectedPane}); }); }, true); diff --git a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js b/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js index 15342f127529..d604332096b5 100644 --- a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js +++ b/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js @@ -14,7 +14,7 @@ var testRunner = { tests: [ { - test: function(params) { + test(params) { params.url.value = "test.com"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -28,7 +28,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "test.com"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", @@ -41,7 +41,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "test.com"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", @@ -54,7 +54,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "test.com"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -64,7 +64,7 @@ var testRunner = { }, { expectPermObservancesDuringTestFunction: true, - test: function(params) { + test(params) { let uri = params.ioService.newURI("http://test.com", null, null); params.pm.add(uri, "popup", Ci.nsIPermissionManager.DENY_ACTION); is(params.tree.view.rowCount, 0, "adding unrelated permission should not change display"); @@ -72,13 +72,13 @@ var testRunner = { }, observances: [{ type: "popup", origin: "http://test.com", data: "added", capability: Ci.nsIPermissionManager.DENY_ACTION }], - cleanUp: function(params) { + cleanUp(params) { let uri = params.ioService.newURI("http://test.com", null, null); params.pm.remove(uri, "popup"); }, }, { - test: function(params) { + test(params) { params.url.value = "https://test.com:12345"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -92,7 +92,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "https://test.com:12345"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", @@ -105,7 +105,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "https://test.com:12345"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", @@ -118,7 +118,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "https://test.com:12345"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -127,7 +127,7 @@ var testRunner = { observances: [{ type: "cookie", origin: "https://test.com:12345", data: "deleted" }], }, { - test: function(params) { + test(params) { params.url.value = "localhost:12345"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -141,7 +141,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "localhost:12345"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", @@ -154,7 +154,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "localhost:12345"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", @@ -167,7 +167,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "localhost:12345"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -220,7 +220,7 @@ var testRunner = { _currentTest: -1, - runTests: function() { + runTests() { this._currentTest++; info("Running test #" + (this._currentTest + 1) + "\n"); @@ -236,11 +236,11 @@ var testRunner = { }); }, - runCurrentTest: function(testNumber) { + runCurrentTest(testNumber) { return new Promise(function(resolve, reject) { let helperFunctions = { - windowLoad: function(win) { + windowLoad(win) { let doc = win.document; let params = { doc, @@ -265,7 +265,7 @@ var testRunner = { }; let permObserver = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic != "perm-changed") return; diff --git a/browser/components/preferences/in-content/tests/head.js b/browser/components/preferences/in-content/tests/head.js index 203fd686782b..d9eb3a1aabfa 100644 --- a/browser/components/preferences/in-content/tests/head.js +++ b/browser/components/preferences/in-content/tests/head.js @@ -136,7 +136,7 @@ function openPreferencesViaOpenPreferencesAPI(aPane, aAdvancedTab, aOptions) { let selectedAdvancedTab = aAdvancedTab && doc.getElementById("advancedPrefs").selectedTab.id; if (!aOptions || !aOptions.leaveOpen) gBrowser.removeCurrentTab(); - deferred.resolve({selectedPane: selectedPane, selectedAdvancedTab: selectedAdvancedTab}); + deferred.resolve({selectedPane, selectedAdvancedTab}); }); }, true); diff --git a/browser/components/preferences/languages.js b/browser/components/preferences/languages.js index 677892b942ff..2be9ddfbced2 100644 --- a/browser/components/preferences/languages.js +++ b/browser/components/preferences/languages.js @@ -10,7 +10,7 @@ var gLanguagesDialog = { _selectedItemID : null, - init: function() + init() { if (!this._availableLanguagesList.length) this._loadAvailableLanguages(); @@ -18,7 +18,7 @@ var gLanguagesDialog = { // Ugly hack used to trigger extra reflow in order to work around XUL bug 1194844; // see bug 1194346. - forceReflow: function() + forceReflow() { this._activeLanguages.style.fontKerning = "none"; setTimeout("gLanguagesDialog._activeLanguages.style.removeProperty('font-kerning')", 0); @@ -34,7 +34,7 @@ var gLanguagesDialog = { return document.getElementById("availableLanguages"); }, - _loadAvailableLanguages: function() + _loadAvailableLanguages() { // This is a parser for: resource://gre/res/language.properties // The file is formatted like so: @@ -102,7 +102,7 @@ var gLanguagesDialog = { this._buildAvailableLanguageList(); }, - _buildAvailableLanguageList: function() + _buildAvailableLanguageList() { var availableLanguagesPopup = document.getElementById("availableLanguagesPopup"); while (availableLanguagesPopup.hasChildNodes()) @@ -126,7 +126,7 @@ var gLanguagesDialog = { } }, - readAcceptLanguages: function() + readAcceptLanguages() { while (this._activeLanguages.hasChildNodes()) this._activeLanguages.removeChild(this._activeLanguages.firstChild); @@ -160,12 +160,12 @@ var gLanguagesDialog = { return undefined; }, - writeAcceptLanguages: function() + writeAcceptLanguages() { return undefined; }, - onAvailableLanguageSelect: function() + onAvailableLanguageSelect() { var addButton = document.getElementById("addButton"); addButton.disabled = false; @@ -173,7 +173,7 @@ var gLanguagesDialog = { this._availableLanguages.removeAttribute("accesskey"); }, - addLanguage: function() + addLanguage() { var selectedID = this._availableLanguages.selectedItem.id; var preference = document.getElementById("intl.accept_languages"); @@ -201,7 +201,7 @@ var gLanguagesDialog = { this._availableLanguages.setAttribute("label", this._availableLanguages.getAttribute("label2")); }, - removeLanguage: function() + removeLanguage() { // Build the new preference value string. var languagesArray = []; @@ -229,7 +229,7 @@ var gLanguagesDialog = { this._buildAvailableLanguageList(); }, - _getLanguageName: function(aABCD) + _getLanguageName(aABCD) { if (!this._availableLanguagesList.length) this._loadAvailableLanguages(); @@ -240,7 +240,7 @@ var gLanguagesDialog = { return ""; }, - moveUp: function() + moveUp() { var selectedItem = this._activeLanguages.selectedItems[0]; var previousItem = selectedItem.previousSibling; @@ -264,7 +264,7 @@ var gLanguagesDialog = { preference.value = string; }, - moveDown: function() + moveDown() { var selectedItem = this._activeLanguages.selectedItems[0]; var nextItem = selectedItem.nextSibling; @@ -288,7 +288,7 @@ var gLanguagesDialog = { preference.value = string; }, - onLanguageSelect: function() + onLanguageSelect() { var upButton = document.getElementById("up"); var downButton = document.getElementById("down"); diff --git a/browser/components/preferences/permissions.js b/browser/components/preferences/permissions.js index 43a7c02dee71..40469cdacf2a 100644 --- a/browser/components/preferences/permissions.js +++ b/browser/components/preferences/permissions.js @@ -32,7 +32,7 @@ var gPermissionManager = { { return this._rowCount; }, - getCellText: function(aRow, aColumn) + getCellText(aRow, aColumn) { if (aColumn.id == "siteCol") return gPermissionManager._permissions[aRow].origin; @@ -41,17 +41,17 @@ var gPermissionManager = { return ""; }, - isSeparator: function(aIndex) { return false; }, - isSorted: function() { return false; }, - isContainer: function(aIndex) { return false; }, - setTree: function(aTree) {}, - getImageSrc: function(aRow, aColumn) {}, - getProgressMode: function(aRow, aColumn) {}, - getCellValue: function(aRow, aColumn) {}, - cycleHeader: function(column) {}, - getRowProperties: function(row) { return ""; }, - getColumnProperties: function(column) { return ""; }, - getCellProperties: function(row, column) { + isSeparator(aIndex) { return false; }, + isSorted() { return false; }, + isContainer(aIndex) { return false; }, + setTree(aTree) {}, + getImageSrc(aRow, aColumn) {}, + getProgressMode(aRow, aColumn) {}, + getCellValue(aRow, aColumn) {}, + cycleHeader(column) {}, + getRowProperties(row) { return ""; }, + getColumnProperties(column) { return ""; }, + getCellProperties(row, column) { if (column.element.getAttribute("id") == "siteCol") return "ltr"; @@ -59,7 +59,7 @@ var gPermissionManager = { } }, - _getCapabilityString: function(aCapability) + _getCapabilityString(aCapability) { var stringKey = null; switch (aCapability) { @@ -79,7 +79,7 @@ var gPermissionManager = { return this._bundle.getString(stringKey); }, - addPermission: function(aCapability) + addPermission(aCapability) { var textbox = document.getElementById("url"); var input_url = textbox.value.replace(/^\s*/, ""); // trim any leading space @@ -127,7 +127,7 @@ var gPermissionManager = { } } - let permissionParams = {principal: principal, type: this._type, capability: aCapability}; + let permissionParams = {principal, type: this._type, capability: aCapability}; if (!permissionExists) { this._permissionsToAdd.set(principal.origin, permissionParams); this._addPermission(permissionParams); @@ -147,7 +147,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = this._permissions.length == 0; }, - _removePermission: function(aPermission) + _removePermission(aPermission) { this._removePermissionFromList(aPermission.principal); @@ -162,7 +162,7 @@ var gPermissionManager = { }, - _handleCapabilityChange: function() + _handleCapabilityChange() { // Re-do the sort, if the status changed from Block to Allow // or vice versa, since if we're sorted on status, we may no @@ -173,7 +173,7 @@ var gPermissionManager = { this._tree.treeBoxObject.invalidate(); }, - _addPermission: function(aPermission) + _addPermission(aPermission) { this._addPermissionToList(aPermission); ++this._view._rowCount; @@ -182,7 +182,7 @@ var gPermissionManager = { this._resortPermissions(); }, - _resortPermissions: function() + _resortPermissions() { gTreeUtils.sort(this._tree, this._view, this._permissions, this._lastPermissionSortColumn, @@ -191,33 +191,33 @@ var gPermissionManager = { !this._lastPermissionSortAscending); // keep sort direction }, - onHostInput: function(aSiteField) + onHostInput(aSiteField) { document.getElementById("btnSession").disabled = !aSiteField.value; document.getElementById("btnBlock").disabled = !aSiteField.value; document.getElementById("btnAllow").disabled = !aSiteField.value; }, - onWindowKeyPress: function(aEvent) + onWindowKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); }, - onHostKeyPress: function(aEvent) + onHostKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN) document.getElementById("btnAllow").click(); }, - onLoad: function() + onLoad() { this._bundle = document.getElementById("bundlePreferences"); var params = window.arguments[0]; this.init(params); }, - init: function(aParams) + init(aParams) { if (this._type) { // reusing an open dialog, clear the old observer @@ -275,7 +275,7 @@ var gPermissionManager = { urlField.focus(); }, - uninit: function() + uninit() { if (!this._observerRemoved) { Services.obs.removeObserver(this, "perm-changed"); @@ -284,7 +284,7 @@ var gPermissionManager = { } }, - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { var permission = aSubject.QueryInterface(Components.interfaces.nsIPermission); @@ -311,7 +311,7 @@ var gPermissionManager = { } }, - onPermissionSelected: function() + onPermissionSelected() { var hasSelection = this._tree.view.selection.count > 0; var hasRows = this._tree.view.rowCount > 0; @@ -319,7 +319,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = !hasRows; }, - onPermissionDeleted: function() + onPermissionDeleted() { if (!this._view.rowCount) return; @@ -333,7 +333,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = !this._permissions.length; }, - onAllPermissionsDeleted: function() + onAllPermissionsDeleted() { if (!this._view.rowCount) return; @@ -347,7 +347,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = true; }, - onPermissionKeyPress: function(aEvent) + onPermissionKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) { this.onPermissionDeleted(); @@ -359,13 +359,13 @@ var gPermissionManager = { _lastPermissionSortColumn: "", _lastPermissionSortAscending: false, - _permissionsComparator : function(a, b) + _permissionsComparator(a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }, - onPermissionSort: function(aColumn) + onPermissionSort(aColumn) { this._lastPermissionSortAscending = gTreeUtils.sort(this._tree, this._view, @@ -377,7 +377,7 @@ var gPermissionManager = { this._lastPermissionSortColumn = aColumn; }, - onApplyChanges: function() + onApplyChanges() { // Stop observing permission changes since we are about // to write out the pending adds/deletes and don't need @@ -395,7 +395,7 @@ var gPermissionManager = { window.close(); }, - _loadPermissions: function() + _loadPermissions() { this._tree = document.getElementById("permissionsTree"); this._permissions = []; @@ -417,7 +417,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = this._permissions.length == 0; }, - _addPermissionToList: function(aPermission) + _addPermissionToList(aPermission) { if (aPermission.type == this._type && (!this._manageCapability || @@ -432,7 +432,7 @@ var gPermissionManager = { } }, - _removePermissionFromList: function(aPrincipal) + _removePermissionFromList(aPrincipal) { for (let i = 0; i < this._permissions.length; ++i) { if (this._permissions[i].principal.equals(aPrincipal)) { @@ -445,7 +445,7 @@ var gPermissionManager = { } }, - setOrigin: function(aOrigin) + setOrigin(aOrigin) { document.getElementById("url").value = aOrigin; } diff --git a/browser/components/preferences/sanitize.js b/browser/components/preferences/sanitize.js index a9beea163d92..cf764086db98 100644 --- a/browser/components/preferences/sanitize.js +++ b/browser/components/preferences/sanitize.js @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gSanitizeDialog = Object.freeze({ - init: function() { + init() { let customWidthElements = document.getElementsByAttribute("dialogWidth", "*"); let isInSubdialog = document.documentElement.hasAttribute("subdialog"); for (let element of customWidthElements) { @@ -13,7 +13,7 @@ var gSanitizeDialog = Object.freeze({ this.onClearHistoryChanged(); }, - onClearHistoryChanged: function() { + onClearHistoryChanged() { let downloadsPref = document.getElementById("privacy.clearOnShutdown.downloads"); let historyPref = document.getElementById("privacy.clearOnShutdown.history"); downloadsPref.value = historyPref.value; diff --git a/browser/components/preferences/translation.js b/browser/components/preferences/translation.js index 0c7d86ff3165..82dd0e7bfedf 100644 --- a/browser/components/preferences/translation.js +++ b/browser/components/preferences/translation.js @@ -33,7 +33,7 @@ Tree.prototype = { get hasSelection() { return this.selection.count > 0; }, - getSelectedItems: function() { + getSelectedItems() { let result = []; let rc = this.selection.getRangeCount(); @@ -51,30 +51,30 @@ Tree.prototype = { get rowCount() { return this._data.length; }, - getCellText: function(aRow, aColumn) { + getCellText(aRow, aColumn) { return this._data[aRow]; }, - isSeparator: function(aIndex) { + isSeparator(aIndex) { return false; }, - isSorted: function() { + isSorted() { return false; }, - isContainer: function(aIndex) { + isContainer(aIndex) { return false; }, - setTree: function(aTree) {}, - getImageSrc: function(aRow, aColumn) {}, - getProgressMode: function(aRow, aColumn) {}, - getCellValue: function(aRow, aColumn) {}, - cycleHeader: function(column) {}, - getRowProperties: function(row) { + setTree(aTree) {}, + getImageSrc(aRow, aColumn) {}, + getProgressMode(aRow, aColumn) {}, + getCellValue(aRow, aColumn) {}, + cycleHeader(column) {}, + getRowProperties(row) { return ""; }, - getColumnProperties: function(column) { + getColumnProperties(column) { return ""; }, - getCellProperties: function(row, column) { + getCellProperties(row, column) { return ""; }, QueryInterface: XPCOMUtils.generateQI([Ci.nsITreeView]) @@ -87,13 +87,13 @@ function Lang(aCode) } Lang.prototype = { - toString: function() { + toString() { return this._label; } } var gTranslationExceptions = { - onLoad: function() { + onLoad() { if (this._siteTree) { // Re-using an open dialog, clear the old observers. this.uninit(); @@ -123,7 +123,7 @@ var gTranslationExceptions = { }, // Get the list of languages we don't translate as an array. - getLanguageExceptions: function() { + getLanguageExceptions() { let langs = Services.prefs.getCharPref(kLanguagesPref); if (!langs) return []; @@ -134,7 +134,7 @@ var gTranslationExceptions = { return result; }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { if (aData == "cleared") { if (!this._sites.length) @@ -180,22 +180,22 @@ var gTranslationExceptions = { } }, - _handleButtonDisabling: function(aTree, aIdPart) { + _handleButtonDisabling(aTree, aIdPart) { let empty = aTree.isEmpty; document.getElementById("removeAll" + aIdPart + "s").disabled = empty; document.getElementById("remove" + aIdPart).disabled = empty || !aTree.hasSelection; }, - onLanguageSelected: function() { + onLanguageSelected() { this._handleButtonDisabling(this._langTree, "Language"); }, - onSiteSelected: function() { + onSiteSelected() { this._handleButtonDisabling(this._siteTree, "Site"); }, - onLanguageDeleted: function() { + onLanguageDeleted() { let langs = Services.prefs.getCharPref(kLanguagesPref); if (!langs) return; @@ -206,11 +206,11 @@ var gTranslationExceptions = { Services.prefs.setCharPref(kLanguagesPref, langs.join(",")); }, - onAllLanguagesDeleted: function() { + onAllLanguagesDeleted() { Services.prefs.setCharPref(kLanguagesPref, ""); }, - onSiteDeleted: function() { + onSiteDeleted() { let removedSites = this._siteTree.getSelectedItems(); for (let origin of removedSites) { let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(origin); @@ -218,7 +218,7 @@ var gTranslationExceptions = { } }, - onAllSitesDeleted: function() { + onAllSitesDeleted() { if (this._siteTree.isEmpty) return; @@ -233,22 +233,22 @@ var gTranslationExceptions = { this.onSiteSelected(); }, - onSiteKeyPress: function(aEvent) { + onSiteKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) this.onSiteDeleted(); }, - onLanguageKeyPress: function(aEvent) { + onLanguageKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) this.onLanguageDeleted(); }, - onWindowKeyPress: function(aEvent) { + onWindowKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); }, - uninit: function() { + uninit() { Services.obs.removeObserver(this, "perm-changed"); Services.prefs.removeObserver(kLanguagesPref, this); } diff --git a/browser/components/search/test/browser_426329.js b/browser/components/search/test/browser_426329.js index d9cbd3f7a9b9..259705b4c26a 100644 --- a/browser/components/search/test/browser_426329.js +++ b/browser/components/search/test/browser_426329.js @@ -47,11 +47,11 @@ function getMenuEntries() { function countEntries(name, value) { return new Promise(resolve => { let count = 0; - let obj = name && value ? {fieldname: name, value: value} : {}; + let obj = name && value ? {fieldname: name, value} : {}; FormHistory.count(obj, - { handleResult: function(result) { count = result; }, - handleError: function(error) { throw error; }, - handleCompletion: function(reason) { + { handleResult(result) { count = result; }, + handleError(error) { throw error; }, + handleCompletion(reason) { if (!reason) { resolve(count); } diff --git a/browser/components/search/test/browser_aboutSearchReset.js b/browser/components/search/test/browser_aboutSearchReset.js index 75b591077695..6001c274af37 100644 --- a/browser/components/search/test/browser_aboutSearchReset.js +++ b/browser/components/search/test/browser_aboutSearchReset.js @@ -49,7 +49,7 @@ var gTests = [ { desc: "Test the 'Keep Current Settings' button.", - run: function* () { + *run() { let engine = yield promiseNewEngine(kTestEngine, {setAsCurrent: true}); let expectedURL = engine. @@ -75,7 +75,7 @@ var gTests = [ { desc: "Test the 'Restore Search Defaults' button.", - run: function* () { + *run() { let currentEngine = Services.search.currentEngine; let originalEngine = Services.search.originalDefaultEngine; let doc = gBrowser.contentDocument; @@ -103,7 +103,7 @@ var gTests = [ { desc: "Click the settings link.", - run: function* () { + *run() { let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, "about:preferences#search") @@ -116,7 +116,7 @@ var gTests = [ { desc: "Load another page without clicking any of the buttons.", - run: function* () { + *run() { yield promiseTabLoadEvent(gBrowser.selectedTab, "about:mozilla"); checkTelemetryRecords(TELEMETRY_RESULT_ENUM.CLOSED_PAGE); diff --git a/browser/components/search/test/browser_abouthome_behavior.js b/browser/components/search/test/browser_abouthome_behavior.js index e7d062e65e46..5a19ffc6c1eb 100644 --- a/browser/components/search/test/browser_abouthome_behavior.js +++ b/browser/components/search/test/browser_abouthome_behavior.js @@ -64,28 +64,28 @@ function test() { { name: "Search with Bing from about:home", searchURL: replaceUrl("http://www.bing.com/search?q=foo&pc=MOZI&form=MOZSPG"), - run: function() { + run() { verify_about_home_search("Bing"); } }, { name: "Search with Yahoo from about:home", searchURL: replaceUrl("https://search.yahoo.com/search?p=foo&ei=UTF-8&fr=moz35"), - run: function() { + run() { verify_about_home_search("Yahoo"); } }, { name: "Search with Google from about:home", searchURL: replaceUrl("https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8"), - run: function() { + run() { verify_about_home_search("Google"); } }, { name: "Search with Amazon.com from about:home", searchURL: replaceUrl("https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&mode=blended&tag=mozilla-20&sourceid=Mozilla-search"), - run: function() { + run() { verify_about_home_search("Amazon.com"); } } diff --git a/browser/components/search/test/browser_addEngine.js b/browser/components/search/test/browser_addEngine.js index 512b2dd558ab..798c4e9f7294 100644 --- a/browser/components/search/test/browser_addEngine.js +++ b/browser/components/search/test/browser_addEngine.js @@ -46,14 +46,14 @@ var gTests = [ description: "Foo Search", searchForm: "http://mochi.test:8888/browser/browser/components/search/test/" }, - run: function() { + run() { Services.obs.addObserver(observer, "browser-search-engine-modified", false); gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml", null, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC", false); }, - added: function(engine) { + added(engine) { ok(engine, "engine was added."); checkEngine(this.engine, engine); @@ -66,14 +66,14 @@ var gTests = [ gSS.currentEngine = engine; }, - current: function(engine) { + current(engine) { let currentEngine = gSS.currentEngine; is(engine, currentEngine, "engine is current"); is(engine.name, this.engine.name, "current engine was changed successfully"); gSS.removeEngine(engine); }, - removed: function(engine) { + removed(engine) { // Remove the observer before calling the currentEngine getter, // as that getter will set the currentEngine to the original default // which will trigger a notification causing the test to loop over all diff --git a/browser/components/search/test/browser_amazon_behavior.js b/browser/components/search/test/browser_amazon_behavior.js index 55695e11e862..d695939c6375 100644 --- a/browser/components/search/test/browser_amazon_behavior.js +++ b/browser/components/search/test/browser_amazon_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base, - run: function() { + run() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base, - run: function() { + run() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search", searchURL: base, - run: function() { + run() { gURLBar.value = "a foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base, - run: function() { + run() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base, - run: function() { + run() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_bing_behavior.js b/browser/components/search/test/browser_bing_behavior.js index 5087bd182004..7011fe41dc59 100644 --- a/browser/components/search/test/browser_bing_behavior.js +++ b/browser/components/search/test/browser_bing_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base + "&form=MOZCON", - run: function() { + run() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base + "&form=MOZLBR", - run: function() { + run() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search with alias", searchURL: base + "&form=MOZLBR", - run: function() { + run() { gURLBar.value = "b foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base + "&form=MOZSBR", - run: function() { + run() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base + "&form=MOZTSB", - run: function() { + run() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_google_behavior.js b/browser/components/search/test/browser_google_behavior.js index 1f31b35d9d93..f75c86a830de 100644 --- a/browser/components/search/test/browser_google_behavior.js +++ b/browser/components/search/test/browser_google_behavior.js @@ -30,7 +30,7 @@ function test() { { name: "context menu search", searchURL: base, - run: function() { + run() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -39,7 +39,7 @@ function test() { { name: "keyword search", searchURL: base, - run: function() { + run() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -48,7 +48,7 @@ function test() { { name: "keyword search", searchURL: base, - run: function() { + run() { gURLBar.value = "g foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -57,7 +57,7 @@ function test() { { name: "search bar search", searchURL: base, - run: function() { + run() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -70,7 +70,7 @@ function test() { { name: "new tab search", searchURL: base, - run: function() { + run() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js b/browser/components/search/test/browser_hiddenOneOffs_cleanup.js index 7bbcd523dbb3..34c7eca17656 100644 --- a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js +++ b/browser/components/search/test/browser_hiddenOneOffs_cleanup.js @@ -7,14 +7,14 @@ function promiseNewEngine(basename) { return new Promise((resolve, reject) => { info("Waiting for engine to be added: " + basename); Services.search.init({ - onInitComplete: function() { + onInitComplete() { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); } diff --git a/browser/components/search/test/browser_searchbar_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_keyboard_navigation.js index 26b8939c7d07..7e0602cf034f 100644 --- a/browser/components/search/test/browser_searchbar_keyboard_navigation.js +++ b/browser/components/search/test/browser_searchbar_keyboard_navigation.js @@ -37,16 +37,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(addOps, { - handleCompletion: function() { + handleCompletion() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_searchbar_openpopup.js b/browser/components/search/test/browser_searchbar_openpopup.js index df2a45e539c4..939ac9941894 100644 --- a/browser/components/search/test/browser_searchbar_openpopup.js +++ b/browser/components/search/test/browser_searchbar_openpopup.js @@ -58,16 +58,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(addOps, { - handleCompletion: function() { + handleCompletion() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js index e5e613971617..9ad747f76812 100644 --- a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js +++ b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js @@ -38,16 +38,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(addOps, { - handleCompletion: function() { + handleCompletion() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_webapi.js b/browser/components/search/test/browser_webapi.js index d8161ffbe528..4016484c31f9 100644 --- a/browser/components/search/test/browser_webapi.js +++ b/browser/components/search/test/browser_webapi.js @@ -14,7 +14,7 @@ function AddSearchProvider(...args) { function promiseDialogOpened() { return new Promise((resolve, reject) => { Services.wm.addListener({ - onOpenWindow: function(xulWin) { + onOpenWindow(xulWin) { Services.wm.removeListener(this); let win = xulWin.QueryInterface(Ci.nsIInterfaceRequestor) diff --git a/browser/components/search/test/browser_yahoo_behavior.js b/browser/components/search/test/browser_yahoo_behavior.js index 5f182971f7f3..ec4d85d3adc4 100644 --- a/browser/components/search/test/browser_yahoo_behavior.js +++ b/browser/components/search/test/browser_yahoo_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base + "&hsimp=yhs-005", - run: function() { + run() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base + "&hsimp=yhs-002", - run: function() { + run() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search with alias", searchURL: base + "&hsimp=yhs-002", - run: function() { + run() { gURLBar.value = "y foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base + "&hsimp=yhs-001", - run: function() { + run() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base + "&hsimp=yhs-004", - run: function() { + run() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/head.js b/browser/components/search/test/head.js index 5fb4fe02cf02..318dd54c7897 100644 --- a/browser/components/search/test/head.js +++ b/browser/components/search/test/head.js @@ -58,11 +58,11 @@ function promiseNewEngine(basename, options = {}) { options.setAsCurrent == undefined ? true : options.setAsCurrent; info("Waiting for engine to be added: " + basename); Services.search.init({ - onInitComplete: function() { + onInitComplete() { let url = getRootDirectory(gTestPath) + basename; let current = Services.search.currentEngine; Services.search.addEngine(url, null, options.iconURL || "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); if (setAsCurrent) { Services.search.currentEngine = engine; @@ -76,7 +76,7 @@ function promiseNewEngine(basename, options = {}) { }); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); } diff --git a/browser/components/selfsupport/SelfSupportService.js b/browser/components/selfsupport/SelfSupportService.js index bdde07a2f43f..38904cdfd395 100644 --- a/browser/components/selfsupport/SelfSupportService.js +++ b/browser/components/selfsupport/SelfSupportService.js @@ -30,7 +30,7 @@ MozSelfSupportInterface.prototype = { _window: null, - init: function(window) { + init(window) { this._window = window; }, @@ -42,34 +42,34 @@ MozSelfSupportInterface.prototype = { Preferences.set(PREF_FHR_UPLOAD_ENABLED, enabled); }, - resetPref: function(name) { + resetPref(name) { Services.prefs.clearUserPref(name); }, - resetSearchEngines: function() { + resetSearchEngines() { Services.search.restoreDefaultEngines(); Services.search.resetToOriginalDefaultEngine(); }, - getTelemetryPingList: function() { + getTelemetryPingList() { return this._wrapPromise(TelemetryArchive.promiseArchivedPingList()); }, - getTelemetryPing: function(pingId) { + getTelemetryPing(pingId) { return this._wrapPromise(TelemetryArchive.promiseArchivedPingById(pingId)); }, - getCurrentTelemetryEnvironment: function() { + getCurrentTelemetryEnvironment() { const current = TelemetryEnvironment.currentEnvironment; return new this._window.Promise(resolve => resolve(current)); }, - getCurrentTelemetrySubsessionPing: function() { + getCurrentTelemetrySubsessionPing() { const current = TelemetryController.getCurrentPingData(true); return new this._window.Promise(resolve => resolve(current)); }, - _wrapPromise: function(promise) { + _wrapPromise(promise) { return new this._window.Promise( (resolve, reject) => promise.then(resolve, reject)); }, diff --git a/browser/components/shell/content/setDesktopBackground.js b/browser/components/shell/content/setDesktopBackground.js index 094c34aa56da..e23cd912e68b 100644 --- a/browser/components/shell/content/setDesktopBackground.js +++ b/browser/components/shell/content/setDesktopBackground.js @@ -20,7 +20,7 @@ var gSetBackground = { .getService(Ci.nsIShellService); }, - load: function() + load() { this._canvas = document.getElementById("screen"); this._screenWidth = screen.width; @@ -49,7 +49,7 @@ var gSetBackground = { }, 0, this); }, - init: function(aImage) + init(aImage) { this._image = aImage; @@ -76,7 +76,7 @@ var gSetBackground = { this.updatePosition(); }, - setDesktopBackground: function() + setDesktopBackground() { if (AppConstants.platform != "macosx") { document.persist("menuPosition", "value"); @@ -95,7 +95,7 @@ var gSetBackground = { Ci.nsIShellService["BACKGROUND_" + this._position]); }, - updatePosition: function() + updatePosition() { var ctx = this._canvas.getContext("2d"); ctx.clearRect(0, 0, this._screenWidth, this._screenHeight); diff --git a/browser/components/syncedtabs/SyncedTabsDeckComponent.js b/browser/components/syncedtabs/SyncedTabsDeckComponent.js index dfbec056ca0b..bdad78e43e32 100644 --- a/browser/components/syncedtabs/SyncedTabsDeckComponent.js +++ b/browser/components/syncedtabs/SyncedTabsDeckComponent.js @@ -49,7 +49,7 @@ function SyncedTabsDeckComponent({ window: this._window, store: this._syncedTabsListStore, View: TabListView, - SyncedTabs: SyncedTabs, + SyncedTabs, clipboardHelper: Cc["@mozilla.org/widget/clipboardhelper;1"] .getService(Ci.nsIClipboardHelper), getChromeWindow: this._getChromeWindow, diff --git a/browser/components/syncedtabs/SyncedTabsDeckStore.js b/browser/components/syncedtabs/SyncedTabsDeckStore.js index ede6914c8302..eef594a51956 100644 --- a/browser/components/syncedtabs/SyncedTabsDeckStore.js +++ b/browser/components/syncedtabs/SyncedTabsDeckStore.js @@ -31,7 +31,7 @@ Object.assign(SyncedTabsDeckStore.prototype, EventEmitter.prototype, { let panels = this._panels.map(panel => { return {id: panel, selected: panel === this._selectedPanel}; }); - this.emit("change", {panels, isUpdatable: isUpdatable}); + this.emit("change", {panels, isUpdatable}); }, /** diff --git a/browser/components/syncedtabs/test/xpcshell/head.js b/browser/components/syncedtabs/test/xpcshell/head.js index af0458ea6e8b..17590109b6b4 100644 --- a/browser/components/syncedtabs/test/xpcshell/head.js +++ b/browser/components/syncedtabs/test/xpcshell/head.js @@ -15,9 +15,9 @@ do_get_profile(); // fxa needs a profile directory for storage. let window = { document: {}, location: {}, - setTimeout: setTimeout, - setInterval: setInterval, - clearTimeout: clearTimeout, + setTimeout, + setInterval, + clearTimeout, clearinterval: clearInterval }; let self = window; diff --git a/browser/components/tests/browser/browser_bug538331.js b/browser/components/tests/browser/browser_bug538331.js index fc1003413b50..1665163633fc 100644 --- a/browser/components/tests/browser/browser_bug538331.js +++ b/browser/components/tests/browser/browser_bug538331.js @@ -135,11 +135,11 @@ function test() var gWindowCatcher = { windowsOpen: 0, finishCalled: false, - start: function() { + start() { Services.ww.registerNotification(this); }, - finish: function(aFunc) { + finish(aFunc) { Services.ww.unregisterNotification(this); this.finishFunc = aFunc; if (this.windowsOpen > 0) @@ -148,7 +148,7 @@ var gWindowCatcher = { this.finishFunc(); }, - closeWindow: function(win) { + closeWindow(win) { info("window catcher closing window: " + win.document.documentURI); win.close(); this.windowsOpen--; @@ -157,11 +157,11 @@ var gWindowCatcher = { } }, - windowLoad: function(win) { + windowLoad(win) { executeSoon(this.closeWindow.bind(this, win)); }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic != "domwindowopened") return; diff --git a/browser/components/tests/unit/test_distribution.js b/browser/components/tests/unit/test_distribution.js index 86f4c40665cd..83255a083356 100644 --- a/browser/components/tests/unit/test_distribution.js +++ b/browser/components/tests/unit/test_distribution.js @@ -46,7 +46,7 @@ function installDistributionEngine() { do_get_file("data/engine-de-DE.xml").copyTo(localeDir, "engine-de-DE.xml"); Services.dirsvc.registerProvider({ - getFile: function(aProp, aPersistent) { + getFile(aProp, aPersistent) { aPersistent.value = true; if (aProp == XRE_APP_DISTRIBUTION_DIR) return distDir.clone(); diff --git a/browser/components/translation/BingTranslator.jsm b/browser/components/translation/BingTranslator.jsm index fc1cc942a14a..cdaec46ff9ef 100644 --- a/browser/components/translation/BingTranslator.jsm +++ b/browser/components/translation/BingTranslator.jsm @@ -58,7 +58,7 @@ this.BingTranslator.prototype = { * @returns {Promise} A promise that will resolve when the translation * task is finished. */ - translate: function() { + translate() { return Task.spawn(function *() { let currentIndex = 0; this._onFinishedDeferred = Promise.defer(); @@ -98,7 +98,7 @@ this.BingTranslator.prototype = { * Resets the expiration time of the current token, in order to * force the token manager to ask for a new token during the next request. */ - _resetToken : function() { + _resetToken() { // Force the token manager to get update token BingTokenManager._currentExpiryTime = 0; }, @@ -111,7 +111,7 @@ this.BingTranslator.prototype = { * * @param request The BingRequest sent to the server. */ - _chunkCompleted: function(bingRequest) { + _chunkCompleted(bingRequest) { if (this._parseChunkResult(bingRequest)) { this._partialSuccess = true; // Count the number of characters successfully translated. @@ -131,7 +131,7 @@ this.BingTranslator.prototype = { * * @param aError [optional] The XHR object of the request that failed. */ - _chunkFailed: function(aError) { + _chunkFailed(aError) { if (aError instanceof Ci.nsIXMLHttpRequest && [400, 401].indexOf(aError.status) != -1) { let body = aError.responseText; @@ -148,7 +148,7 @@ this.BingTranslator.prototype = { * This function handles resolving the promise * returned by the public `translate()` method when all chunks are completed. */ - _checkIfFinished: function() { + _checkIfFinished() { // Check if all pending requests have been // completed and then resolves the promise. // If at least one chunk was successful, the @@ -177,7 +177,7 @@ this.BingTranslator.prototype = { * @param request The request sent to the server. * @returns boolean True if parsing of this chunk was successful. */ - _parseChunkResult: function(bingRequest) { + _parseChunkResult(bingRequest) { let results; try { let doc = bingRequest.networkRequest.responseXML; @@ -220,7 +220,7 @@ this.BingTranslator.prototype = { * @param startIndex What is the index, in the roots list, that the * chunk should start. */ - _generateNextTranslationRequest: function(startIndex) { + _generateNextTranslationRequest(startIndex) { let currentDataSize = 0; let currentChunks = 0; let output = []; @@ -285,7 +285,7 @@ BingRequest.prototype = { /** * Initiates the request */ - fireRequest: function() { + fireRequest() { return Task.spawn(function *() { // Prepare authentication. let token = yield BingTokenManager.getToken(); @@ -324,11 +324,11 @@ BingRequest.prototype = { onLoad: (function(responseText, xhr) { deferred.resolve(this); }).bind(this), - onError: function(e, responseText, xhr) { + onError(e, responseText, xhr) { deferred.reject(xhr); }, postData: requestString, - headers: headers + headers }; // Fire the request. @@ -358,7 +358,7 @@ var BingTokenManager = { * can be the same one used in the past if it is still * valid. */ - getToken: function() { + getToken() { if (this._pendingRequest) { return this._pendingRequest; } @@ -378,7 +378,7 @@ var BingTokenManager = { * @returns {Promise} A promise that resolves with the token * string once it is obtained. */ - _getNewToken: function() { + _getNewToken() { let url = getUrlParam("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13", "browser.translation.bing.authURL"); let params = [ @@ -392,7 +392,7 @@ var BingTokenManager = { let deferred = Promise.defer(); let options = { - onLoad: function(responseText, xhr) { + onLoad(responseText, xhr) { BingTokenManager._pendingRequest = null; try { let json = JSON.parse(responseText); @@ -411,7 +411,7 @@ var BingTokenManager = { deferred.reject(e); } }, - onError: function(e, responseText, xhr) { + onError(e, responseText, xhr) { BingTokenManager._pendingRequest = null; deferred.reject(e); }, diff --git a/browser/components/translation/LanguageDetector.jsm b/browser/components/translation/LanguageDetector.jsm index a65d6eda124a..e75f777a1f26 100644 --- a/browser/components/translation/LanguageDetector.jsm +++ b/browser/components/translation/LanguageDetector.jsm @@ -134,7 +134,7 @@ this.LanguageDetector = { * entry with the languge code 'un', indicating the percent of * the text which is unknown. */ - detectLanguage: function(aParams) { + detectLanguage(aParams) { if (typeof aParams == "string") aParams = { text: aParams }; diff --git a/browser/components/translation/Translation.jsm b/browser/components/translation/Translation.jsm index c2591b65ed67..9dc29930f58c 100644 --- a/browser/components/translation/Translation.jsm +++ b/browser/components/translation/Translation.jsm @@ -41,7 +41,7 @@ this.Translation = { return this._defaultTargetLanguage; }, - documentStateReceived: function(aBrowser, aData) { + documentStateReceived(aBrowser, aData) { if (aData.state == this.STATE_OFFER) { if (aData.detectedLanguage == this.defaultTargetLanguage) { // Detected language is the same as the user's locale. @@ -78,7 +78,7 @@ this.Translation = { trUI.showTranslationInfoBar(); }, - openProviderAttribution: function() { + openProviderAttribution() { let attribution = this.supportedEngines[this.translationEngine]; Cu.import("resource:///modules/RecentWindow.jsm"); RecentWindow.getMostRecentBrowserWindow().openUILinkIn(attribution, "tab"); @@ -138,7 +138,7 @@ TranslationUI.prototype = { aBrowser.messageManager.addMessageListener("Translation:Finished", this); this._browser = aBrowser; }, - translate: function(aFrom, aTo) { + translate(aFrom, aTo) { if (aFrom == aTo || (this.state == Translation.STATE_TRANSLATED && this.translatedFrom == aFrom && this.translatedTo == aTo)) { @@ -166,7 +166,7 @@ TranslationUI.prototype = { ); }, - showURLBarIcon: function() { + showURLBarIcon() { let chromeWin = this.browser.ownerGlobal; let PopupNotifications = chromeWin.PopupNotifications; let removeId = this.originalShown ? "translated" : "translate"; @@ -214,14 +214,14 @@ TranslationUI.prototype = { }, originalShown: true, - showOriginalContent: function() { + showOriginalContent() { this.originalShown = true; this.showURLBarIcon(); this.browser.messageManager.sendAsyncMessage("Translation:ShowOriginal"); TranslationTelemetry.recordShowOriginalContent(); }, - showTranslatedContent: function() { + showTranslatedContent() { this.originalShown = false; this.showURLBarIcon(); this.browser.messageManager.sendAsyncMessage("Translation:ShowTranslation"); @@ -231,7 +231,7 @@ TranslationUI.prototype = { return this.browser.ownerGlobal.gBrowser.getNotificationBox(this.browser); }, - showTranslationInfoBar: function() { + showTranslationInfoBar() { let notificationBox = this.notificationBox; let notif = notificationBox.appendNotification("", "translation", null, notificationBox.PRIORITY_INFO_HIGH); @@ -239,7 +239,7 @@ TranslationUI.prototype = { return notif; }, - shouldShowInfoBar: function(aURI) { + shouldShowInfoBar(aURI) { // Never show the infobar automatically while the translation // service is temporarily unavailable. if (Translation.serviceUnavailable) @@ -263,7 +263,7 @@ TranslationUI.prototype = { return true; }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Translation:Finished": if (msg.data.success) { @@ -284,7 +284,7 @@ TranslationUI.prototype = { } }, - infobarClosed: function() { + infobarClosed() { if (this.state == Translation.STATE_OFFER) TranslationTelemetry.recordDeniedTranslationOffer(); } @@ -298,7 +298,7 @@ TranslationUI.prototype = { */ this.TranslationTelemetry = { - init: function() { + init() { // Constructing histograms. const plain = (id) => Services.telemetry.getHistogramById(id); const keyed = (id) => Services.telemetry.getKeyedHistogramById(id); @@ -326,7 +326,7 @@ this.TranslationTelemetry = { * @param language * The language of the page. */ - recordTranslationOpportunity: function(language) { + recordTranslationOpportunity(language) { return this._recordOpportunity(language, true); }, @@ -337,7 +337,7 @@ this.TranslationTelemetry = { * @param language * The language of the page. */ - recordMissedTranslationOpportunity: function(language) { + recordMissedTranslationOpportunity(language) { return this._recordOpportunity(language, false); }, @@ -351,7 +351,7 @@ this.TranslationTelemetry = { * These translation opportunities should still be recorded in addition to * recording the automatic rejection of the offer. */ - recordAutoRejectedTranslationOffer: function() { + recordAutoRejectedTranslationOffer() { if (!this._canRecord) return; this.HISTOGRAMS.AUTO_REJECTED().add(); }, @@ -365,7 +365,7 @@ this.TranslationTelemetry = { * @param numCharacters * The number of characters that were translated */ - recordTranslation: function(langFrom, langTo, numCharacters) { + recordTranslation(langFrom, langTo, numCharacters) { if (!this._canRecord) return; this.HISTOGRAMS.PAGES().add(); this.HISTOGRAMS.PAGES_BY_LANG().add(langFrom + " -> " + langTo); @@ -384,7 +384,7 @@ this.TranslationTelemetry = { * the user has manually adjusted the detected language false should * be passed. */ - recordDetectedLanguageChange: function(beforeFirstTranslation) { + recordDetectedLanguageChange(beforeFirstTranslation) { if (!this._canRecord) return; this.HISTOGRAMS.DETECTION_CHANGES().add(beforeFirstTranslation); }, @@ -394,7 +394,7 @@ this.TranslationTelemetry = { * only be called when actually executing a translation, not every time the * user changes in the language in the UI. */ - recordTargetLanguageChange: function() { + recordTargetLanguageChange() { if (!this._canRecord) return; this.HISTOGRAMS.TARGET_CHANGES().add(); }, @@ -402,7 +402,7 @@ this.TranslationTelemetry = { /** * Record a denied translation offer. */ - recordDeniedTranslationOffer: function() { + recordDeniedTranslationOffer() { if (!this._canRecord) return; this.HISTOGRAMS.DENIED().add(); }, @@ -410,7 +410,7 @@ this.TranslationTelemetry = { /** * Record a "Show Original" command use. */ - recordShowOriginalContent: function() { + recordShowOriginalContent() { if (!this._canRecord) return; this.HISTOGRAMS.SHOW_ORIGINAL().add(); }, @@ -418,7 +418,7 @@ this.TranslationTelemetry = { /** * Record the state of translation preferences. */ - recordPreferences: function() { + recordPreferences() { if (!this._canRecord) return; if (Services.prefs.getBoolPref(TRANSLATION_PREF_SHOWUI)) { this.HISTOGRAMS.SHOW_UI().add(1); @@ -428,7 +428,7 @@ this.TranslationTelemetry = { } }, - _recordOpportunity: function(language, success) { + _recordOpportunity(language, success) { if (!this._canRecord) return; this.HISTOGRAMS.OPPORTUNITIES().add(success); this.HISTOGRAMS.OPPORTUNITIES_BY_LANG().add(language, success); @@ -438,7 +438,7 @@ this.TranslationTelemetry = { * A shortcut for reading the telemetry preference. * */ - _canRecord: function() { + _canRecord() { return Services.prefs.getBoolPref("toolkit.telemetry.enabled"); } }; diff --git a/browser/components/translation/TranslationContentHandler.jsm b/browser/components/translation/TranslationContentHandler.jsm index 3b0d59dddd40..62376d4aa5ed 100644 --- a/browser/components/translation/TranslationContentHandler.jsm +++ b/browser/components/translation/TranslationContentHandler.jsm @@ -31,7 +31,7 @@ this.TranslationContentHandler = function(global, docShell) { } TranslationContentHandler.prototype = { - handleEvent: function(aEvent) { + handleEvent(aEvent) { // We are only listening to pageshow events. let target = aEvent.target; @@ -61,7 +61,7 @@ TranslationContentHandler.prototype = { }, /* nsIWebProgressListener implementation */ - onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { if (!aWebProgress.isTopLevel || !(aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) || !this.global.content) @@ -108,15 +108,15 @@ TranslationContentHandler.prototype = { }, // Unused methods. - onProgressChange: function() {}, - onLocationChange: function() {}, - onStatusChange: function() {}, - onSecurityChange: function() {}, + onProgressChange() {}, + onLocationChange() {}, + onStatusChange() {}, + onSecurityChange() {}, QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference]), - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Translation:TranslateDocument": { diff --git a/browser/components/translation/TranslationDocument.jsm b/browser/components/translation/TranslationDocument.jsm index 058d07a498cf..c754251046bd 100644 --- a/browser/components/translation/TranslationDocument.jsm +++ b/browser/components/translation/TranslationDocument.jsm @@ -42,7 +42,7 @@ this.TranslationDocument.prototype = { * * @param document The document to be translated */ - _init: function(document) { + _init(document) { let window = document.defaultView; let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -94,7 +94,7 @@ this.TranslationDocument.prototype = { * * @returns A TranslationItem object. */ - _createItemForNode: function(node, id, isRoot) { + _createItemForNode(node, id, isRoot) { if (this.itemsMap.has(node)) { return this.itemsMap.get(node); } @@ -129,7 +129,7 @@ this.TranslationDocument.prototype = { * * @returns A string representation of the TranslationItem. */ - generateTextForItem: function(item) { + generateTextForItem(item) { if (item.original) { return regenerateTextFromOriginalHelper(item); } @@ -187,7 +187,7 @@ this.TranslationDocument.prototype = { * Changes the document to display its translated * content. */ - showTranslation: function() { + showTranslation() { this.originalShown = false; this._swapDocumentContent("translation"); }, @@ -196,7 +196,7 @@ this.TranslationDocument.prototype = { * Changes the document to display its original * content. */ - showOriginal: function() { + showOriginal() { this.originalShown = true; this._swapDocumentContent("original"); }, @@ -208,7 +208,7 @@ this.TranslationDocument.prototype = { * @param target A string that is either "translation" * or "original". */ - _swapDocumentContent: function(target) { + _swapDocumentContent(target) { Task.spawn(function *() { // Let the event loop breath on every 100 nodes // that are replaced. @@ -274,7 +274,7 @@ TranslationItem.prototype = { isRoot: false, isSimpleRoot: false, - toString: function() { + toString() { let rootType = ""; if (this.isRoot) { if (this.isSimpleRoot) { @@ -305,7 +305,7 @@ TranslationItem.prototype = { * @param result A string with the textual result received from the server, * which can be plain-text or a serialized HTML doc. */ - parseResult: function(result) { + parseResult(result) { if (this.isSimpleRoot) { this.translation = [result]; return; @@ -325,7 +325,7 @@ TranslationItem.prototype = { * @returns A TranslationItem with the given id, or null if * it was not found. */ - getChildById: function(id) { + getChildById(id) { for (let child of this.children) { if (("n" + child.id) == id) { return child; @@ -341,7 +341,7 @@ TranslationItem.prototype = { * @param target A string that is either "translation" * or "original". */ - swapText: function(target) { + swapText(target) { swapTextForItem(this, target); } }; @@ -354,7 +354,7 @@ TranslationItem.prototype = { * for correct positioning and spliting of text nodes. */ const TranslationItem_NodePlaceholder = { - toString: function() { + toString() { return "[object TranslationItem_NodePlaceholder]"; } }; diff --git a/browser/components/translation/YandexTranslator.jsm b/browser/components/translation/YandexTranslator.jsm index ab92e09625c9..11206d91d48a 100644 --- a/browser/components/translation/YandexTranslator.jsm +++ b/browser/components/translation/YandexTranslator.jsm @@ -76,7 +76,7 @@ this.YandexTranslator.prototype = { * @returns {Promise} A promise that will resolve when the translation * task is finished. */ - translate: function() { + translate() { return Task.spawn(function *() { let currentIndex = 0; this._onFinishedDeferred = Promise.defer(); @@ -120,7 +120,7 @@ this.YandexTranslator.prototype = { * * @param request The YandexRequest sent to the server */ - _chunkCompleted: function(yandexRequest) { + _chunkCompleted(yandexRequest) { if (this._parseChunkResult(yandexRequest)) { this._partialSuccess = true; // Count the number of characters successfully translated. @@ -140,7 +140,7 @@ this.YandexTranslator.prototype = { * * @param aError [optional] The XHR object of the request that failed. */ - _chunkFailed: function(aError) { + _chunkFailed(aError) { if (aError instanceof Ci.nsIXMLHttpRequest) { let body = aError.responseText; let json = { code: 0 }; @@ -160,7 +160,7 @@ this.YandexTranslator.prototype = { * This function handles resolving the promise * returned by the public `translate()` method when all chunks are completed. */ - _checkIfFinished: function() { + _checkIfFinished() { // Check if all pending requests have been // completed and then resolves the promise. // If at least one chunk was successful, the @@ -188,7 +188,7 @@ this.YandexTranslator.prototype = { * @param request The request sent to the server. * @returns boolean True if parsing of this chunk was successful. */ - _parseChunkResult: function(yandexRequest) { + _parseChunkResult(yandexRequest) { let results; try { let result = JSON.parse(yandexRequest.networkRequest.responseText); @@ -228,7 +228,7 @@ this.YandexTranslator.prototype = { * @param startIndex What is the index, in the roots list, that the * chunk should start. */ - _generateNextTranslationRequest: function(startIndex) { + _generateNextTranslationRequest(startIndex) { let currentDataSize = 0; let currentChunks = 0; let output = []; @@ -292,7 +292,7 @@ YandexRequest.prototype = { /** * Initiates the request */ - fireRequest: function() { + fireRequest() { return Task.spawn(function *() { // Prepare URL. let url = getUrlParam("https://translate.yandex.net/api/v1.5/tr.json/translate", @@ -317,7 +317,7 @@ YandexRequest.prototype = { onLoad: (function(responseText, xhr) { deferred.resolve(this); }).bind(this), - onError: function(e, responseText, xhr) { + onError(e, responseText, xhr) { deferred.reject(xhr); }, postData: params diff --git a/browser/components/translation/test/browser_translation_infobar.js b/browser/components/translation/test/browser_translation_infobar.js index 4dbdcbee4c3c..9b6917b3fe31 100644 --- a/browser/components/translation/test/browser_translation_infobar.js +++ b/browser/components/translation/test/browser_translation_infobar.js @@ -33,23 +33,23 @@ function waitForCondition(condition, nextTest, errorMsg) { } var TranslationStub = { - translate: function(aFrom, aTo) { + translate(aFrom, aTo) { this.state = Translation.STATE_TRANSLATING; this.translatedFrom = aFrom; this.translatedTo = aTo; }, - _reset: function() { + _reset() { this.translatedFrom = ""; this.translatedTo = ""; }, - failTranslation: function() { + failTranslation() { this.state = Translation.STATE_ERROR; this._reset(); }, - finishTranslation: function() { + finishTranslation() { this.showTranslatedContent(); this.state = Translation.STATE_TRANSLATED; this._reset(); diff --git a/browser/components/translation/test/browser_translation_telemetry.js b/browser/components/translation/test/browser_translation_telemetry.js index 2c89c283f0b7..4e3e08925e9c 100644 --- a/browser/components/translation/test/browser_translation_telemetry.js +++ b/browser/components/translation/test/browser_translation_telemetry.js @@ -24,14 +24,14 @@ var MetricsChecker = { DETECT_LANG : Services.telemetry.getHistogramById("SHOULD_AUTO_DETECT_LANGUAGE"), }, - reset: function() { + reset() { for (let i of Object.keys(this.HISTOGRAMS)) { this.HISTOGRAMS[i].clear(); } this.updateMetrics(); }, - updateMetrics: function() { + updateMetrics() { this._metrics = { opportunitiesCount: this.HISTOGRAMS.OPPORTUNITIES.snapshot().sum || 0, pageCount: this.HISTOGRAMS.PAGES.snapshot().sum || 0, @@ -65,7 +65,7 @@ var MetricsChecker = { /** * A recurrent loop for making assertions about collected metrics. */ - _assertionLoop: function(prevMetrics, metrics, additions) { + _assertionLoop(prevMetrics, metrics, additions) { for (let metric of Object.keys(additions)) { let addition = additions[metric]; // Allows nesting metrics. Useful for keyed histograms. @@ -77,7 +77,7 @@ var MetricsChecker = { } }, - checkAdditions: function(additions) { + checkAdditions(additions) { let prevMetrics = this._metrics; this.updateMetrics(); this._assertionLoop(prevMetrics, this._metrics, additions); diff --git a/browser/components/uitour/UITour-lib.js b/browser/components/uitour/UITour-lib.js index 40c1a82b4d99..9b7775864988 100644 --- a/browser/components/uitour/UITour-lib.js +++ b/browser/components/uitour/UITour-lib.js @@ -27,7 +27,7 @@ if (typeof Mozilla == 'undefined') { var event = new CustomEvent('mozUITour', { bubbles: true, detail: { - action: action, + action, data: data || {} } }); @@ -94,19 +94,19 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.registerPageID = function(pageID) { _sendEvent('registerPageID', { - pageID: pageID + pageID }); }; Mozilla.UITour.showHeartbeat = function(message, thankyouMessage, flowId, engagementURL, learnMoreLabel, learnMoreURL, options) { var args = { - message: message, - thankyouMessage: thankyouMessage, - flowId: flowId, - engagementURL: engagementURL, - learnMoreLabel: learnMoreLabel, - learnMoreURL: learnMoreURL, + message, + thankyouMessage, + flowId, + engagementURL, + learnMoreLabel, + learnMoreURL, }; if (options) { @@ -123,8 +123,8 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.showHighlight = function(target, effect) { _sendEvent('showHighlight', { - target: target, - effect: effect + target, + effect }); }; @@ -152,13 +152,13 @@ if (typeof Mozilla == 'undefined') { targetCallbackID = _waitForCallback(options.targetCallback); _sendEvent('showInfo', { - target: target, - title: title, - text: text, - icon: icon, + target, + title, + text, + icon, buttons: buttonData, - closeButtonCallbackID: closeButtonCallbackID, - targetCallbackID: targetCallbackID + closeButtonCallbackID, + targetCallbackID }); }; @@ -209,14 +209,14 @@ if (typeof Mozilla == 'undefined') { showCallbackID = _waitForCallback(callback); _sendEvent('showMenu', { - name: name, - showCallbackID: showCallbackID, + name, + showCallbackID, }); }; Mozilla.UITour.hideMenu = function(name) { _sendEvent('hideMenu', { - name: name + name }); }; @@ -260,34 +260,34 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.addNavBarWidget = function(name, callback) { _sendEvent('addNavBarWidget', { - name: name, + name, callbackID: _waitForCallback(callback), }); }; Mozilla.UITour.setDefaultSearchEngine = function(identifier) { _sendEvent('setDefaultSearchEngine', { - identifier: identifier, + identifier, }); }; Mozilla.UITour.setTreatmentTag = function(name, value) { _sendEvent('setTreatmentTag', { - name: name, - value: value + name, + value }); }; Mozilla.UITour.getTreatmentTag = function(name, callback) { _sendEvent('getTreatmentTag', { - name: name, + name, callbackID: _waitForCallback(callback) }); }; Mozilla.UITour.setSearchTerm = function(term) { _sendEvent('setSearchTerm', { - term: term + term }); }; @@ -307,7 +307,7 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.openPreferences = function(pane) { _sendEvent('openPreferences', { - pane: pane + pane }); }; diff --git a/browser/components/uitour/UITour.jsm b/browser/components/uitour/UITour.jsm index 2e25fdd458f4..eeb73ade9eab 100644 --- a/browser/components/uitour/UITour.jsm +++ b/browser/components/uitour/UITour.jsm @@ -214,7 +214,7 @@ this.UITour = { ["webide", {query: "#webide-button"}], ]), - init: function() { + init() { log.debug("Initializing UITour"); // Lazy getter is initialized here so it can be replicated any time // in a test. @@ -243,7 +243,7 @@ this.UITour = { }, {})); }, - restoreSeenPageIDs: function() { + restoreSeenPageIDs() { delete this.seenPageIDs; if (UITelemetry.enabled) { @@ -276,7 +276,7 @@ this.UITour = { return this.seenPageIDs; }, - addSeenPageID: function(aPageID) { + addSeenPageID(aPageID) { if (!UITelemetry.enabled) return; @@ -287,7 +287,7 @@ this.UITour = { this.persistSeenIDs(); }, - persistSeenIDs: function() { + persistSeenIDs() { if (this.seenPageIDs.size === 0) { Services.prefs.clearUserPref(PREF_SEENPAGEIDS); return; @@ -303,7 +303,7 @@ this.UITour = { return this._readerViewTriggerRegEx = new RegExp(readerViewUITourTrigger, "i"); }, - onLocationChange: function(aLocation) { + onLocationChange(aLocation) { // The ReaderView tour page is expected to run in Reader View, // which disables JavaScript on the page. To get around that, we // automatically start a pre-defined tour on page load (for hysterical @@ -314,7 +314,7 @@ this.UITour = { } }, - onPageEvent: function(aMessage, aEvent) { + onPageEvent(aMessage, aEvent) { let browser = aMessage.target; let window = browser.ownerGlobal; @@ -620,7 +620,7 @@ this.UITour = { value = Services.prefs.getComplexValue("browser.uitour.treatment." + name, Ci.nsISupportsString).data; } catch (ex) {} - this.sendPageCallback(messageManager, data.callbackID, { value: value }); + this.sendPageCallback(messageManager, data.callbackID, { value }); break; } @@ -708,7 +708,7 @@ this.UITour = { window.addEventListener("SSWindowClosing", this); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { log.debug("handleEvent: type =", aEvent.type, "event =", aEvent); switch (aEvent.type) { case "TabSelect": { @@ -734,7 +734,7 @@ this.UITour = { } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { log.debug("observe: aTopic =", aTopic); switch (aTopic) { // The browser message manager is disconnected when the is @@ -769,7 +769,7 @@ this.UITour = { // additional utm_* URL params that should be appended, validate and append // them to the passed URLSearchParams object. Returns true if the params // were validated and appended, and false if the request should be ignored. - _populateCampaignParams: function(urlSearchParams, extraURLCampaignParams) { + _populateCampaignParams(urlSearchParams, extraURLCampaignParams) { // We are extra paranoid about what params we allow to be appended. if (typeof extraURLCampaignParams == "undefined") { // no params, so it's all good. @@ -811,12 +811,12 @@ this.UITour = { return true; }, - setTelemetryBucket: function(aPageID) { + setTelemetryBucket(aPageID) { let bucket = BUCKET_NAME + BrowserUITelemetry.BUCKET_SEPARATOR + aPageID; BrowserUITelemetry.setBucket(bucket); }, - setExpiringTelemetryBucket: function(aPageID, aType) { + setExpiringTelemetryBucket(aPageID, aType) { let bucket = BUCKET_NAME + BrowserUITelemetry.BUCKET_SEPARATOR + aPageID + BrowserUITelemetry.BUCKET_SEPARATOR + aType; @@ -826,7 +826,7 @@ this.UITour = { // This is registered with UITelemetry by BrowserUITelemetry, so that UITour // can remain lazy-loaded on-demand. - getTelemetry: function() { + getTelemetry() { return { seenPageIDs: [...this.seenPageIDs.keys()], }; @@ -835,7 +835,7 @@ this.UITour = { /** * Tear down a tour from a tab e.g. upon switching/closing tabs. */ - teardownTourForBrowser: function(aWindow, aBrowser, aTourPageClosing = false) { + teardownTourForBrowser(aWindow, aBrowser, aTourPageClosing = false) { log.debug("teardownTourForBrowser: aBrowser = ", aBrowser, aTourPageClosing); if (this.pageIDSourceBrowsers.has(aBrowser)) { @@ -873,7 +873,7 @@ this.UITour = { /** * Tear down all tours for a ChromeWindow. */ - teardownTourForWindow: function(aWindow) { + teardownTourForWindow(aWindow) { log.debug("teardownTourForWindow"); aWindow.gBrowser.tabContainer.removeEventListener("TabSelect", this); aWindow.removeEventListener("SSWindowClosing", this); @@ -892,7 +892,7 @@ this.UITour = { }, // This function is copied to UITourListener. - isSafeScheme: function(aURI) { + isSafeScheme(aURI) { let allowedSchemes = new Set(["https", "about"]); if (!Services.prefs.getBoolPref("browser.uitour.requireSecure")) allowedSchemes.add("http"); @@ -905,7 +905,7 @@ this.UITour = { return true; }, - resolveURL: function(aBrowser, aURL) { + resolveURL(aBrowser, aURL) { try { let uri = Services.io.newURI(aURL, null, aBrowser.currentURI); @@ -918,20 +918,20 @@ this.UITour = { return null; }, - sendPageCallback: function(aMessageManager, aCallbackID, aData = {}) { + sendPageCallback(aMessageManager, aCallbackID, aData = {}) { let detail = {data: aData, callbackID: aCallbackID}; log.debug("sendPageCallback", detail); aMessageManager.sendAsyncMessage("UITour:SendPageCallback", detail); }, - isElementVisible: function(aElement) { + isElementVisible(aElement) { let targetStyle = aElement.ownerGlobal.getComputedStyle(aElement); return !aElement.ownerDocument.hidden && targetStyle.display != "none" && targetStyle.visibility == "visible"; }, - getTarget: function(aWindow, aTargetName, aSticky = false) { + getTarget(aWindow, aTargetName, aSticky = false) { log.debug("getTarget:", aTargetName); let deferred = Promise.defer(); if (typeof aTargetName != "string" || !aTargetName) { @@ -966,7 +966,7 @@ this.UITour = { infoPanelOffsetX: targetObject.infoPanelOffsetX, infoPanelOffsetY: targetObject.infoPanelOffsetY, infoPanelPosition: targetObject.infoPanelPosition, - node: node, + node, removeTargetListener: targetObject.removeTargetListener, targetName: aTargetName, widgetName: targetObject.widgetName, @@ -976,7 +976,7 @@ this.UITour = { return deferred.promise; }, - targetIsInAppMenu: function(aTarget) { + targetIsInAppMenu(aTarget) { let placement = CustomizableUI.getPlacementOfWidget(aTarget.widgetName || aTarget.node.id); if (placement && placement.area == CustomizableUI.AREA_PANEL) { return true; @@ -997,7 +997,7 @@ this.UITour = { * Called before opening or after closing a highlight or info panel to see if * we need to open or close the appMenu to see the annotation's anchor. */ - _setAppMenuStateForAnnotation: function(aWindow, aAnnotationType, aShouldOpenForHighlight, aCallback = null) { + _setAppMenuStateForAnnotation(aWindow, aAnnotationType, aShouldOpenForHighlight, aCallback = null) { log.debug("_setAppMenuStateForAnnotation:", aAnnotationType); log.debug("_setAppMenuStateForAnnotation: Menu is expected to be:", aShouldOpenForHighlight ? "open" : "closed"); @@ -1037,14 +1037,14 @@ this.UITour = { }, - previewTheme: function(aTheme) { + previewTheme(aTheme) { let origin = Services.prefs.getCharPref("browser.uitour.themeOrigin"); let data = LightweightThemeManager.parseTheme(aTheme, origin); if (data) LightweightThemeManager.previewTheme(data); }, - resetTheme: function() { + resetTheme() { LightweightThemeManager.resetPreview(); }, @@ -1387,7 +1387,7 @@ this.UITour = { * @param {Node} aAnchor The element that's supposed to be the anchor * @type {Node} */ - _correctAnchor: function(aAnchor) { + _correctAnchor(aAnchor) { // If the target is in the overflow panel, just return the overflow button. if (aAnchor.getAttribute("overflowedItem")) { let doc = aAnchor.ownerDocument; @@ -1407,7 +1407,7 @@ this.UITour = { * @param aEffect (optional) The effect to use from UITour.highlightEffects or "none". * @see UITour.highlightEffects */ - showHighlight: function(aChromeWindow, aTarget, aEffect = "none") { + showHighlight(aChromeWindow, aTarget, aEffect = "none") { function showHighlightPanel() { let highlighter = aChromeWindow.document.getElementById("UITourHighlight"); @@ -1478,7 +1478,7 @@ this.UITour = { showHighlightPanel.bind(this)); }, - hideHighlight: function(aWindow) { + hideHighlight(aWindow) { let highlighter = aWindow.document.getElementById("UITourHighlight"); this._removeAnnotationPanelMutationObserver(highlighter.parentElement); highlighter.parentElement.hidePopup(); @@ -1617,7 +1617,7 @@ this.UITour = { return tooltip.getAttribute("targetName") == aTargetName && tooltip.state != "closed"; }, - hideInfo: function(aWindow) { + hideInfo(aWindow) { let document = aWindow.document; let tooltip = document.getElementById("UITourTooltip"); @@ -1630,7 +1630,7 @@ this.UITour = { tooltipButtons.firstChild.remove(); }, - showMenu: function(aWindow, aMenuName, aOpenCallback = null) { + showMenu(aWindow, aMenuName, aOpenCallback = null) { log.debug("showMenu:", aMenuName); function openMenuButton(aMenuBtn) { if (!aMenuBtn || !aMenuBtn.boxObject || aMenuBtn.open) { @@ -1731,7 +1731,7 @@ this.UITour = { } }, - hideMenu: function(aWindow, aMenuName) { + hideMenu(aWindow, aMenuName) { log.debug("hideMenu:", aMenuName); function closeMenuButton(aMenuBtn) { if (aMenuBtn && aMenuBtn.boxObject) @@ -1749,11 +1749,11 @@ this.UITour = { } }, - showNewTab: function(aWindow, aBrowser) { + showNewTab(aWindow, aBrowser) { aWindow.openLinkIn("about:newtab", "current", {targetBrowser: aBrowser}); }, - hideAnnotationsForPanel: function(aEvent, aTargetPositionCallback) { + hideAnnotationsForPanel(aEvent, aTargetPositionCallback) { let win = aEvent.target.ownerGlobal; let annotationElements = new Map([ // [annotationElement (panel), method to hide the annotation] @@ -1778,7 +1778,7 @@ this.UITour = { UITour.appMenuOpenForAnnotation.clear(); }, - hideAppMenuAnnotations: function(aEvent) { + hideAppMenuAnnotations(aEvent) { UITour.hideAnnotationsForPanel(aEvent, UITour.targetIsInAppMenu); }, @@ -1788,13 +1788,13 @@ this.UITour = { }); }, - onPanelHidden: function(aEvent) { + onPanelHidden(aEvent) { aEvent.target.removeAttribute("noautohide"); UITour.recreatePopup(aEvent.target); UITour.clearAvailableTargetsCache(); }, - recreatePopup: function(aPanel) { + recreatePopup(aPanel) { // After changing popup attributes that relate to how the native widget is created // (e.g. @noautohide) we need to re-create the frame/widget for it to take effect. if (aPanel.hidden) { @@ -1808,7 +1808,7 @@ this.UITour = { aPanel.hidden = false; }, - getConfiguration: function(aMessageManager, aWindow, aConfiguration, aCallbackID) { + getConfiguration(aMessageManager, aWindow, aConfiguration, aCallbackID) { switch (aConfiguration) { case "appinfo": let props = ["defaultUpdateChannel", "version"]; @@ -1888,7 +1888,7 @@ this.UITour = { } }, - setConfiguration: function(aWindow, aConfiguration, aValue) { + setConfiguration(aWindow, aConfiguration, aValue) { switch (aConfiguration) { case "defaultBrowser": // Ignore aValue in this case because the default browser can only @@ -1906,7 +1906,7 @@ this.UITour = { } }, - getAvailableTargets: function(aMessageManager, aChromeWindow, aCallbackID) { + getAvailableTargets(aMessageManager, aChromeWindow, aCallbackID) { Task.spawn(function*() { let window = aChromeWindow; let data = this.availableTargetsCache.get(window); @@ -1941,7 +1941,7 @@ this.UITour = { }); }, - startSubTour: function(aFeature) { + startSubTour(aFeature) { if (aFeature != "string") { log.error("startSubTour: No feature option specified"); return; @@ -1955,7 +1955,7 @@ this.UITour = { } }, - addNavBarWidget: function(aTarget, aMessageManager, aCallbackID) { + addNavBarWidget(aTarget, aMessageManager, aCallbackID) { if (aTarget.node) { log.error("addNavBarWidget: can't add a widget already present:", aTarget); return; @@ -1973,7 +1973,7 @@ this.UITour = { this.sendPageCallback(aMessageManager, aCallbackID); }, - _addAnnotationPanelMutationObserver: function(aPanelEl) { + _addAnnotationPanelMutationObserver(aPanelEl) { if (AppConstants.platform == "linux") { let observer = this._annotationPanelMutationObservers.get(aPanelEl); if (observer) { @@ -1990,7 +1990,7 @@ this.UITour = { } }, - _removeAnnotationPanelMutationObserver: function(aPanelEl) { + _removeAnnotationPanelMutationObserver(aPanelEl) { if (AppConstants.platform == "linux") { let observer = this._annotationPanelMutationObservers.get(aPanelEl); if (observer) { @@ -2005,7 +2005,7 @@ this.UITour = { * nsXULPopupManager::PopupResized and lead to incorrect width and height attributes getting * set on the panel. */ - _annotationMutationCallback: function(aMutations) { + _annotationMutationCallback(aMutations) { for (let mutation of aMutations) { // Remove both attributes at once and ignore remaining mutations to be proccessed. mutation.target.removeAttribute("width"); @@ -2055,7 +2055,7 @@ this.UITour = { } let detail = { event: eventName, - params: params, + params, }; messageManager.sendAsyncMessage("UITour:SendPageNotification", detail); } @@ -2096,7 +2096,7 @@ this.UITour.init(); * Public API to be called by the UITour code */ const UITourHealthReport = { - recordTreatmentTag: function(tag, value) { + recordTreatmentTag(tag, value) { return TelemetryController.submitExternalPing("uitour-tag", { version: 1, diff --git a/browser/components/uitour/content-UITour.js b/browser/components/uitour/content-UITour.js index f5646486f653..f7ef7d371a59 100644 --- a/browser/components/uitour/content-UITour.js +++ b/browser/components/uitour/content-UITour.js @@ -8,7 +8,7 @@ const PREF_TEST_WHITELIST = "browser.uitour.testingOrigins"; const UITOUR_PERMISSION = "uitour"; var UITourListener = { - handleEvent: function(event) { + handleEvent(event) { if (!Services.prefs.getBoolPref("browser.uitour.enabled")) { return; } @@ -24,7 +24,7 @@ var UITourListener = { }); }, - isTestingOrigin: function(aURI) { + isTestingOrigin(aURI) { if (Services.prefs.getPrefType(PREF_TEST_WHITELIST) != Services.prefs.PREF_STRING) { return false; } @@ -44,7 +44,7 @@ var UITourListener = { }, // This function is copied from UITour.jsm. - isSafeScheme: function(aURI) { + isSafeScheme(aURI) { let allowedSchemes = new Set(["https", "about"]); if (!Services.prefs.getBoolPref("browser.uitour.requireSecure")) allowedSchemes.add("http"); @@ -55,7 +55,7 @@ var UITourListener = { return true; }, - ensureTrustedOrigin: function() { + ensureTrustedOrigin() { if (content.top != content) return false; @@ -74,7 +74,7 @@ var UITourListener = { return this.isTestingOrigin(uri); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "UITour:SendPageCallback": this.sendPageEvent("Response", aMessage.data); @@ -85,7 +85,7 @@ var UITourListener = { } }, - sendPageEvent: function(type, detail) { + sendPageEvent(type, detail) { if (!this.ensureTrustedOrigin()) { return; } diff --git a/browser/components/uitour/test/browser_UITour_defaultBrowser.js b/browser/components/uitour/test/browser_UITour_defaultBrowser.js index 5ebf553b0562..f5f529d30b19 100644 --- a/browser/components/uitour/test/browser_UITour_defaultBrowser.js +++ b/browser/components/uitour/test/browser_UITour_defaultBrowser.js @@ -12,8 +12,8 @@ Cc["@mozilla.org/moz/jssubscript-loader;1"] function MockShellService() {} MockShellService.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIShellService]), - isDefaultBrowser: function(aStartupCheck, aForAllTypes) { return false; }, - setDefaultBrowser: function(aClaimAllTypes, aForAllUsers) { + isDefaultBrowser(aStartupCheck, aForAllTypes) { return false; }, + setDefaultBrowser(aClaimAllTypes, aForAllUsers) { setDefaultBrowserCalled = true; }, shouldCheckDefaultBrowser: false, @@ -23,12 +23,12 @@ MockShellService.prototype = { BACKGROUND_CENTER : 3, BACKGROUND_FILL : 4, BACKGROUND_FIT : 5, - setDesktopBackground: function(aElement, aPosition) {}, + setDesktopBackground(aElement, aPosition) {}, APPLICATION_MAIL : 0, APPLICATION_NEWS : 1, - openApplication: function(aApplication) {}, + openApplication(aApplication) {}, desktopBackgroundColor: 0, - openApplicationWithURI: function(aApplication, aURI) {}, + openApplicationWithURI(aApplication, aURI) {}, defaultFeedReader: 0, }; diff --git a/browser/components/uitour/test/browser_UITour_heartbeat.js b/browser/components/uitour/test/browser_UITour_heartbeat.js index 6cfeb2a2732c..5b6a3ba717ef 100644 --- a/browser/components/uitour/test/browser_UITour_heartbeat.js +++ b/browser/components/uitour/test/browser_UITour_heartbeat.js @@ -221,7 +221,7 @@ add_UITour_task(function* test_heartbeat_take_optional_icon_URL() { // Show the Heartbeat notification and wait for it to be displayed. let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL, null, null, { - iconURL: iconURL + iconURL }); // Validate the returned timestamp. diff --git a/browser/components/uitour/test/browser_UITour_modalDialog.js b/browser/components/uitour/test/browser_UITour_modalDialog.js index 49d01474f9c2..a697d5f2df3a 100644 --- a/browser/components/uitour/test/browser_UITour_modalDialog.js +++ b/browser/components/uitour/test/browser_UITour_modalDialog.js @@ -22,7 +22,7 @@ function startCallbackTimer() { var observer = SpecialPowers.wrapCallbackObject({ - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports, Ci.nsISupportsWeakReference]; @@ -31,7 +31,7 @@ var observer = SpecialPowers.wrapCallbackObject({ return this; }, - observe : function(subject, topic, data) { + observe(subject, topic, data) { var doc = getDialogDoc(); if (doc) handleDialog(doc); diff --git a/browser/components/uitour/test/browser_no_tabs.js b/browser/components/uitour/test/browser_no_tabs.js index 62048b1568d3..05c0f2b9f67f 100644 --- a/browser/components/uitour/test/browser_no_tabs.js +++ b/browser/components/uitour/test/browser_no_tabs.js @@ -26,7 +26,7 @@ function createHiddenBrowser(aURL) { browser.setAttribute("src", aURL); doc.documentElement.appendChild(browser); - resolve({frame: frame, browser: browser}); + resolve({frame, browser}); })); } diff --git a/browser/experiments/Experiments.jsm b/browser/experiments/Experiments.jsm index f76092f497f9..9038c7d801b4 100644 --- a/browser/experiments/Experiments.jsm +++ b/browser/experiments/Experiments.jsm @@ -211,7 +211,7 @@ var Experiments = { /** * Provides access to the global `Experiments.Experiments` instance. */ - instance: function() { + instance() { if (!gExperiments) { gExperiments = new Experiments.Experiments(); } @@ -236,11 +236,11 @@ Experiments.Policy = function() { }; Experiments.Policy.prototype = { - now: function() { + now() { return new Date(); }, - random: function() { + random() { let pref = gPrefs.get(PREF_FORCE_SAMPLE); if (pref !== undefined) { let val = Number.parseFloat(pref); @@ -256,19 +256,19 @@ Experiments.Policy.prototype = { return Math.random(); }, - futureDate: function(offset) { + futureDate(offset) { return new Date(this.now().getTime() + offset); }, - oneshotTimer: function(callback, timeout, thisObj, name) { + oneshotTimer(callback, timeout, thisObj, name) { return CommonUtils.namedTimer(callback, timeout, thisObj, name); }, - updatechannel: function() { + updatechannel() { return UpdateUtils.UpdateChannel; }, - locale: function() { + locale() { let chrome = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry); return chrome.getSelectedLocale("global"); }, @@ -277,7 +277,7 @@ Experiments.Policy.prototype = { * For testing a race condition, one of the tests delays the callback of * writing the cache by replacing this policy function. */ - delayCacheWrite: function(promise) { + delayCacheWrite(promise) { return promise; }, }; @@ -373,7 +373,7 @@ Experiments.Experiments.prototype = { return !this._shutdown; }, - init: function() { + init() { this._shutdown = false; configureLogging(); @@ -467,7 +467,7 @@ Experiments.Experiments.prototype = { }), // Return state information, for debugging purposes. - _getState: function() { + _getState() { let activeExperiment = this._getActiveExperiment(); let state = { isShutdown: this._shutdown, @@ -497,13 +497,13 @@ Experiments.Experiments.prototype = { return state; }, - _addToForensicsLog: function(what, string) { + _addToForensicsLog(what, string) { this._forensicsLogs.shift(); let timeInSec = Math.floor(Services.telemetry.msSinceProcessStart() / 1000); this._forensicsLogs.push(`${timeInSec}: ${what} - ${string}`); }, - _registerWithAddonManager: function(previousExperimentsProvider) { + _registerWithAddonManager(previousExperimentsProvider) { this._log.trace("Registering instance with Addon Manager."); AddonManager.addAddonListener(this); @@ -526,7 +526,7 @@ Experiments.Experiments.prototype = { }, - _unregisterWithAddonManager: function() { + _unregisterWithAddonManager() { this._log.trace("Unregistering instance with Addon Manager."); this._log.trace("Removing install listener from add-on manager."); @@ -546,7 +546,7 @@ Experiments.Experiments.prototype = { * Change the PreviousExperimentsProvider that this instance uses. * For testing only. */ - _setPreviousExperimentsProvider: function(provider) { + _setPreviousExperimentsProvider(provider) { this._unregisterWithAddonManager(); this._registerWithAddonManager(provider); }, @@ -554,7 +554,7 @@ Experiments.Experiments.prototype = { /** * Throws an exception if we've already shut down. */ - _checkForShutdown: function() { + _checkForShutdown() { if (this._shutdown) { throw new AlreadyShutdownError("uninit() already called"); } @@ -594,7 +594,7 @@ Experiments.Experiments.prototype = { } }), - _telemetryStatusChanged: function() { + _telemetryStatusChanged() { this._toggleExperimentsEnabled(gExperimentsEnabled); }, @@ -616,7 +616,7 @@ Experiments.Experiments.prototype = { * * @return Promise> Array of experiment info objects. */ - getExperiments: function() { + getExperiments() { return Task.spawn(function*() { yield this._loadTask; let list = []; @@ -628,7 +628,7 @@ Experiments.Experiments.prototype = { } list.push({ - id: id, + id, name: experiment._name, description: experiment._description, active: experiment.enabled, @@ -648,7 +648,7 @@ Experiments.Experiments.prototype = { * Returns the ExperimentInfo for the active experiment, or null * if there is none. */ - getActiveExperiment: function() { + getActiveExperiment() { let experiment = this._getActiveExperiment(); if (!experiment) { return null; @@ -718,7 +718,7 @@ Experiments.Experiments.prototype = { /** * Determine whether another date has the same UTC day as now(). */ - _dateIsTodayUTC: function(d) { + _dateIsTodayUTC(d) { let now = this._policy.now(); return stripDateToMidnight(now).getTime() == stripDateToMidnight(d).getTime(); @@ -734,7 +734,7 @@ Experiments.Experiments.prototype = { * * @return Promise */ - lastActiveToday: function() { + lastActiveToday() { return Task.spawn(function* getMostRecentActiveExperimentTask() { let experiments = yield this.getExperiments(); @@ -753,7 +753,7 @@ Experiments.Experiments.prototype = { }.bind(this)); }, - _run: function() { + _run() { this._log.trace("_run"); this._checkForShutdown(); if (!this._mainTask) { @@ -783,7 +783,7 @@ Experiments.Experiments.prototype = { return this._mainTask; }, - _main: function*() { + *_main() { do { this._log.trace("_main iteration"); yield this._loadTask; @@ -804,7 +804,7 @@ Experiments.Experiments.prototype = { while (this._refresh || this._terminateReason || this._dirty); }, - _loadManifest: function*() { + *_loadManifest() { this._log.trace("_loadManifest"); let uri = Services.urlFormatter.formatURLPref(PREF_BRANCH + PREF_MANIFEST_URI); @@ -833,7 +833,7 @@ Experiments.Experiments.prototype = { * @return Promise<> * The promise is resolved when the manifest and experiment list is updated. */ - updateManifest: function() { + updateManifest() { this._log.trace("updateManifest()"); if (!gExperimentsEnabled) { @@ -848,7 +848,7 @@ Experiments.Experiments.prototype = { return this._run(); }, - notify: function(timer) { + notify(timer) { this._log.trace("notify()"); this._checkForShutdown(); return this._run(); @@ -856,7 +856,7 @@ Experiments.Experiments.prototype = { // START OF ADD-ON LISTENERS - onUninstalled: function(addon) { + onUninstalled(addon) { this._log.trace("onUninstalled() - addon id: " + addon.id); if (gActiveUninstallAddonIDs.has(addon.id)) { this._log.trace("matches pending uninstall"); @@ -873,7 +873,7 @@ Experiments.Experiments.prototype = { /** * @returns {Boolean} returns false when we cancel the install. */ - onInstallStarted: function(install) { + onInstallStarted(install) { if (install.addon.type != "experiment") { return true; } @@ -917,7 +917,7 @@ Experiments.Experiments.prototype = { // END OF ADD-ON LISTENERS. - _getExperimentByAddonId: function(addonId) { + _getExperimentByAddonId(addonId) { for (let [, entry] of this._experiments) { if (entry._addonId === addonId) { return entry; @@ -931,7 +931,7 @@ Experiments.Experiments.prototype = { * Helper function to make HTTP GET requests. Returns a promise that is resolved with * the responseText when the request is complete. */ - _httpGetRequest: function(url) { + _httpGetRequest(url) { this._log.trace("httpGetRequest(" + url + ")"); let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest); @@ -986,7 +986,7 @@ Experiments.Experiments.prototype = { /* * Part of the main task to save the cache to disk, called from _main. */ - _saveToCache: function* () { + *_saveToCache() { this._log.trace("_saveToCache"); let path = this._cacheFilePath; this._dirty = false; @@ -1029,7 +1029,7 @@ Experiments.Experiments.prototype = { } }), - _populateFromCache: function(data) { + _populateFromCache(data) { this._log.trace("populateFromCache() - data: " + JSON.stringify(data)); // If the user has a newer cache version than we can understand, we fail @@ -1062,7 +1062,7 @@ Experiments.Experiments.prototype = { * Update the experiment entries from the experiments * array in the manifest */ - _updateExperiments: function(manifestObject) { + _updateExperiments(manifestObject) { this._log.trace("_updateExperiments() - experiments: " + JSON.stringify(manifestObject)); if (manifestObject.version !== MANIFEST_VERSION) { @@ -1113,7 +1113,7 @@ Experiments.Experiments.prototype = { this._dirty = true; }, - getActiveExperimentID: function() { + getActiveExperimentID() { if (!this._experiments) { return null; } @@ -1124,7 +1124,7 @@ Experiments.Experiments.prototype = { return e.id; }, - getActiveExperimentBranch: function() { + getActiveExperimentBranch() { if (!this._experiments) { return null; } @@ -1135,7 +1135,7 @@ Experiments.Experiments.prototype = { return e.branch; }, - _getActiveExperiment: function() { + _getActiveExperiment() { let enabled = [...this._experiments.values()].filter(experiment => experiment._enabled); if (enabled.length == 1) { @@ -1155,7 +1155,7 @@ Experiments.Experiments.prototype = { * * @return Promise<> Promise that will get resolved once the task is done or failed. */ - disableExperiment: function(reason) { + disableExperiment(reason) { if (!reason) { throw new Error("Must specify a termination reason."); } @@ -1180,7 +1180,7 @@ Experiments.Experiments.prototype = { * Task function to check applicability of experiments, disable the active * experiment if needed and activate the first applicable candidate. */ - _evaluateExperiments: function*() { + *_evaluateExperiments() { this._log.trace("_evaluateExperiments"); this._checkForShutdown(); @@ -1317,7 +1317,7 @@ Experiments.Experiments.prototype = { /* * Schedule the soonest re-check of experiment applicability that is needed. */ - _scheduleNextRun: function() { + _scheduleNextRun() { this._checkForShutdown(); if (this._timer) { @@ -1462,7 +1462,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The experiment data from the manifest. * @return boolean Whether initialization succeeded. */ - initFromManifestData: function(data) { + initFromManifestData(data) { if (!this._isManifestDataValid(data)) { return false; } @@ -1522,7 +1522,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The entry data from the cache. * @return boolean Whether initialization succeeded. */ - initFromCacheData: function(data) { + initFromCacheData(data) { for (let [key, dval] of this.UPGRADE_KEYS) { if (!(key in data)) { data[key] = dval; @@ -1567,7 +1567,7 @@ Experiments.ExperimentEntry.prototype = { /* * Returns a JSON representation of this object. */ - toJSON: function() { + toJSON() { let obj = {}; // Dates are serialized separately as epoch ms. @@ -1592,7 +1592,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The experiment data from the manifest. * @return boolean Whether updating succeeded. */ - updateFromManifestData: function(data) { + updateFromManifestData(data) { let old = this._manifestData; if (!this._isManifestDataValid(data)) { @@ -1624,7 +1624,7 @@ Experiments.ExperimentEntry.prototype = { * If it is not applicable it is rejected with * a Promise which contains the reason. */ - isApplicable: function() { + isApplicable() { let versionCmp = Cc["@mozilla.org/xpcom/version-comparator;1"] .getService(Ci.nsIVersionComparator); let app = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo); @@ -2015,7 +2015,7 @@ Experiments.ExperimentEntry.prototype = { * * @return Promise */ - _getAddon: function() { + _getAddon() { if (!this._addonId) { return Promise.resolve(null); } @@ -2030,7 +2030,7 @@ Experiments.ExperimentEntry.prototype = { }); }, - _logTermination: function(terminationKind, terminationReason) { + _logTermination(terminationKind, terminationReason) { if (terminationKind === undefined) { return; } @@ -2051,7 +2051,7 @@ Experiments.ExperimentEntry.prototype = { /** * Determine whether an active experiment should be stopped. */ - shouldStop: function() { + shouldStop() { if (!this._enabled) { throw new Error("shouldStop must not be called on disabled experiments."); } @@ -2059,7 +2059,7 @@ Experiments.ExperimentEntry.prototype = { let deferred = Promise.defer(); this.isApplicable().then( () => deferred.resolve({shouldStop: false}), - reason => deferred.resolve({shouldStop: true, reason: reason}) + reason => deferred.resolve({shouldStop: true, reason}) ); return deferred.promise; @@ -2068,7 +2068,7 @@ Experiments.ExperimentEntry.prototype = { /* * Should this be discarded from the cache due to age? */ - shouldDiscard: function() { + shouldDiscard() { let limit = this._policy.now(); limit.setDate(limit.getDate() - KEEP_HISTORY_N_DAYS); return (this._lastChangedDate < limit); @@ -2078,7 +2078,7 @@ Experiments.ExperimentEntry.prototype = { * Get next date (in epoch-ms) to schedule a re-evaluation for this. * Returns 0 if it doesn't need one. */ - getScheduleTime: function() { + getScheduleTime() { if (this._enabled) { let startTime = this._startDate.getTime(); let maxActiveTime = startTime + 1000 * this._manifestData.maxActiveSeconds; @@ -2095,7 +2095,7 @@ Experiments.ExperimentEntry.prototype = { /* * Perform sanity checks on the experiment data. */ - _isManifestDataValid: function(data) { + _isManifestDataValid(data) { this._log.trace("isManifestDataValid() - data: " + JSON.stringify(data)); for (let key of this.MANIFEST_REQUIRED_FIELDS) { @@ -2148,12 +2148,12 @@ this.Experiments.PreviousExperimentProvider = function(experiments) { this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ name: "PreviousExperimentProvider", - startup: function() { + startup() { this._log.trace("startup()"); Services.obs.addObserver(this, EXPERIMENTS_CHANGED_TOPIC, false); }, - shutdown: function() { + shutdown() { this._log.trace("shutdown()"); try { Services.obs.removeObserver(this, EXPERIMENTS_CHANGED_TOPIC); @@ -2162,7 +2162,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ } }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case EXPERIMENTS_CHANGED_TOPIC: this._updateExperimentList(); @@ -2170,7 +2170,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ } }, - getAddonByID: function(id, cb) { + getAddonByID(id, cb) { for (let experiment of this._experimentList) { if (experiment.id == id) { cb(new PreviousExperimentAddon(experiment)); @@ -2181,7 +2181,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ cb(null); }, - getAddonsByTypes: function(types, cb) { + getAddonsByTypes(types, cb) { if (types && types.length > 0 && types.indexOf("experiment") == -1) { cb([]); return; @@ -2190,7 +2190,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ cb(this._experimentList.map(e => new PreviousExperimentAddon(e))); }, - _updateExperimentList: function() { + _updateExperimentList() { return this._experiments.getExperiments().then((experiments) => { let list = experiments.filter(e => !e.active); @@ -2323,11 +2323,11 @@ PreviousExperimentAddon.prototype = Object.freeze({ // BEGIN REQUIRED METHODS - isCompatibleWith: function(appVersion, platformVersion) { + isCompatibleWith(appVersion, platformVersion) { return true; }, - findUpdates: function(listener, reason, appVersion, platformVersion) { + findUpdates(listener, reason, appVersion, platformVersion) { AddonManagerPrivate.callNoUpdateListeners(this, listener, reason, appVersion, platformVersion); }, diff --git a/browser/experiments/ExperimentsService.js b/browser/experiments/ExperimentsService.js index 478793617f29..28da659bb0a9 100644 --- a/browser/experiments/ExperimentsService.js +++ b/browser/experiments/ExperimentsService.js @@ -54,7 +54,7 @@ ExperimentsService.prototype = { classID: Components.ID("{f7800463-3b97-47f9-9341-b7617e6d8d49}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback, Ci.nsIObserver]), - notify: function(timer) { + notify(timer) { if (!gExperimentsEnabled) { return; } @@ -67,14 +67,14 @@ ExperimentsService.prototype = { } }, - _delayedInit: function() { + _delayedInit() { if (!this._initialized) { this._initialized = true; Experiments.instance(); // for side effects } }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "profile-after-change": if (gExperimentsEnabled) { diff --git a/browser/experiments/test/xpcshell/test_activate.js b/browser/experiments/test/xpcshell/test_activate.js index 60deafbfb3d5..3e62c896241d 100644 --- a/browser/experiments/test/xpcshell/test_activate.js +++ b/browser/experiments/test/xpcshell/test_activate.js @@ -52,7 +52,7 @@ function isApplicable(experiment) { let deferred = Promise.defer(); experiment.isApplicable().then( result => deferred.resolve({ applicable: true, reason: null }), - reason => deferred.resolve({ applicable: false, reason: reason }) + reason => deferred.resolve({ applicable: false, reason }) ); return deferred.promise; diff --git a/browser/extensions/pocket/bootstrap.js b/browser/extensions/pocket/bootstrap.js index a9a70d0b7011..1d2f7313679f 100644 --- a/browser/extensions/pocket/bootstrap.js +++ b/browser/extensions/pocket/bootstrap.js @@ -91,13 +91,13 @@ function CreatePocketWidget(reason) { label: gPocketBundle.GetStringFromName("pocket-button.label"), tooltiptext: gPocketBundle.GetStringFromName("pocket-button.tooltiptext"), // Use forwarding functions here to avoid loading Pocket.jsm on startup: - onViewShowing: function() { + onViewShowing() { return Pocket.onPanelViewShowing.apply(this, arguments); }, - onViewHiding: function() { + onViewHiding() { return Pocket.onPanelViewHiding.apply(this, arguments); }, - onBeforeCreated: function(doc) { + onBeforeCreated(doc) { // Bug 1223127,CUI should make this easier to do. if (doc.getElementById("PanelUI-pocketView")) return; @@ -158,10 +158,10 @@ function CreatePocketWidget(reason) { // PocketContextMenu // When the context menu is opened check if we need to build and enable pocket UI. var PocketContextMenu = { - init: function() { + init() { Services.obs.addObserver(this, "on-build-contextmenu", false); }, - shutdown: function() { + shutdown() { Services.obs.removeObserver(this, "on-build-contextmenu"); // loop through windows and remove context menus // iterate through all windows and add pocket to them @@ -174,7 +174,7 @@ var PocketContextMenu = { } } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { let subject = aSubject.wrappedJSObject; let document = subject.menu.ownerDocument; let pocketEnabled = CustomizableUI.getPlacementOfWidget("pocket-button"); @@ -240,20 +240,20 @@ var PocketReader = { this._hidden = hide; this.update(); }, - startup: function() { + startup() { // Setup the listeners, update will be called when the widget is added, // no need to do that now. let mm = Services.mm; mm.addMessageListener("Reader:OnSetup", this); mm.addMessageListener("Reader:Clicked-pocket-button", this); }, - shutdown: function() { + shutdown() { let mm = Services.mm; mm.removeMessageListener("Reader:OnSetup", this); mm.removeMessageListener("Reader:Clicked-pocket-button", this); this.hidden = true; }, - update: function() { + update() { if (this.hidden) { Services.mm.broadcastAsyncMessage("Reader:RemoveButton", { id: "pocket-button" }); } else { @@ -263,7 +263,7 @@ var PocketReader = { image: "chrome://pocket/content/panels/img/pocket.svg#pocket-mark" }); } }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Reader:OnSetup": { // Tell the reader about our button. @@ -299,7 +299,7 @@ var PocketReader = { function pktUIGetter(prop, window) { return { - get: function() { + get() { // delete any getters for properties loaded from main.js so we only load main.js once delete window.pktUI; delete window.pktApi; @@ -313,7 +313,7 @@ function pktUIGetter(prop, window) { } var PocketOverlay = { - startup: function(reason) { + startup(reason) { let styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"] .getService(Ci.nsIStyleSheetService); this._sheetType = styleSheetService.AUTHOR_SHEET; @@ -329,7 +329,7 @@ var PocketOverlay = { this.onWindowOpened(win); } }, - shutdown: function(reason) { + shutdown(reason) { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.broadcastAsyncMessage("PocketShuttingDown"); @@ -359,14 +359,14 @@ var PocketOverlay = { PocketContextMenu.shutdown(); PocketReader.shutdown(); }, - onWindowOpened: function(window) { + onWindowOpened(window) { if (window.hasOwnProperty("pktUI")) return; this.setWindowScripts(window); this.addStyles(window); this.updateWindow(window); }, - setWindowScripts: function(window) { + setWindowScripts(window) { XPCOMUtils.defineLazyModuleGetter(window, "Pocket", "chrome://pocket/content/Pocket.jsm"); // Can't use XPCOMUtils for these because the scripts try to define the variables @@ -376,7 +376,7 @@ var PocketOverlay = { Object.defineProperty(window, "pktUIMessaging", pktUIGetter("pktUIMessaging", window)); }, // called for each window as it is opened - updateWindow: function(window) { + updateWindow(window) { // insert our three menu items let document = window.document; let hidden = !CustomizableUI.getPlacementOfWidget("pocket-button"); @@ -438,7 +438,7 @@ var PocketOverlay = { sib.parentNode.insertBefore(menu, sib); } }, - onWidgetAfterDOMChange: function(aWidgetNode) { + onWidgetAfterDOMChange(aWidgetNode) { if (aWidgetNode.id != "pocket-button") { return; } @@ -455,12 +455,12 @@ var PocketOverlay = { PocketReader.hidden = hidden; }, - addStyles: function(win) { + addStyles(win) { let utils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); utils.addSheet(this._cachedSheet, this._sheetType); }, - removeStyles: function(win) { + removeStyles(win) { let utils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); utils.removeSheet(gPocketStyleURI, this._sheetType); } diff --git a/browser/extensions/pocket/content/AboutPocket.jsm b/browser/extensions/pocket/content/AboutPocket.jsm index c7f57aa87304..53e7788b3e47 100644 --- a/browser/extensions/pocket/content/AboutPocket.jsm +++ b/browser/extensions/pocket/content/AboutPocket.jsm @@ -31,11 +31,11 @@ function AboutPage(chromeURL, aboutHost, classID, description, uriFlags) { AboutPage.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]), - getURIFlags: function(aURI) { // eslint-disable-line no-unused-vars + getURIFlags(aURI) { // eslint-disable-line no-unused-vars return this.uriFlags; }, - newChannel: function(aURI, aLoadInfo) { + newChannel(aURI, aLoadInfo) { let newURI = Services.io.newURI(this.chromeURL, null, null); let channel = Services.io.newChannelFromURIWithLoadInfo(newURI, aLoadInfo); @@ -48,20 +48,20 @@ AboutPage.prototype = { return channel; }, - createInstance: function(outer, iid) { + createInstance(outer, iid) { if (outer !== null) { throw Cr.NS_ERROR_NO_AGGREGATION; } return this.QueryInterface(iid); }, - register: function() { + register() { Cm.QueryInterface(Ci.nsIComponentRegistrar).registerFactory( this.classID, this.description, "@mozilla.org/network/protocol/about;1?what=" + this.aboutHost, this); }, - unregister: function() { + unregister() { Cm.QueryInterface(Ci.nsIComponentRegistrar).unregisterFactory( this.classID, this); } diff --git a/browser/extensions/pocket/content/main.js b/browser/extensions/pocket/content/main.js index ff3b5eccaff2..07147fd2155a 100644 --- a/browser/extensions/pocket/content/main.js +++ b/browser/extensions/pocket/content/main.js @@ -175,7 +175,7 @@ var pktUI = (function() { + inOverflowMenu + "&locale=" + getUILocale(), { - onShow: function() { + onShow() { }, onHide: panelDidHide, width: inOverflowMenu ? overflowMenuWidth : 300, @@ -203,7 +203,7 @@ var pktUI = (function() { } var panelId = showPanel("about:pocket-saved?pockethost=" + Services.prefs.getCharPref("extensions.pocket.site") + "&premiumStatus=" + (pktApi.isPremiumUser() ? '1' : '0') + '&inoverflowmenu=' + inOverflowMenu + "&locale=" + getUILocale(), { - onShow: function() { + onShow() { var saveLinkMessageId = 'saveLink'; // Send error message for invalid url @@ -229,15 +229,15 @@ var pktUI = (function() { // Add url var options = { - success: function(data, request) { + success(data, request) { var item = data.item; var successResponse = { status: "success", - item: item + item }; pktUIMessaging.sendMessageToPanel(panelId, saveLinkMessageId, successResponse); }, - error: function(error, request) { + error(error, request) { // If user is not authorized show singup page if (request.status === 401) { showSignUp(); @@ -418,8 +418,8 @@ var pktUI = (function() { pktUIMessaging.addMessageListener(iframe, _getTagsMessageId, function(panelId, data) { pktApi.getTags(function(tags, usedTags) { pktUIMessaging.sendResponseMessageToPanel(panelId, _getTagsMessageId, { - tags: tags, - usedTags: usedTags + tags, + usedTags }); }); }); @@ -428,17 +428,17 @@ var pktUI = (function() { var _getSuggestedTagsMessageId = "getSuggestedTags"; pktUIMessaging.addMessageListener(iframe, _getSuggestedTagsMessageId, function(panelId, data) { pktApi.getSuggestedTagsForURL(data.url, { - success: function(data, response) { + success(data, response) { var suggestedTags = data.suggested_tags; var successResponse = { status: "success", value: { - suggestedTags: suggestedTags + suggestedTags } } pktUIMessaging.sendResponseMessageToPanel(panelId, _getSuggestedTagsMessageId, successResponse); }, - error: function(error, response) { + error(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _getSuggestedTagsMessageId, error); } }) @@ -448,11 +448,11 @@ var pktUI = (function() { var _addTagsMessageId = "addTags"; pktUIMessaging.addMessageListener(iframe, _addTagsMessageId, function(panelId, data) { pktApi.addTagsToURL(data.url, data.tags, { - success: function(data, response) { + success(data, response) { var successResponse = {status: "success"}; pktUIMessaging.sendResponseMessageToPanel(panelId, _addTagsMessageId, successResponse); }, - error: function(error, response) { + error(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _addTagsMessageId, error); } }); @@ -462,11 +462,11 @@ var pktUI = (function() { var _deleteItemMessageId = "deleteItem"; pktUIMessaging.addMessageListener(iframe, _deleteItemMessageId, function(panelId, data) { pktApi.deleteItem(data.itemId, { - success: function(data, response) { + success(data, response) { var successResponse = {status: "success"}; pktUIMessaging.sendResponseMessageToPanel(panelId, _deleteItemMessageId, successResponse); }, - error: function(error, response) { + error(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _deleteItemMessageId, error); } }) @@ -485,7 +485,7 @@ var pktUI = (function() { strings[str.key] = str.value; } } - pktUIMessaging.sendResponseMessageToPanel(panelId, _initL10NMessageId, { strings: strings }); + pktUIMessaging.sendResponseMessageToPanel(panelId, _initL10NMessageId, { strings }); }); } @@ -588,15 +588,15 @@ var pktUI = (function() { * Public functions */ return { - getPanelFrame: getPanelFrame, + getPanelFrame, - openTabWithUrl: openTabWithUrl, + openTabWithUrl, - pocketPanelDidShow: pocketPanelDidShow, - pocketPanelDidHide: pocketPanelDidHide, + pocketPanelDidShow, + pocketPanelDidHide, - tryToSaveUrl: tryToSaveUrl, - tryToSaveCurrentPage: tryToSaveCurrentPage + tryToSaveUrl, + tryToSaveCurrentPage }; }()); @@ -669,12 +669,12 @@ var pktUIMessaging = (function() { * iframe as a message response */ function sendErrorMessageToPanel(panelId, messageId, error) { - var errorResponse = {status: "error", error: error}; + var errorResponse = {status: "error", error}; sendMessageToPanel(panelId, messageId, errorResponse); } function sendErrorResponseMessageToPanel(panelId, messageId, error) { - var errorResponse = {status: "error", error: error}; + var errorResponse = {status: "error", error}; sendResponseMessageToPanel(panelId, messageId, errorResponse); } @@ -730,10 +730,10 @@ var pktUIMessaging = (function() { * Public */ return { - addMessageListener: addMessageListener, - sendMessageToPanel: sendMessageToPanel, - sendResponseMessageToPanel: sendResponseMessageToPanel, - sendErrorMessageToPanel: sendErrorMessageToPanel, - sendErrorResponseMessageToPanel: sendErrorResponseMessageToPanel + addMessageListener, + sendMessageToPanel, + sendResponseMessageToPanel, + sendErrorMessageToPanel, + sendErrorResponseMessageToPanel } }()); diff --git a/browser/extensions/pocket/content/panels/js/messages.js b/browser/extensions/pocket/content/panels/js/messages.js index ae08c3e73a3b..eeeceb0a78f4 100644 --- a/browser/extensions/pocket/content/panels/js/messages.js +++ b/browser/extensions/pocket/content/panels/js/messages.js @@ -40,7 +40,7 @@ var pktPanelMessaging = (function() { // Payload needs to be an object in format: // { panelId: panelId, data: {} } var messagePayload = { - panelId: panelId, + panelId, data: (payload || {}) }; @@ -70,9 +70,9 @@ var pktPanelMessaging = (function() { * Public functions */ return { - panelIdFromURL: panelIdFromURL, - addMessageListener : addMessageListener, - removeMessageListener : removeMessageListener, - sendMessage: sendMessage + panelIdFromURL, + addMessageListener, + removeMessageListener, + sendMessage }; }()); diff --git a/browser/extensions/pocket/content/panels/js/saved.js b/browser/extensions/pocket/content/panels/js/saved.js index ff47020d040c..64642f474a75 100644 --- a/browser/extensions/pocket/content/panels/js/saved.js +++ b/browser/extensions/pocket/content/panels/js/saved.js @@ -173,7 +173,7 @@ var PKT_SAVED_OVERLAY = function(options) noResultsHideDropdown: true, scrollKeyboard: true, emptyInputLength: 200, - search_function: function(term, cb) { + search_function(term, cb) { var returnlist = []; if (term.length) { var limit = 15; @@ -191,7 +191,7 @@ var PKT_SAVED_OVERLAY = function(options) } cb(returnlist); }, - textToData: function(text) { + textToData(text) { if ($.trim(text).length > 25 || !$.trim(text).length) { if (text.length > 25) { myself.showTagsError(myself.dictJSON.maxtaglength); @@ -205,7 +205,7 @@ var PKT_SAVED_OVERLAY = function(options) myself.hideTagsError(); return {name:myself.sanitizeText(text.toLowerCase())}; }, - onReady: function() { + onReady() { $('.token-input-dropdown').addClass('token-input-dropdown-tag'); inputwrapper.find('.token-input-input-token input').attr('placeholder', $('.tag-input').attr('placeholder')).css('width', '200px'); if ($('.pkt_ext_suggestedtag_detail').length) { @@ -237,22 +237,22 @@ var PKT_SAVED_OVERLAY = function(options) }); myself.checkPlaceholderStatus(); }, - onAdd: function() { + onAdd() { myself.checkValidTagSubmit(); changestamp = Date.now(); myself.hideInactiveTags(); myself.checkPlaceholderStatus(); }, - onDelete: function() { + onDelete() { myself.checkValidTagSubmit(); changestamp = Date.now(); myself.showActiveTags(); myself.checkPlaceholderStatus(); }, - onShowDropdown: function() { + onShowDropdown() { thePKT_SAVED.sendMessage("expandSavePanel"); }, - onHideDropdown: function() { + onHideDropdown() { thePKT_SAVED.sendMessage("collapseSavePanel"); } }); @@ -457,7 +457,7 @@ var PKT_SAVED_OVERLAY = function(options) }; PKT_SAVED_OVERLAY.prototype = { - create : function() + create() { if (this.active) { @@ -497,7 +497,7 @@ PKT_SAVED_OVERLAY.prototype = { this.initOpenListInput(); this.initAutoCloseEvents(); }, - createPremiumFunctionality: function() + createPremiumFunctionality() { if (this.premiumStatus && !$('.pkt_ext_suggestedtag_detail').length) { @@ -512,7 +512,7 @@ PKT_SAVED_OVERLAY.prototype = { var PKT_SAVED = function() {}; PKT_SAVED.prototype = { - init: function() { + init() { if (this.inited) { return; } @@ -522,15 +522,15 @@ PKT_SAVED.prototype = { this.inited = true; }, - addMessageListener: function(messageId, callback) { + addMessageListener(messageId, callback) { pktPanelMessaging.addMessageListener(this.panelId, messageId, callback); }, - sendMessage: function(messageId, payload, callback) { + sendMessage(messageId, payload, callback) { pktPanelMessaging.sendMessage(this.panelId, messageId, payload, callback); }, - create: function() { + create() { var myself = this; var url = window.location.href.match(/premiumStatus=([\w|\d|\.]*)&?/); if (url && url.length > 1) diff --git a/browser/extensions/pocket/content/panels/js/signup.js b/browser/extensions/pocket/content/panels/js/signup.js index 08821be99324..13794995286d 100644 --- a/browser/extensions/pocket/content/panels/js/signup.js +++ b/browser/extensions/pocket/content/panels/js/signup.js @@ -61,7 +61,7 @@ var PKT_SIGNUP_OVERLAY = function(options) }; PKT_SIGNUP_OVERLAY.prototype = { - create : function() + create() { var controlvariant = window.location.href.match(/controlvariant=([\w|\.]*)&?/); if (controlvariant && controlvariant.length > 1) @@ -145,7 +145,7 @@ PKT_SIGNUP_OVERLAY.prototype = { var PKT_SIGNUP = function() {}; PKT_SIGNUP.prototype = { - init: function() { + init() { if (this.inited) { return; } @@ -155,15 +155,15 @@ PKT_SIGNUP.prototype = { this.inited = true; }, - addMessageListener: function(messageId, callback) { + addMessageListener(messageId, callback) { pktPanelMessaging.addMessageListener(this.panelId, messageId, callback); }, - sendMessage: function(messageId, payload, callback) { + sendMessage(messageId, payload, callback) { pktPanelMessaging.sendMessage(this.panelId, messageId, payload, callback); }, - create: function() { + create() { this.overlay.create(); // tell back end we're ready diff --git a/browser/extensions/pocket/content/pktApi.jsm b/browser/extensions/pocket/content/pktApi.jsm index 63b6d415c9e8..f18117ec0a13 100644 --- a/browser/extensions/pocket/content/pktApi.jsm +++ b/browser/extensions/pocket/content/pktApi.jsm @@ -337,7 +337,7 @@ var pktApi = (function() { var sendData = { access_token: accessToken, - url: url, + url, since: since ? since : 0 }; @@ -348,7 +348,7 @@ var pktApi = (function() { return apiRequest({ path: "/firefox/save", data: sendData, - success: function(data) { + success(data) { // Update premium status, tags and since var tags = data.tags; @@ -458,7 +458,7 @@ var pktApi = (function() { * @return {Boolean} Returns Boolean whether the api call started sucessfully */ function addTagsToURL(url, tags, options) { - return addTags({url: url}, tags, options); + return addTags({url}, tags, options); } /** @@ -475,7 +475,7 @@ var pktApi = (function() { // Tags add action var action = { action: "tags_add", - tags: tags + tags }; action = extend(action, actionPart); @@ -584,7 +584,7 @@ var pktApi = (function() { * @return {Boolean} Returns Boolean whether the api call started sucessfully */ function getSuggestedTagsForURL(url, options) { - return getSuggestedTags({url: url}, options); + return getSuggestedTags({url}, options); } /** @@ -600,7 +600,7 @@ var pktApi = (function() { return apiRequest({ path: "/getSuggestedTags", - data: data, + data, success: options.success, error: options.error }); @@ -642,16 +642,16 @@ var pktApi = (function() { * Public functions */ return { - isUserLoggedIn : isUserLoggedIn, - clearUserData: clearUserData, - addLink: addLink, - deleteItem: deleteItem, - addTagsToItem: addTagsToItem, - addTagsToURL: addTagsToURL, - getTags: getTags, - isPremiumUser: isPremiumUser, - getSuggestedTagsForItem: getSuggestedTagsForItem, - getSuggestedTagsForURL: getSuggestedTagsForURL, - getSignupPanelTabTestVariant: getSignupPanelTabTestVariant, + isUserLoggedIn, + clearUserData, + addLink, + deleteItem, + addTagsToItem, + addTagsToURL, + getTags, + isPremiumUser, + getSuggestedTagsForItem, + getSuggestedTagsForURL, + getSignupPanelTabTestVariant, }; }()); diff --git a/browser/extensions/pocket/test/head.js b/browser/extensions/pocket/test/head.js index e044a42c76ba..a4cf877b0196 100644 --- a/browser/extensions/pocket/test/head.js +++ b/browser/extensions/pocket/test/head.js @@ -36,7 +36,7 @@ function promisePocketDisabled() { } return new Promise((resolve, reject) => { let listener = { - onWidgetDestroyed: function(widgetid) { + onWidgetDestroyed(widgetid) { if (widgetid == "pocket-button") { CustomizableUI.removeListener(listener); info( "pocket-button destroyed"); diff --git a/browser/extensions/presentation/bootstrap.js b/browser/extensions/presentation/bootstrap.js index 5cd2f11036b9..d81e3643adaa 100644 --- a/browser/extensions/presentation/bootstrap.js +++ b/browser/extensions/presentation/bootstrap.js @@ -33,7 +33,7 @@ function shutdown(aData, aReason) { // Register/unregister a constructor as a factory. function Factory() {} Factory.prototype = { - register: function(targetConstructor) { + register(targetConstructor) { let proto = targetConstructor.prototype; this._classID = proto.classID; @@ -45,7 +45,7 @@ Factory.prototype = { proto.contractID, factory); }, - unregister: function() { + unregister() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(this._classID, this._factory); this._factory = null; @@ -55,14 +55,14 @@ Factory.prototype = { var Presentation = { // PUBLIC APIs - init: function() { + init() { log("init"); // Register PresentationDevicePrompt into a XPCOM component. Cu.import(PRESENTATION_DEVICE_PROMPT_PATH); this._register(); }, - uninit: function() { + uninit() { log("uninit"); // Unregister PresentationDevicePrompt XPCOM component. this._unregister(); @@ -70,13 +70,13 @@ var Presentation = { }, // PRIVATE APIs - _register: function() { + _register() { log("_register"); this._devicePromptFactory = new Factory(); this._devicePromptFactory.register(PresentationDevicePrompt); }, - _unregister: function() { + _unregister() { log("_unregister"); this._devicePromptFactory.unregister(); delete this._devicePromptFactory; diff --git a/browser/extensions/presentation/content/PresentationDevicePrompt.jsm b/browser/extensions/presentation/content/PresentationDevicePrompt.jsm index 883ffff34fa3..949040192712 100644 --- a/browser/extensions/presentation/content/PresentationDevicePrompt.jsm +++ b/browser/extensions/presentation/content/PresentationDevicePrompt.jsm @@ -171,7 +171,7 @@ PresentationPermissionPrompt.prototype = { } return this.principal.URI.hostPort; }, - _createPopupContent: function() { + _createPopupContent() { log("_createPopupContent"); if (!this._devices.length) { @@ -223,7 +223,7 @@ PresentationDevicePrompt.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIPresentationDevicePrompt]), // This will be fired when window.PresentationRequest(URL).start() is called. - promptDeviceSelection: function(aRequest) { + promptDeviceSelection(aRequest) { log("promptDeviceSelection"); // Cancel request if no available device. @@ -238,7 +238,7 @@ PresentationDevicePrompt.prototype = { let promptUI = new PresentationPermissionPrompt(aRequest, devices); promptUI.prompt(); }, - _loadDevices: function() { + _loadDevices() { let deviceManager = Cc["@mozilla.org/presentation-device/manager;1"] .getService(Ci.nsIPresentationDeviceManager); let devices = deviceManager.getAvailableDevices().QueryInterface(Ci.nsIArray); diff --git a/browser/modules/AboutHome.jsm b/browser/modules/AboutHome.jsm index 01cbafba99f4..627e7bd56af2 100644 --- a/browser/modules/AboutHome.jsm +++ b/browser/modules/AboutHome.jsm @@ -104,7 +104,7 @@ var AboutHome = { "AboutHome:MaybeShowAutoMigrationUndoNotification", ], - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); for (let msg of this.MESSAGES) { @@ -112,7 +112,7 @@ var AboutHome = { } }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { let window = aMessage.target.ownerGlobal; switch (aMessage.name) { @@ -160,7 +160,7 @@ var AboutHome = { // Send all the chrome-privileged data needed by about:home. This // gets re-sent when the search engine changes. - sendAboutHomeData: function(target) { + sendAboutHomeData(target) { let wrapper = {}; Components.utils.import("resource:///modules/sessionstore/SessionStore.jsm", wrapper); diff --git a/browser/modules/AboutNewTab.jsm b/browser/modules/AboutNewTab.jsm index 145cec09a71a..afb04ad499fb 100644 --- a/browser/modules/AboutNewTab.jsm +++ b/browser/modules/AboutNewTab.jsm @@ -22,17 +22,17 @@ var AboutNewTab = { pageListener: null, - init: function() { + init() { this.pageListener = new RemotePages("about:newtab"); this.pageListener.addMessageListener("NewTab:Customize", this.customize.bind(this)); }, - customize: function(message) { + customize(message) { NewTabUtils.allPages.enabled = message.data.enabled; NewTabUtils.allPages.enhanced = message.data.enhanced; }, - uninit: function() { + uninit() { this.pageListener.destroy(); this.pageListener = null; }, diff --git a/browser/modules/BrowserUITelemetry.jsm b/browser/modules/BrowserUITelemetry.jsm index 6e54d45df651..8f74aca423a8 100644 --- a/browser/modules/BrowserUITelemetry.jsm +++ b/browser/modules/BrowserUITelemetry.jsm @@ -170,7 +170,7 @@ const BUCKET_PREFIX = "bucket_"; const BUCKET_SEPARATOR = "|"; this.BrowserUITelemetry = { - init: function() { + init() { UITelemetry.addSimpleMeasureFunction("toolbars", this.getToolbarMeasures.bind(this)); UITelemetry.addSimpleMeasureFunction("contextmenu", @@ -189,7 +189,7 @@ this.BrowserUITelemetry = { CustomizableUI.addListener(this); }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "sessionstore-windows-restored": this._gatherFirstWindowMeasurements(); @@ -241,7 +241,7 @@ this.BrowserUITelemetry = { * @returns a reference to the second last object in the chain - * so in our example, that'd be "b". */ - _ensureObjectChain: function(aKeys, aEndWith, aRoot) { + _ensureObjectChain(aKeys, aEndWith, aRoot) { let current = aRoot; let parent = null; aKeys.unshift(this._bucket); @@ -260,13 +260,13 @@ this.BrowserUITelemetry = { }, _countableEvents: {}, - _countEvent: function(aKeyArray, root = this._countableEvents) { + _countEvent(aKeyArray, root = this._countableEvents) { let countObject = this._ensureObjectChain(aKeyArray, 0, root); let lastItemKey = aKeyArray[aKeyArray.length - 1]; countObject[lastItemKey]++; }, - _countMouseUpEvent: function(aCategory, aAction, aButton) { + _countMouseUpEvent(aCategory, aAction, aButton) { const BUTTONS = ["left", "middle", "right"]; let buttonKey = BUTTONS[aButton]; if (buttonKey) { @@ -275,7 +275,7 @@ this.BrowserUITelemetry = { }, _firstWindowMeasurements: null, - _gatherFirstWindowMeasurements: function() { + _gatherFirstWindowMeasurements() { // We'll gather measurements as soon as the session has restored. // We do this here instead of waiting for UITelemetry to ask for // our measurements because at that point all browser windows have @@ -295,7 +295,7 @@ this.BrowserUITelemetry = { }); }, - _registerWindow: function(aWindow) { + _registerWindow(aWindow) { aWindow.addEventListener("unload", this); let document = aWindow.document; @@ -323,7 +323,7 @@ this.BrowserUITelemetry = { WINDOW_DURATION_MAP.set(aWindow, {}); }, - _unregisterWindow: function(aWindow) { + _unregisterWindow(aWindow) { aWindow.removeEventListener("unload", this); let document = aWindow.document; @@ -349,7 +349,7 @@ this.BrowserUITelemetry = { } }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "unload": this._unregisterWindow(aEvent.currentTarget); @@ -363,7 +363,7 @@ this.BrowserUITelemetry = { } }, - _handleMouseUp: function(aEvent) { + _handleMouseUp(aEvent) { let targetID = aEvent.currentTarget.id; switch (targetID) { @@ -381,7 +381,7 @@ this.BrowserUITelemetry = { } }, - _handleMouseDown: function(aEvent) { + _handleMouseDown(aEvent) { if (aEvent.currentTarget.id == "PanelUI-menu-button") { // _countMouseUpEvent expects a detail for the second argument, // but we don't really have any details to give. Just passing in @@ -391,13 +391,13 @@ this.BrowserUITelemetry = { } }, - _PlacesChevronMouseUp: function(aEvent) { + _PlacesChevronMouseUp(aEvent) { let target = aEvent.originalTarget; let result = target.id == "PlacesChevron" ? "chevron" : "overflowed-item"; this._countMouseUpEvent("click-bookmarks-bar", result, aEvent.button); }, - _PlacesToolbarItemsMouseUp: function(aEvent) { + _PlacesToolbarItemsMouseUp(aEvent) { let target = aEvent.originalTarget; // If this isn't a bookmark-item, we don't care about it. if (!target.classList.contains("bookmark-item")) { @@ -408,14 +408,14 @@ this.BrowserUITelemetry = { this._countMouseUpEvent("click-bookmarks-bar", result, aEvent.button); }, - _menubarMouseUp: function(aEvent) { + _menubarMouseUp(aEvent) { let target = aEvent.originalTarget; let tag = target.localName let result = (tag == "menu" || tag == "menuitem") ? tag : "other"; this._countMouseUpEvent("click-menubar", result, aEvent.button); }, - _bookmarksMenuButtonMouseUp: function(aEvent) { + _bookmarksMenuButtonMouseUp(aEvent) { let bookmarksWidget = CustomizableUI.getWidget("bookmarks-menu-button"); if (bookmarksWidget.areaType == CustomizableUI.TYPE_MENU_PANEL) { // In the menu panel, only the star is visible, and that opens up the @@ -441,7 +441,7 @@ this.BrowserUITelemetry = { } }, - _checkForBuiltinItem: function(aEvent) { + _checkForBuiltinItem(aEvent) { let item = aEvent.originalTarget; // We don't want to count clicks on the private browsing @@ -482,7 +482,7 @@ this.BrowserUITelemetry = { } }, - _getWindowMeasurements: function(aWindow, searchResult) { + _getWindowMeasurements(aWindow, searchResult) { let document = aWindow.document; let result = {}; @@ -582,14 +582,14 @@ this.BrowserUITelemetry = { return result; }, - getToolbarMeasures: function() { + getToolbarMeasures() { let result = this._firstWindowMeasurements || {}; result.countableEvents = this._countableEvents; result.durations = this._durations; return result; }, - getSyncState: function() { + getSyncState() { let result = {}; for (let sub of ["desktop", "mobile"]) { let count = 0; @@ -601,11 +601,11 @@ this.BrowserUITelemetry = { return result; }, - countCustomizationEvent: function(aEventType) { + countCustomizationEvent(aEventType) { this._countEvent(["customize", aEventType]); }, - countSearchEvent: function(source, query, selection) { + countSearchEvent(source, query, selection) { this._countEvent(["search", source]); if ((/^[a-zA-Z]+:[^\/\\]/).test(query)) { this._countEvent(["search", "urlbar-keyword"]); @@ -615,35 +615,35 @@ this.BrowserUITelemetry = { } }, - countOneoffSearchEvent: function(id, type, where) { + countOneoffSearchEvent(id, type, where) { this._countEvent(["search-oneoff", id, type, where]); }, - countSearchSettingsEvent: function(source) { + countSearchSettingsEvent(source) { this._countEvent(["click-builtin-item", source, "search-settings"]); }, - countPanicEvent: function(timeId) { + countPanicEvent(timeId) { this._countEvent(["forget-button", timeId]); }, - countTabMutingEvent: function(action, reason) { + countTabMutingEvent(action, reason) { this._countEvent(["tab-audio-control", action, reason || "no reason given"]); }, - countSyncedTabEvent: function(what, where) { + countSyncedTabEvent(what, where) { // "what" will be, eg, "open" // "where" will be "toolbarbutton-subview" or "sidebar" this._countEvent(["synced-tabs", what, where]); }, - countSidebarEvent: function(sidebarID, action) { + countSidebarEvent(sidebarID, action) { // sidebarID is the ID of the sidebar (duh!) // action will be "hide" or "show" this._countEvent(["sidebar", sidebarID, action]); }, - _logAwesomeBarSearchResult: function(url) { + _logAwesomeBarSearchResult(url) { let spec = Services.search.parseSubmissionURL(url); if (spec.engine) { let matchedEngine = "default"; @@ -658,7 +658,7 @@ this.BrowserUITelemetry = { customization: [], }, - onCustomizeStart: function(aWindow) { + onCustomizeStart(aWindow) { this._countEvent(["customize", "start"]); let durationMap = WINDOW_DURATION_MAP.get(aWindow); if (!durationMap) { @@ -672,12 +672,12 @@ this.BrowserUITelemetry = { }; }, - onCustomizeEnd: function(aWindow) { + onCustomizeEnd(aWindow) { let durationMap = WINDOW_DURATION_MAP.get(aWindow); if (durationMap && "customization" in durationMap) { let duration = aWindow.performance.now() - durationMap.customization.start; this._durations.customization.push({ - duration: duration, + duration, bucket: durationMap.customization.bucket, }); delete durationMap.customization; @@ -720,7 +720,7 @@ this.BrowserUITelemetry = { _contextMenuInteractions: {}, - registerContextMenuInteraction: function(keys, itemID) { + registerContextMenuInteraction(keys, itemID) { if (itemID) { if (itemID == "openlinkprivate") { // Don't record anything, not even an other-item count @@ -738,7 +738,7 @@ this.BrowserUITelemetry = { this._countEvent(keys, this._contextMenuInteractions); }, - getContextMenuInfo: function() { + getContextMenuInfo() { return this._contextMenuInteractions; }, @@ -777,7 +777,7 @@ this.BrowserUITelemetry = { * * @param aName Name of bucket, or null for default bucket name (__DEFAULT__) */ - setBucket: function(aName) { + setBucket(aName) { if (this._bucketTimer) { Timer.clearTimeout(this._bucketTimer); this._bucketTimer = null; @@ -820,7 +820,7 @@ this.BrowserUITelemetry = { * timed as though they started expiring 300ms before * setExpiringBucket was called. */ - setExpiringBucket: function(aName, aTimeSteps, aTimeOffset = 0) { + setExpiringBucket(aName, aTimeSteps, aTimeOffset = 0) { if (aTimeSteps.length === 0) { this.setBucket(null); return; @@ -858,7 +858,7 @@ this.BrowserUITelemetry = { * * @return Minimal string representation. */ - _toTimeStr: function(aTimeMS) { + _toTimeStr(aTimeMS) { let timeStr = ""; function reduce(aUnitLength, aSymbol) { diff --git a/browser/modules/CastingApps.jsm b/browser/modules/CastingApps.jsm index 6f9be7c3ba5a..3d4f6f5b0941 100644 --- a/browser/modules/CastingApps.jsm +++ b/browser/modules/CastingApps.jsm @@ -12,17 +12,17 @@ Cu.import("resource://gre/modules/SimpleServiceDiscovery.jsm"); var CastingApps = { - _sendEventToVideo: function(element, data) { + _sendEventToVideo(element, data) { let event = element.ownerDocument.createEvent("CustomEvent"); event.initCustomEvent("media-videoCasting", false, true, JSON.stringify(data)); element.dispatchEvent(event); }, - makeURI: function(url, charset, baseURI) { + makeURI(url, charset, baseURI) { return Services.io.newURI(url, charset, baseURI); }, - getVideo: function(element) { + getVideo(element) { if (!element) { return null; } @@ -45,7 +45,7 @@ var CastingApps = { // Use the file extension to guess the mime type let sourceURI = this.makeURI(sourceURL, null, this.makeURI(element.baseURI)); if (this.allowableExtension(sourceURI, extensions)) { - return { element: element, source: sourceURI.spec, poster: posterURL, sourceURI: sourceURI}; + return { element, source: sourceURI.spec, poster: posterURL, sourceURI}; } } @@ -58,14 +58,14 @@ var CastingApps = { // Using the type attribute is our ideal way to guess the mime type. Otherwise, // fallback to using the file extension to guess the mime type if (this.allowableMimeType(sourceNode.type, types) || this.allowableExtension(sourceURI, extensions)) { - return { element: element, source: sourceURI.spec, poster: posterURL, sourceURI: sourceURI, type: sourceNode.type }; + return { element, source: sourceURI.spec, poster: posterURL, sourceURI, type: sourceNode.type }; } } return null; }, - sendVideoToService: function(videoElement, service) { + sendVideoToService(videoElement, service) { if (!service) return; @@ -101,9 +101,9 @@ var CastingApps = { } this.session = { - service: service, - app: app, - remoteMedia: remoteMedia, + service, + app, + remoteMedia, data: { title: video.title, source: video.source, @@ -116,7 +116,7 @@ var CastingApps = { }); }, - getServicesForVideo: function(videoElement) { + getServicesForVideo(videoElement) { let video = this.getVideo(videoElement); if (!video) { return {}; @@ -130,12 +130,12 @@ var CastingApps = { return filteredServices; }, - getServicesForMirroring: function() { + getServicesForMirroring() { return SimpleServiceDiscovery.services.filter(service => service.mirror); }, // RemoteMedia callback API methods - onRemoteMediaStart: function(remoteMedia) { + onRemoteMediaStart(remoteMedia) { if (!this.session) { return; } @@ -148,17 +148,17 @@ var CastingApps = { } }, - onRemoteMediaStop: function(remoteMedia) { + onRemoteMediaStop(remoteMedia) { }, - onRemoteMediaStatus: function(remoteMedia) { + onRemoteMediaStatus(remoteMedia) { }, - allowableExtension: function(uri, extensions) { + allowableExtension(uri, extensions) { return (uri instanceof Ci.nsIURL) && extensions.indexOf(uri.fileExtension) != -1; }, - allowableMimeType: function(type, types) { + allowableMimeType(type, types) { return types.indexOf(type) != -1; } }; diff --git a/browser/modules/ContentClick.jsm b/browser/modules/ContentClick.jsm index 997588bcd5ba..d2e0419054c4 100644 --- a/browser/modules/ContentClick.jsm +++ b/browser/modules/ContentClick.jsm @@ -16,12 +16,12 @@ Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); var ContentClick = { - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Content:Click", this); }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Content:Click": this.contentAreaClick(message.json, message.target) @@ -29,7 +29,7 @@ var ContentClick = { } }, - contentAreaClick: function(json, browser) { + contentAreaClick(json, browser) { // This is heavily based on contentAreaClick from browser.js (Bug 903016) // The json is set up in a way to look like an Event. let window = browser.ownerGlobal; diff --git a/browser/modules/ContentCrashHandlers.jsm b/browser/modules/ContentCrashHandlers.jsm index 18dd516391a6..dda1780ac1fc 100644 --- a/browser/modules/ContentCrashHandlers.jsm +++ b/browser/modules/ContentCrashHandlers.jsm @@ -55,7 +55,7 @@ this.TabCrashHandler = { return this.prefs = Services.prefs.getBranch("browser.tabs.crashReporting."); }, - init: function() { + init() { if (this.initialized) return; this.initialized = true; @@ -74,7 +74,7 @@ this.TabCrashHandler = { this.pageListener.addMessageListener("restoreAll", this.receiveMessage.bind(this)); }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "ipc:content-shutdown": { aSubject.QueryInterface(Ci.nsIPropertyBag2); @@ -140,7 +140,7 @@ this.TabCrashHandler = { } }, - receiveMessage: function(message) { + receiveMessage(message) { let browser = message.target.browser; let gBrowser = browser.ownerGlobal.gBrowser; let tab = gBrowser.getTabForBrowser(browser); @@ -400,7 +400,7 @@ this.TabCrashHandler = { this.removeSubmitCheckboxesForSameCrash(childID); }, - removeSubmitCheckboxesForSameCrash: function(childID) { + removeSubmitCheckboxesForSameCrash(childID) { let enumerator = Services.wm.getEnumerator("navigator:browser"); while (enumerator.hasMoreElements()) { let window = enumerator.getNext(); @@ -428,7 +428,7 @@ this.TabCrashHandler = { } }, - onAboutTabCrashedLoad: function(message) { + onAboutTabCrashedLoad(message) { this._crashedTabCount++; // Broadcast to all about:tabcrashed pages a count of @@ -834,7 +834,7 @@ this.UnsubmittedCrashHandler = { }, { label: gNavigatorBundle.GetStringFromName("pendingCrashReports.viewAll"), - callback: function() { + callback() { chromeWin.openUILinkIn("about:crashes", "tab"); return true; }, diff --git a/browser/modules/ContentLinkHandler.jsm b/browser/modules/ContentLinkHandler.jsm index 443cae2daf71..90e33470d0f5 100644 --- a/browser/modules/ContentLinkHandler.jsm +++ b/browser/modules/ContentLinkHandler.jsm @@ -27,7 +27,7 @@ const SIZES_TELEMETRY_ENUM = { }; this.ContentLinkHandler = { - init: function(chromeGlobal) { + init(chromeGlobal) { chromeGlobal.addEventListener("DOMLinkAdded", (event) => { this.onLinkEvent(event, chromeGlobal); }, false); @@ -36,7 +36,7 @@ this.ContentLinkHandler = { }, false); }, - onLinkEvent: function(event, chromeGlobal) { + onLinkEvent(event, chromeGlobal) { var link = event.originalTarget; var rel = link.rel && link.rel.toLowerCase(); if (!link || !link.ownerDocument || !rel || !link.href) @@ -124,7 +124,7 @@ this.ContentLinkHandler = { { let engine = { title: link.title, href: link.href }; chromeGlobal.sendAsyncMessage("Link:AddSearch", - {engine: engine, + {engine, url: link.ownerDocument.documentURI}); searchAdded = true; } @@ -134,7 +134,7 @@ this.ContentLinkHandler = { } }, - getLinkIconURI: function(aLink) { + getLinkIconURI(aLink) { let targetDoc = aLink.ownerDocument; var uri = BrowserUtils.makeURI(aLink.href, targetDoc.characterSet); try { diff --git a/browser/modules/ContentSearch.jsm b/browser/modules/ContentSearch.jsm index 42525702905c..a825cc698559 100644 --- a/browser/modules/ContentSearch.jsm +++ b/browser/modules/ContentSearch.jsm @@ -108,7 +108,7 @@ this.ContentSearch = { // fetch cancellation from _cancelSuggestions. _currentSuggestion: null, - init: function() { + init() { Cc["@mozilla.org/globalmessagemanager;1"]. getService(Ci.nsIMessageListenerManager). addMessageListener(INBOUND_MESSAGE, this); @@ -133,7 +133,7 @@ this.ContentSearch = { return this._searchSuggestionUIStrings; }, - destroy: function() { + destroy() { if (this._destroyedPromise) { return this._destroyedPromise; } @@ -154,13 +154,13 @@ this.ContentSearch = { * @param messageManager * The MessageManager object of the selected browser. */ - focusInput: function(messageManager) { + focusInput(messageManager) { messageManager.sendAsyncMessage(OUTBOUND_MESSAGE, { type: "FocusInput" }); }, - receiveMessage: function(msg) { + receiveMessage(msg) { // Add a temporary event handler that exists only while the message is in // the event queue. If the message's source docshell changes browsers in // the meantime, then we need to update msg.target. event.detail will be @@ -190,13 +190,13 @@ this.ContentSearch = { this._processEventQueue(); }, - observe: function(subj, topic, data) { + observe(subj, topic, data) { switch (topic) { case "nsPref:changed": case "browser-search-engine-modified": this._eventQueue.push({ type: "Observe", - data: data, + data, }); this._processEventQueue(); break; @@ -207,7 +207,7 @@ this.ContentSearch = { } }, - removeFormHistoryEntry: function(msg, entry) { + removeFormHistoryEntry(msg, entry) { let browserData = this._suggestionDataForBrowser(msg.target); if (browserData && browserData.previousFormHistoryResult) { let { previousFormHistoryResult } = browserData; @@ -220,7 +220,7 @@ this.ContentSearch = { } }, - performSearch: function(msg, data) { + performSearch(msg, data) { this._ensureDataHasProperties(data, [ "engineName", "searchString", @@ -273,7 +273,7 @@ this.ContentSearch = { let priv = PrivateBrowsingUtils.isBrowserPrivate(browser); // fetch() rejects its promise if there's a pending request, but since we // process our event queue serially, there's never a pending request. - this._currentSuggestion = { controller: controller, target: browser }; + this._currentSuggestion = { controller, target: browser }; let suggestions = yield controller.fetch(searchString, priv, engine); this._currentSuggestion = null; @@ -350,7 +350,7 @@ this.ContentSearch = { return state; }), - _processEventQueue: function() { + _processEventQueue() { if (this._currentEventPromise || !this._eventQueue.length) { return; } @@ -369,7 +369,7 @@ this.ContentSearch = { }.bind(this)); }, - _cancelSuggestions: function(msg) { + _cancelSuggestions(msg) { let cancelled = false; // cancel active suggestion request if (this._currentSuggestion && this._currentSuggestion.target === msg.target) { @@ -401,25 +401,25 @@ this.ContentSearch = { } }), - _onMessageGetState: function(msg, data) { + _onMessageGetState(msg, data) { return this.currentStateObj().then(state => { this._reply(msg, "State", state); }); }, - _onMessageGetStrings: function(msg, data) { + _onMessageGetStrings(msg, data) { this._reply(msg, "Strings", this.searchSuggestionUIStrings); }, - _onMessageSearch: function(msg, data) { + _onMessageSearch(msg, data) { this.performSearch(msg, data); }, - _onMessageSetCurrentEngine: function(msg, data) { + _onMessageSetCurrentEngine(msg, data) { Services.search.currentEngine = Services.search.getEngineByName(data); }, - _onMessageManageEngines: function(msg, data) { + _onMessageManageEngines(msg, data) { let browserWin = msg.target.ownerGlobal; browserWin.openPreferences("paneSearch"); }, @@ -444,11 +444,11 @@ this.ContentSearch = { yield this.addFormHistoryEntry(msg, entry); }), - _onMessageRemoveFormHistoryEntry: function(msg, entry) { + _onMessageRemoveFormHistoryEntry(msg, entry) { this.removeFormHistoryEntry(msg, entry); }, - _onMessageSpeculativeConnect: function(msg, engineName) { + _onMessageSpeculativeConnect(msg, engineName) { let engine = Services.search.getEngineByName(engineName); if (!engine) { throw new Error("Unknown engine name: " + engineName); @@ -473,7 +473,7 @@ this.ContentSearch = { } }), - _suggestionDataForBrowser: function(browser, create = false) { + _suggestionDataForBrowser(browser, create = false) { let data = this._suggestionMap.get(browser); if (!data && create) { // Since one SearchSuggestionController instance is meant to be used per @@ -487,7 +487,7 @@ this.ContentSearch = { return data; }, - _reply: function(msg, type, data) { + _reply(msg, type, data) { // We reply asyncly to messages, and by the time we reply the browser we're // responding to may have been destroyed. messageManager is null then. if (!Cu.isDeadWrapper(msg.target) && msg.target.messageManager) { @@ -495,16 +495,16 @@ this.ContentSearch = { } }, - _broadcast: function(type, data) { + _broadcast(type, data) { Cc["@mozilla.org/globalmessagemanager;1"]. getService(Ci.nsIMessageListenerManager). broadcastAsyncMessage(...this._msgArgs(type, data)); }, - _msgArgs: function(type, data) { + _msgArgs(type, data) { return [OUTBOUND_MESSAGE, { - type: type, - data: data, + type, + data, }]; }, @@ -515,13 +515,13 @@ this.ContentSearch = { "searchWithEngine", [engine.name], 1); let obj = { name: engine.name, - placeholder: placeholder, + placeholder, iconBuffer: yield this._arrayBufferFromDataURI(favicon), }; return obj; }), - _arrayBufferFromDataURI: function(uri) { + _arrayBufferFromDataURI(uri) { if (!uri) { return Promise.resolve(null); } @@ -546,7 +546,7 @@ this.ContentSearch = { return deferred.promise; }, - _ensureDataHasProperties: function(data, requiredProperties) { + _ensureDataHasProperties(data, requiredProperties) { for (let prop of requiredProperties) { if (!(prop in data)) { throw new Error("Message data missing required property: " + prop); @@ -554,7 +554,7 @@ this.ContentSearch = { } }, - _initService: function() { + _initService() { if (!this._initServicePromise) { let deferred = Promise.defer(); this._initServicePromise = deferred.promise; diff --git a/browser/modules/ContentWebRTC.jsm b/browser/modules/ContentWebRTC.jsm index 24c25a3b2b19..bc6930ea34ba 100644 --- a/browser/modules/ContentWebRTC.jsm +++ b/browser/modules/ContentWebRTC.jsm @@ -19,7 +19,7 @@ const kBrowserURL = "chrome://browser/content/browser.xul"; this.ContentWebRTC = { _initialized: false, - init: function() { + init() { if (this._initialized) return; @@ -33,7 +33,7 @@ this.ContentWebRTC = { Services.obs.addObserver(processShutdown, "content-child-shutdown", false); }, - uninit: function() { + uninit() { Services.obs.removeObserver(handleGUMRequest, "getUserMedia:request"); Services.obs.removeObserver(handlePCRequest, "PeerConnection:request"); Services.obs.removeObserver(updateIndicators, "recording-device-events"); @@ -46,7 +46,7 @@ this.ContentWebRTC = { }, // Called only for 'unload' to remove pending gUM prompts in reloaded frames. - handleEvent: function(aEvent) { + handleEvent(aEvent) { let contentWindow = aEvent.target.defaultView; let mm = getMessageManagerForWindow(contentWindow); for (let key of contentWindow.pendingGetUserMediaRequests.keys()) { @@ -57,7 +57,7 @@ this.ContentWebRTC = { } }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "rtcpeer:Allow": case "rtcpeer:Deny": { @@ -115,9 +115,9 @@ function handlePCRequest(aSubject, aTopic, aData) { contentWindow.pendingPeerConnectionRequests.add(callID); let request = { - windowID: windowID, - innerWindowID: innerWindowID, - callID: callID, + windowID, + innerWindowID, + callID, documentURI: contentWindow.document.documentURI, secure: isSecure, }; @@ -210,11 +210,11 @@ function prompt(aContentWindow, aWindowID, aCallID, aConstraints, aDevices, aSec windowID: aWindowID, documentURI: aContentWindow.document.documentURI, secure: aSecure, - requestTypes: requestTypes, - sharingScreen: sharingScreen, - sharingAudio: sharingAudio, - audioDevices: audioDevices, - videoDevices: videoDevices + requestTypes, + sharingScreen, + sharingAudio, + audioDevices, + videoDevices }; let mm = getMessageManagerForWindow(aContentWindow); diff --git a/browser/modules/DirectoryLinksProvider.jsm b/browser/modules/DirectoryLinksProvider.jsm index 9a15397a410f..2563436c553e 100644 --- a/browser/modules/DirectoryLinksProvider.jsm +++ b/browser/modules/DirectoryLinksProvider.jsm @@ -268,7 +268,7 @@ var DirectoryLinksProvider = { } }, - _cacheSuggestedLinks: function(link) { + _cacheSuggestedLinks(link) { // Don't cache links that don't have the expected 'frecent_sites' if (!link.frecent_sites) { return; @@ -729,7 +729,7 @@ var DirectoryLinksProvider = { }.bind(this)); }, - _handleManyLinksChanged: function() { + _handleManyLinksChanged() { this._topSitesWithSuggestedLinks.clear(); this._suggestedLinks.forEach((suggestedLinks, site) => { if (NewTabUtils.isTopPlacesSite(site)) { @@ -744,7 +744,7 @@ var DirectoryLinksProvider = { * * @return true if _topSitesWithSuggestedLinks was modified, false otherwise. */ - _handleLinkChanged: function(aLink) { + _handleLinkChanged(aLink) { let changedLinkSite = NewTabUtils.extractSite(aLink.url); let linkStored = this._topSitesWithSuggestedLinks.has(changedLinkSite); @@ -768,13 +768,13 @@ var DirectoryLinksProvider = { return false; }, - _populatePlacesLinks: function() { + _populatePlacesLinks() { NewTabUtils.links.populateProviderCache(NewTabUtils.placesProvider, () => { this._handleManyLinksChanged(); }); }, - onDeleteURI: function(aProvider, aLink) { + onDeleteURI(aProvider, aLink) { let {url} = aLink; // remove clicked flag for that url and // call observer upon disk write completion @@ -783,14 +783,14 @@ var DirectoryLinksProvider = { }); }, - onClearHistory: function() { + onClearHistory() { // remove all clicked flags and call observers upon file write this._removeAllTileClicks().then(() => { this._callObservers("onClearHistory"); }); }, - onLinkChanged: function(aProvider, aLink) { + onLinkChanged(aProvider, aLink) { // Make sure NewTabUtils.links handles the notification first. setTimeout(() => { if (this._handleLinkChanged(aLink) || this._shouldUpdateSuggestedTile()) { @@ -799,14 +799,14 @@ var DirectoryLinksProvider = { }, 0); }, - onManyLinksChanged: function() { + onManyLinksChanged() { // Make sure NewTabUtils.links handles the notification first. setTimeout(() => { this._handleManyLinksChanged(); }, 0); }, - _getCurrentTopSiteCount: function() { + _getCurrentTopSiteCount() { let visibleTopSiteCount = 0; let newTabLinks = NewTabUtils.links.getLinks(); for (let link of newTabLinks.slice(0, MIN_VISIBLE_HISTORY_TILES)) { @@ -822,7 +822,7 @@ var DirectoryLinksProvider = { return visibleTopSiteCount; }, - _shouldUpdateSuggestedTile: function() { + _shouldUpdateSuggestedTile() { let sortedLinks = NewTabUtils.getProviderLinks(this); let mostFrecentLink = {}; @@ -850,7 +850,7 @@ var DirectoryLinksProvider = { * * @return the chosen suggested tile, or undefined if there isn't one */ - _updateSuggestedTile: function() { + _updateSuggestedTile() { let sortedLinks = NewTabUtils.getProviderLinks(this); if (!sortedLinks) { @@ -1249,7 +1249,7 @@ var DirectoryLinksProvider = { } }, - _removeObservers: function() { + _removeObservers() { this._observers.clear(); } }; diff --git a/browser/modules/E10SUtils.jsm b/browser/modules/E10SUtils.jsm index fdfde0a157d0..5f6e9243d152 100644 --- a/browser/modules/E10SUtils.jsm +++ b/browser/modules/E10SUtils.jsm @@ -46,13 +46,13 @@ this.E10SUtils = { WEB_REMOTE_TYPE, FILE_REMOTE_TYPE, - canLoadURIInProcess: function(aURL, aProcess) { + canLoadURIInProcess(aURL, aProcess) { let remoteType = aProcess == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT ? DEFAULT_REMOTE_TYPE : NOT_REMOTE; return remoteType == this.getRemoteTypeForURI(aURL, true, remoteType); }, - getRemoteTypeForURI: function(aURL, aMultiProcess, + getRemoteTypeForURI(aURL, aMultiProcess, aPreferredRemoteType = DEFAULT_REMOTE_TYPE) { if (!aMultiProcess) { return NOT_REMOTE; @@ -143,12 +143,12 @@ this.E10SUtils = { return validatedWebRemoteType(aPreferredRemoteType); }, - shouldLoadURIInThisProcess: function(aURI) { + shouldLoadURIInThisProcess(aURI) { let remoteType = Services.appinfo.remoteType; return remoteType == this.getRemoteTypeForURI(aURI.spec, true, remoteType); }, - shouldLoadURI: function(aDocShell, aURI, aReferrer) { + shouldLoadURI(aDocShell, aURI, aReferrer) { // Inner frames should always load in the current process if (aDocShell.QueryInterface(Ci.nsIDocShellTreeItem).sameTypeParent) return true; @@ -157,7 +157,7 @@ this.E10SUtils = { return this.shouldLoadURIInThisProcess(aURI); }, - redirectLoad: function(aDocShell, aURI, aReferrer, aFreshProcess) { + redirectLoad(aDocShell, aURI, aReferrer, aFreshProcess) { // Retarget the load to the correct process let messageManager = aDocShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIContentFrameMessageManager); @@ -175,7 +175,7 @@ this.E10SUtils = { return false; }, - wrapHandlingUserInput: function(aWindow, aIsHandling, aCallback) { + wrapHandlingUserInput(aWindow, aIsHandling, aCallback) { var handlingUserInput; try { handlingUserInput = aWindow.QueryInterface(Ci.nsIInterfaceRequestor) diff --git a/browser/modules/Feeds.jsm b/browser/modules/Feeds.jsm index 179d2b83d23e..c9708488080a 100644 --- a/browser/modules/Feeds.jsm +++ b/browser/modules/Feeds.jsm @@ -72,7 +72,7 @@ this.Feeds = { * Whether this is already a known feed or not, if true only a security * check will be performed. */ - isValidFeed: function(aLink, aPrincipal, aIsFeed) { + isValidFeed(aLink, aPrincipal, aIsFeed) { if (!aLink || !aPrincipal) return false; diff --git a/browser/modules/FormSubmitObserver.jsm b/browser/modules/FormSubmitObserver.jsm index 7de3ab30de8a..01bd144739df 100644 --- a/browser/modules/FormSubmitObserver.jsm +++ b/browser/modules/FormSubmitObserver.jsm @@ -38,7 +38,7 @@ FormSubmitObserver.prototype = * Public apis */ - init: function(aWindow, aTabChildGlobal) + init(aWindow, aTabChildGlobal) { this._content = aWindow; this._tab = aTabChildGlobal; @@ -57,7 +57,7 @@ FormSubmitObserver.prototype = this._tab.addEventListener("unload", this, false); }, - uninit: function() + uninit() { Services.obs.removeObserver(this, "invalidformsubmit"); this._content.removeEventListener("pageshow", this, false); @@ -72,7 +72,7 @@ FormSubmitObserver.prototype = * Events */ - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "pageshow": if (this._isRootDocumentEvent(aEvent)) { @@ -95,7 +95,7 @@ FormSubmitObserver.prototype = * nsIFormSubmitObserver */ - notifyInvalidSubmit : function(aFormElement, aInvalidElements) + notifyInvalidSubmit(aFormElement, aInvalidElements) { // We are going to handle invalid form submission attempt by focusing the // first invalid element and show the corresponding validation message in a @@ -149,7 +149,7 @@ FormSubmitObserver.prototype = * with. Updates the validation message or closes the popup if form data * becomes valid. */ - _onInput: function(aEvent) { + _onInput(aEvent) { let element = aEvent.originalTarget; // If the form input is now valid, hide the popup. @@ -170,7 +170,7 @@ FormSubmitObserver.prototype = * Blur event handler in which we disconnect from the form element and * hide the popup. */ - _onBlur: function(aEvent) { + _onBlur(aEvent) { aEvent.originalTarget.removeEventListener("input", this, false); aEvent.originalTarget.removeEventListener("blur", this, false); this._element = null; @@ -182,7 +182,7 @@ FormSubmitObserver.prototype = * information. Can be called repetitively to update the currently * displayed popup position and text. */ - _showPopup: function(aElement) { + _showPopup(aElement) { // Collect positional information and show the popup let panelData = {}; @@ -214,15 +214,15 @@ FormSubmitObserver.prototype = this._mm.sendAsyncMessage("FormValidation:ShowPopup", panelData); }, - _hidePopup: function() { + _hidePopup() { this._mm.sendAsyncMessage("FormValidation:HidePopup", {}); }, - _getWindowUtils: function() { + _getWindowUtils() { return this._content.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); }, - _isRootDocumentEvent: function(aEvent) { + _isRootDocumentEvent(aEvent) { if (this._content == null) { return true; } diff --git a/browser/modules/FormValidationHandler.jsm b/browser/modules/FormValidationHandler.jsm index 62565af58d97..0193d644dfe6 100644 --- a/browser/modules/FormValidationHandler.jsm +++ b/browser/modules/FormValidationHandler.jsm @@ -25,13 +25,13 @@ var FormValidationHandler = * Public apis */ - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("FormValidation:ShowPopup", this); mm.addMessageListener("FormValidation:HidePopup", this); }, - uninit: function() { + uninit() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.removeMessageListener("FormValidation:ShowPopup", this); mm.removeMessageListener("FormValidation:HidePopup", this); @@ -39,7 +39,7 @@ var FormValidationHandler = this._anchor = null; }, - hidePopup: function() { + hidePopup() { this._hidePopup(); }, @@ -47,7 +47,7 @@ var FormValidationHandler = * Events */ - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { let window = aMessage.target.ownerGlobal; let json = aMessage.json; let tabBrowser = window.gBrowser; @@ -66,11 +66,11 @@ var FormValidationHandler = } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { this._hidePopup(); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "FullZoomChange": case "TextZoomChange": @@ -88,7 +88,7 @@ var FormValidationHandler = * Internal */ - _onPopupHiding: function(aEvent) { + _onPopupHiding(aEvent) { aEvent.originalTarget.removeEventListener("popuphiding", this, true); let tabBrowser = aEvent.originalTarget.ownerDocument.getElementById("content"); tabBrowser.selectedBrowser.removeEventListener("scroll", this, true); @@ -115,7 +115,7 @@ var FormValidationHandler = * position - popup positional string constants. * message - the form element validation message text. */ - _showPopup: function(aWindow, aPanelData) { + _showPopup(aWindow, aPanelData) { let previouslyShown = !!this._panel; this._panel = aWindow.document.getElementById("invalid-form-popup"); this._panel.firstChild.textContent = aPanelData.message; @@ -149,7 +149,7 @@ var FormValidationHandler = * Hide the popup if currently displayed. Will fire an event to onPopupHiding * above if visible. */ - _hidePopup: function() { + _hidePopup() { if (this._panel) { this._panel.hidePopup(); } diff --git a/browser/modules/HiddenFrame.jsm b/browser/modules/HiddenFrame.jsm index b5582bd97f37..207ffe9bf50e 100644 --- a/browser/modules/HiddenFrame.jsm +++ b/browser/modules/HiddenFrame.jsm @@ -39,7 +39,7 @@ HiddenFrame.prototype = { * @returns Promise Returns a promise which is resolved when the hidden frame has finished * loading. */ - get: function() { + get() { if (!this._deferred) { this._deferred = PromiseUtils.defer(); this._create(); @@ -48,7 +48,7 @@ HiddenFrame.prototype = { return this._deferred.promise; }, - destroy: function() { + destroy() { clearTimeout(this._retryTimerId); if (this._frame) { @@ -62,7 +62,7 @@ HiddenFrame.prototype = { } }, - handleEvent: function() { + handleEvent() { let contentWindow = this._frame.contentWindow; if (contentWindow.location.href === XUL_PAGE) { this._frame.removeEventListener("load", this, true); @@ -72,7 +72,7 @@ HiddenFrame.prototype = { } }, - _create: function() { + _create() { if (this.isReady) { let doc = this.hiddenDOMDocument; this._frame = doc.createElementNS(HTML_NS, "iframe"); diff --git a/browser/modules/NetworkPrioritizer.jsm b/browser/modules/NetworkPrioritizer.jsm index ef71d320dfb6..82cdc6dd03be 100644 --- a/browser/modules/NetworkPrioritizer.jsm +++ b/browser/modules/NetworkPrioritizer.jsm @@ -87,7 +87,7 @@ var BrowserHelper = { windowEntry.lastSelectedBrowser = aBrowser; }, - onRemotenessChange: function(aBrowser) { + onRemotenessChange(aBrowser) { aBrowser.setPriority(_priorityBackup.get(aBrowser.permanentKey)); }, diff --git a/browser/modules/PermissionUI.jsm b/browser/modules/PermissionUI.jsm index 19b4faaabdb8..e6d95ab437eb 100644 --- a/browser/modules/PermissionUI.jsm +++ b/browser/modules/PermissionUI.jsm @@ -481,7 +481,7 @@ GeolocationPermissionPrompt.prototype = { gBrowserBundle.GetStringFromName("geolocation.allowLocation.accesskey"), action: null, expireType: null, - callback: function(state) { + callback(state) { if (state && state.checkboxChecked) { secHistogram.add(ALWAYS_SHARE); } else { @@ -496,7 +496,7 @@ GeolocationPermissionPrompt.prototype = { expireType: PrivateBrowsingUtils.isWindowPrivate(this.browser.ownerGlobal) ? Ci.nsIPermissionManager.EXPIRE_SESSION : null, - callback: function(state) { + callback(state) { if (state && state.checkboxChecked) { secHistogram.add(NEVER_SHARE); } diff --git a/browser/modules/PluginContent.jsm b/browser/modules/PluginContent.jsm index 7c1139f6285a..c087576e842f 100644 --- a/browser/modules/PluginContent.jsm +++ b/browser/modules/PluginContent.jsm @@ -31,7 +31,7 @@ const FLASH_MIME_TYPE = "application/x-shockwave-flash"; const REPLACEMENT_STYLE_SHEET = Services.io.newURI("chrome://pluginproblem/content/pluginReplaceBinding.css", null, null); PluginContent.prototype = { - init: function(global) { + init(global) { this.global = global; // Need to hold onto the content window or else it'll get destroyed this.content = this.global.content; @@ -62,7 +62,7 @@ PluginContent.prototype = { Services.obs.addObserver(this, "decoder-doctor-notification", false); }, - uninit: function() { + uninit() { let global = this.global; global.removeEventListener("PluginBindingAttached", this, true); @@ -89,7 +89,7 @@ PluginContent.prototype = { delete this.content; }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "BrowserPlugins:ActivatePlugins": this.activatePlugins(msg.data.pluginInfo, msg.data.newState); @@ -143,7 +143,7 @@ PluginContent.prototype = { } }, - onPageShow: function(event) { + onPageShow(event) { // Ignore events that aren't from the main document. if (!this.content || event.target != this.content.document) { return; @@ -157,7 +157,7 @@ PluginContent.prototype = { } }, - onPageHide: function(event) { + onPageHide(event) { // Ignore events that aren't from the main document. if (!this.content || event.target != this.content.document) { return; @@ -168,12 +168,12 @@ PluginContent.prototype = { this.haveShownNotification = false; }, - getPluginUI: function(plugin, anonid) { + getPluginUI(plugin, anonid) { return plugin.ownerDocument. getAnonymousElementByAttribute(plugin, "anonid", anonid); }, - _getPluginInfo: function(pluginElement) { + _getPluginInfo(pluginElement) { if (pluginElement instanceof Ci.nsIDOMHTMLAnchorElement) { // Anchor elements are our place holders, and we only have them for Flash let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); @@ -223,11 +223,11 @@ PluginContent.prototype = { } return { mimetype: tagMimetype, - pluginName: pluginName, - pluginTag: pluginTag, - permissionString: permissionString, - fallbackType: fallbackType, - blocklistState: blocklistState, + pluginName, + pluginTag, + permissionString, + fallbackType, + blocklistState, }; }, @@ -237,7 +237,7 @@ PluginContent.prototype = { * nsIObjectLoadingContent. This only should happen if the plugin is * click-to-play (see bug 1186948). */ - _getPluginInfoForTag: function(pluginTag, tagMimetype) { + _getPluginInfoForTag(pluginTag, tagMimetype) { let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); let pluginName = gNavigatorBundle.GetStringFromName("pluginInfo.unknownPlugin"); @@ -268,22 +268,22 @@ PluginContent.prototype = { } return { mimetype: tagMimetype, - pluginName: pluginName, - pluginTag: pluginTag, - permissionString: permissionString, + pluginName, + pluginTag, + permissionString, // Since we should only have entered _getPluginInfoForTag when // examining a click-to-play plugin, we can safely hard-code // this fallback type, since we don't actually have an // nsIObjectLoadingContent to check. fallbackType: Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY, - blocklistState: blocklistState, + blocklistState, }; }, /** * Update the visibility of the plugin overlay. */ - setVisibility : function(plugin, overlay, shouldShow) { + setVisibility(plugin, overlay, shouldShow) { overlay.classList.toggle("visible", shouldShow); if (shouldShow) { overlay.removeAttribute("dismissed"); @@ -298,7 +298,7 @@ PluginContent.prototype = { * This function will handle showing or hiding the overlay. * @returns true if the plugin is invisible. */ - shouldShowOverlay : function(plugin, overlay) { + shouldShowOverlay(plugin, overlay) { // If the overlay size is 0, we haven't done layout yet. Presume that // plugins are visible until we know otherwise. if (overlay.scrollWidth == 0) { @@ -347,7 +347,7 @@ PluginContent.prototype = { return true; }, - addLinkClickCallback: function(linkNode, callbackName /* callbackArgs...*/) { + addLinkClickCallback(linkNode, callbackName /* callbackArgs...*/) { // XXX just doing (callback)(arg) was giving a same-origin error. bug? let self = this; let callbackArgs = Array.prototype.slice.call(arguments).slice(2); @@ -378,7 +378,7 @@ PluginContent.prototype = { }, // Helper to get the binding handler type from a plugin object - _getBindingType : function(plugin) { + _getBindingType(plugin) { if (!(plugin instanceof Ci.nsIObjectLoadingContent)) return null; @@ -403,7 +403,7 @@ PluginContent.prototype = { } }, - handleEvent: function(event) { + handleEvent(event) { let eventType = event.type; if (eventType == "unload") { @@ -583,7 +583,7 @@ PluginContent.prototype = { } }, - _recordFlashPluginTelemetry: function(eventType, plugin) { + _recordFlashPluginTelemetry(eventType, plugin) { if (!Services.telemetry.canRecordExtended) { return; } @@ -618,7 +618,7 @@ PluginContent.prototype = { } }, - _finishRecordingFlashPluginTelemetry: function() { + _finishRecordingFlashPluginTelemetry() { if (this.flashPluginStats) { Services.telemetry.getHistogramById('FLASH_PLUGIN_INSTANCES_ON_PAGE') .add(this.flashPluginStats.instancesCount); @@ -626,12 +626,12 @@ PluginContent.prototype = { } }, - isKnownPlugin: function(objLoadingContent) { + isKnownPlugin(objLoadingContent) { return (objLoadingContent.getContentTypeForMIMEType(objLoadingContent.actualType) == Ci.nsIObjectLoadingContent.TYPE_PLUGIN); }, - canActivatePlugin: function(objLoadingContent) { + canActivatePlugin(objLoadingContent) { // if this isn't a known plugin, we can't activate it // (this also guards pluginHost.getPermissionStringForType against // unexpected input) @@ -652,7 +652,7 @@ PluginContent.prototype = { isFallbackTypeValid; }, - hideClickToPlayOverlay: function(plugin) { + hideClickToPlayOverlay(plugin) { let overlay = this.getPluginUI(plugin, "main"); if (overlay) { overlay.classList.remove("visible"); @@ -660,7 +660,7 @@ PluginContent.prototype = { }, // Forward a link click callback to the chrome process. - forwardCallback: function(name, pluginTag) { + forwardCallback(name, pluginTag) { this.global.sendAsyncMessage("PluginContent:LinkClickCallback", { name, pluginTag }); }, @@ -692,12 +692,12 @@ PluginContent.prototype = { { runID, keyVals, submitURLOptIn }); }, - reloadPage: function() { + reloadPage() { this.global.content.location.reload(); }, // Event listener for click-to-play plugins. - _handleClickToPlayEvent: function(plugin) { + _handleClickToPlayEvent(plugin) { let doc = plugin.ownerDocument; let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); let permissionString; @@ -730,7 +730,7 @@ PluginContent.prototype = { } }, - onOverlayClick: function(event) { + onOverlayClick(event) { let document = event.target.ownerDocument; let plugin = document.getBindingParent(event.target); let contentWindow = plugin.ownerGlobal.top; @@ -747,7 +747,7 @@ PluginContent.prototype = { } }, - reshowClickToPlayNotification: function() { + reshowClickToPlayNotification() { let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -766,7 +766,7 @@ PluginContent.prototype = { /** * Activate the plugins that the user has specified. */ - activatePlugins: function(pluginInfo, newState) { + activatePlugins(pluginInfo, newState) { let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -812,7 +812,7 @@ PluginContent.prototype = { this.updateNotificationUI(); }, - _showClickToPlayNotification: function(plugin, showNow) { + _showClickToPlayNotification(plugin, showNow) { let plugins = []; // If plugin is null, that means the user has navigated back to a page with @@ -872,8 +872,8 @@ PluginContent.prototype = { this.global.sendAsyncMessage("PluginContent:ShowClickToPlayNotification", { plugins: [...this.pluginData.values()], - showNow: showNow, - location: location, + showNow, + location, }, null, principal); }, @@ -888,7 +888,7 @@ PluginContent.prototype = { * document). If this parameter is omitted, it defaults * to the current top-level document. */ - updateNotificationUI: function(document) { + updateNotificationUI(document) { document = document || this.content.document; // We're only interested in the top-level document, since that's @@ -953,23 +953,23 @@ PluginContent.prototype = { // If there are any items remaining in `actions` now, they are hidden // plugins that need a notification bar. this.global.sendAsyncMessage("PluginContent:UpdateHiddenPluginUI", { - haveInsecure: haveInsecure, + haveInsecure, actions: [...actions.values()], - location: location, + location, }, null, principal); }, - removeNotification: function(name) { - this.global.sendAsyncMessage("PluginContent:RemoveNotification", { name: name }); + removeNotification(name) { + this.global.sendAsyncMessage("PluginContent:RemoveNotification", { name }); }, - clearPluginCaches: function() { + clearPluginCaches() { this.pluginData.clear(); this.pluginCrashData.clear(); }, - hideNotificationBar: function(name) { - this.global.sendAsyncMessage("PluginContent:HideNotificationBar", { name: name }); + hideNotificationBar(name) { + this.global.sendAsyncMessage("PluginContent:HideNotificationBar", { name }); }, /** @@ -983,7 +983,7 @@ PluginContent.prototype = { * @returns bool * True if the plugin is a descendant of the full screen DOM element, false otherwise. **/ - isWithinFullScreenElement: function(fullScreenElement, domElement) { + isWithinFullScreenElement(fullScreenElement, domElement) { /** * Traverses down iframes until it find a non-iframe full screen DOM element. @@ -1018,7 +1018,7 @@ PluginContent.prototype = { * fired for both NPAPI and Gecko Media plugins. In the latter case, the * target of the event is the document that the GMP is being used in. */ - onPluginCrashed: function(target, aEvent) { + onPluginCrashed(target, aEvent) { if (!(aEvent instanceof this.content.PluginCrashedEvent)) return; @@ -1057,7 +1057,7 @@ PluginContent.prototype = { }); }, - NPAPIPluginProcessCrashed: function({pluginName, runID, state}) { + NPAPIPluginProcessCrashed({pluginName, runID, state}) { let message = gNavigatorBundle.formatStringFromName("crashedpluginsMessage.title", [pluginName], 1); @@ -1086,8 +1086,8 @@ PluginContent.prototype = { // WeakSet. Once the WeakSet is empty, we can clear the map. if (!this.pluginCrashData.has(runID)) { this.pluginCrashData.set(runID, { - state: state, - message: message, + state, + message, instances: new WeakSet(), }); } @@ -1098,7 +1098,7 @@ PluginContent.prototype = { } }, - setCrashedNPAPIPluginState: function({plugin, state, message}) { + setCrashedNPAPIPluginState({plugin, state, message}) { // Force a layout flush so the binding is attached. plugin.clientTop; let overlay = this.getPluginUI(plugin, "main"); @@ -1165,7 +1165,7 @@ PluginContent.prototype = { } }, - NPAPIPluginCrashReportSubmitted: function({ runID, state }) { + NPAPIPluginCrashReportSubmitted({ runID, state }) { this.pluginCrashData.delete(runID); let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -1181,7 +1181,7 @@ PluginContent.prototype = { } }, - GMPCrashed: function(aEvent) { + GMPCrashed(aEvent) { let target = aEvent.target; let pluginName = aEvent.pluginName; let gmpPlugin = aEvent.gmpPlugin; diff --git a/browser/modules/ProcessHangMonitor.jsm b/browser/modules/ProcessHangMonitor.jsm index 7c7c86b2c129..8f439f4335c6 100644 --- a/browser/modules/ProcessHangMonitor.jsm +++ b/browser/modules/ProcessHangMonitor.jsm @@ -49,7 +49,7 @@ var ProcessHangMonitor = { /** * Initialize hang reporting. Called once in the parent process. */ - init: function() { + init() { Services.obs.addObserver(this, "process-hang-report", false); Services.obs.addObserver(this, "clear-hang-report", false); Services.obs.addObserver(this, "xpcom-shutdown", false); @@ -60,7 +60,7 @@ var ProcessHangMonitor = { * Terminate JavaScript associated with the hang being reported for * the selected browser in |win|. */ - terminateScript: function(win) { + terminateScript(win) { this.handleUserInput(win, report => report.terminateScript()); }, @@ -68,7 +68,7 @@ var ProcessHangMonitor = { * Start devtools debugger for JavaScript associated with the hang * being reported for the selected browser in |win|. */ - debugScript: function(win) { + debugScript(win) { this.handleUserInput(win, report => { function callback() { report.endStartingDebugger(); @@ -87,7 +87,7 @@ var ProcessHangMonitor = { * for the selected browser in |win|. Will attempt to generate a combined * crash report for all processes. */ - terminatePlugin: function(win) { + terminatePlugin(win) { this.handleUserInput(win, report => report.terminatePlugin()); }, @@ -95,7 +95,7 @@ var ProcessHangMonitor = { * Dismiss the browser notification and invoke an appropriate action based on * the hang type. */ - stopIt: function(win) { + stopIt(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return; @@ -115,7 +115,7 @@ var ProcessHangMonitor = { * Dismiss the notification, clear the report from the active list and set up * a new timer to track a wait period during which we won't notify. */ - waitLonger: function(win) { + waitLonger(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return; @@ -155,7 +155,7 @@ var ProcessHangMonitor = { * |win|, invoke |func| on that report and stop notifying the user * about it. */ - handleUserInput: function(win, func) { + handleUserInput(win, func) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return null; @@ -165,7 +165,7 @@ var ProcessHangMonitor = { return func(report); }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "xpcom-shutdown": Services.obs.removeObserver(this, "xpcom-shutdown"); @@ -198,7 +198,7 @@ var ProcessHangMonitor = { /** * Find a active hang report for the given element. */ - findActiveReport: function(browser) { + findActiveReport(browser) { let frameLoader = browser.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader; for (let report of this._activeReports) { if (report.isReportForBrowser(frameLoader)) { @@ -211,7 +211,7 @@ var ProcessHangMonitor = { /** * Find a paused hang report for the given element. */ - findPausedReport: function(browser) { + findPausedReport(browser) { let frameLoader = browser.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader; for (let [report, ] of this._pausedReports) { if (report.isReportForBrowser(frameLoader)) { @@ -225,7 +225,7 @@ var ProcessHangMonitor = { * Remove an active hang report from the active list and cancel the timer * associated with it. */ - removeActiveReport: function(report) { + removeActiveReport(report) { this._activeReports.delete(report); this.updateWindows(); }, @@ -234,7 +234,7 @@ var ProcessHangMonitor = { * Remove a paused hang report from the paused list and cancel the timer * associated with it. */ - removePausedReport: function(report) { + removePausedReport(report) { let timer = this._pausedReports.get(report); if (timer) { timer.cancel(); @@ -248,7 +248,7 @@ var ProcessHangMonitor = { * each window to watch for events that would cause a different hang * report to be displayed. */ - updateWindows: function() { + updateWindows() { let e = Services.wm.getEnumerator("navigator:browser"); while (e.hasMoreElements()) { let win = e.getNext(); @@ -267,7 +267,7 @@ var ProcessHangMonitor = { /** * If there is a hang report for the current tab in |win|, display it. */ - updateWindow: function(win) { + updateWindow(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (report) { @@ -280,7 +280,7 @@ var ProcessHangMonitor = { /** * Show the notification for a hang. */ - showNotification: function(win, report) { + showNotification(win, report) { let nb = win.document.getElementById("high-priority-global-notificationbox"); let notification = nb.getNotificationWithValue("process-hang"); if (notification) { @@ -292,14 +292,14 @@ var ProcessHangMonitor = { let buttons = [{ label: bundle.getString("processHang.button_stop.label"), accessKey: bundle.getString("processHang.button_stop.accessKey"), - callback: function() { + callback() { ProcessHangMonitor.stopIt(win); } }, { label: bundle.getString("processHang.button_wait.label"), accessKey: bundle.getString("processHang.button_wait.accessKey"), - callback: function() { + callback() { ProcessHangMonitor.waitLonger(win); } }]; @@ -308,7 +308,7 @@ var ProcessHangMonitor = { buttons.push({ label: bundle.getString("processHang.button_debug.label"), accessKey: bundle.getString("processHang.button_debug.accessKey"), - callback: function() { + callback() { ProcessHangMonitor.debugScript(win); } }); @@ -323,7 +323,7 @@ var ProcessHangMonitor = { /** * Ensure that no hang notifications are visible in |win|. */ - hideNotification: function(win) { + hideNotification(win) { let nb = win.document.getElementById("high-priority-global-notificationbox"); let notification = nb.getNotificationWithValue("process-hang"); if (notification) { @@ -335,17 +335,17 @@ var ProcessHangMonitor = { * Install event handlers on |win| to watch for events that would * cause a different hang report to be displayed. */ - trackWindow: function(win) { + trackWindow(win) { win.gBrowser.tabContainer.addEventListener("TabSelect", this, true); win.gBrowser.tabContainer.addEventListener("TabRemotenessChange", this, true); }, - untrackWindow: function(win) { + untrackWindow(win) { win.gBrowser.tabContainer.removeEventListener("TabSelect", this, true); win.gBrowser.tabContainer.removeEventListener("TabRemotenessChange", this, true); }, - handleEvent: function(event) { + handleEvent(event) { let win = event.target.ownerGlobal; // If a new tab is selected or if a tab changes remoteness, then @@ -360,7 +360,7 @@ var ProcessHangMonitor = { * Handle a potentially new hang report. If it hasn't been seen * before, show a notification for it in all open XUL windows. */ - reportHang: function(report) { + reportHang(report) { // If this hang was already reported reset the timer for it. if (this._activeReports.has(report)) { // if this report is in active but doesn't have a notification associated @@ -389,7 +389,7 @@ var ProcessHangMonitor = { this.updateWindows(); }, - clearHang: function(report) { + clearHang(report) { this.removeActiveReport(report); this.removePausedReport(report); report.userCanceled(); diff --git a/browser/modules/ReaderParent.jsm b/browser/modules/ReaderParent.jsm index 6fcaada42685..8b59ac5d15a9 100644 --- a/browser/modules/ReaderParent.jsm +++ b/browser/modules/ReaderParent.jsm @@ -28,20 +28,20 @@ var ReaderParent = { "Reader:UpdateReaderButton", ], - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); for (let msg of this.MESSAGES) { mm.addMessageListener(msg, this); } }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Reader:ArticleGet": this._getArticle(message.data.url, message.target).then((article) => { // Make sure the target browser is still alive before trying to send data back. if (message.target.messageManager) { - message.target.messageManager.sendAsyncMessage("Reader:ArticleData", { article: article }); + message.target.messageManager.sendAsyncMessage("Reader:ArticleData", { article }); } }, e => { if (e && e.newURL) { @@ -80,7 +80,7 @@ var ReaderParent = { } }, - updateReaderButton: function(browser) { + updateReaderButton(browser) { let win = browser.ownerGlobal; if (browser != win.gBrowser.selectedBrowser) { return; @@ -124,7 +124,7 @@ var ReaderParent = { } }, - forceShowReaderIcon: function(browser) { + forceShowReaderIcon(browser) { browser.isArticle = true; this.updateReaderButton(browser); }, @@ -136,7 +136,7 @@ var ReaderParent = { this.toggleReaderMode(event); }, - toggleReaderMode: function(event) { + toggleReaderMode(event) { let win = event.target.ownerGlobal; let browser = win.gBrowser.selectedBrowser; browser.messageManager.sendAsyncMessage("Reader:ToggleReaderMode"); diff --git a/browser/modules/RemotePrompt.jsm b/browser/modules/RemotePrompt.jsm index da4945c2eb8d..9dde55b8f6dd 100644 --- a/browser/modules/RemotePrompt.jsm +++ b/browser/modules/RemotePrompt.jsm @@ -17,12 +17,12 @@ Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/SharedPromptUtils.jsm"); var RemotePrompt = { - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Prompt:Open", this); }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Prompt:Open": if (message.data.uri) { @@ -34,7 +34,7 @@ var RemotePrompt = { } }, - openTabPrompt: function(args, browser) { + openTabPrompt(args, browser) { let window = browser.ownerGlobal; let tabPrompt = window.gBrowser.getTabModalPromptBox(browser) let newPrompt; @@ -92,7 +92,7 @@ var RemotePrompt = { } }, - openModalWindow: function(args, browser) { + openModalWindow(args, browser) { let window = browser.ownerGlobal; try { PromptUtils.fireDialogEvent(window, "DOMWillOpenModalDialog", browser); diff --git a/browser/modules/SelfSupportBackend.jsm b/browser/modules/SelfSupportBackend.jsm index d25b4a74fbd6..d8fbb71dca54 100644 --- a/browser/modules/SelfSupportBackend.jsm +++ b/browser/modules/SelfSupportBackend.jsm @@ -53,11 +53,11 @@ const IS_UNIFIED_TELEMETRY = Preferences.get(PREF_TELEMETRY_UNIFIED, false); var gLogAppenderDump = null; this.SelfSupportBackend = Object.freeze({ - init: function() { + init() { SelfSupportBackendInternal.init(); }, - uninit: function() { + uninit() { SelfSupportBackendInternal.uninit(); }, }); @@ -75,7 +75,7 @@ var SelfSupportBackendInternal = { /** * Initializes the self support backend. */ - init: function() { + init() { this._configureLogging(); this._log.trace("init"); @@ -108,7 +108,7 @@ var SelfSupportBackendInternal = { /** * Shut down the self support backend, if active. */ - uninit: function() { + uninit() { this._log.trace("uninit"); Preferences.ignore(PREF_BRANCH_LOG, this._configureLogging, this); @@ -142,7 +142,7 @@ var SelfSupportBackendInternal = { * Handle notifications. Once all windows are created, we wait a little bit more * since tabs might still be loading. Then, we open the self support. */ - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { this._log.trace("observe - Topic " + aTopic); if (aTopic === "sessionstore-windows-restored") { @@ -154,7 +154,7 @@ var SelfSupportBackendInternal = { /** * Configure the logger based on the preferences. */ - _configureLogging: function() { + _configureLogging() { if (!this._log) { this._log = Log.repository.getLogger(LOGGER_NAME); @@ -183,7 +183,7 @@ var SelfSupportBackendInternal = { * Create an hidden frame to host our |browser|, then load the SelfSupport page in it. * @param aURL The URL to load in the browser. */ - _makeHiddenBrowser: function(aURL) { + _makeHiddenBrowser(aURL) { this._frame = new HiddenFrame(); return this._frame.get().then(aFrame => { let doc = aFrame.document; @@ -197,7 +197,7 @@ var SelfSupportBackendInternal = { }); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { this._log.trace("handleEvent - aEvent.type " + aEvent.type + ", Trusted " + aEvent.isTrusted); if (aEvent.type === "DOMWindowClose") { @@ -217,7 +217,7 @@ var SelfSupportBackendInternal = { /** * Called when the self support page correctly loads. */ - _pageSuccessCallback: function() { + _pageSuccessCallback() { this._log.debug("_pageSuccessCallback - Page correctly loaded."); this._browser.removeProgressListener(this._progressListener); this._progressListener.destroy(); @@ -230,7 +230,7 @@ var SelfSupportBackendInternal = { /** * Called when the self support page fails to load. */ - _pageLoadErrorCallback: function() { + _pageLoadErrorCallback() { this._log.info("_pageLoadErrorCallback - Too many failed load attempts. Giving up."); this.uninit(); }, @@ -240,7 +240,7 @@ var SelfSupportBackendInternal = { * self support page and attempt to load the page content. If loading fails, try again * after an interval. */ - _loadSelfSupport: function() { + _loadSelfSupport() { // Fetch the Self Support URL from the preferences. let unformattedURL = Preferences.get(PREF_URL, null); let url = Services.urlFormatter.formatURL(unformattedURL); @@ -290,7 +290,7 @@ function ProgressListener(aLoadErrorCallback, aLoadSuccessCallback) { } ProgressListener.prototype = { - onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { if (aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) { this._log.warn("onLocationChange - There was a problem fetching the SelfSupport URL (attempt " + this._loadAttempts + ")."); @@ -312,7 +312,7 @@ ProgressListener.prototype = { } }, - onStateChange: function(aWebProgress, aRequest, aFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aFlags, aStatus) { if (aFlags & Ci.nsIWebProgressListener.STATE_STOP && aFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK && aFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW && @@ -321,7 +321,7 @@ ProgressListener.prototype = { } }, - destroy: function() { + destroy() { // Make sure we don't try to reload self support when shutting down. clearTimeout(this._reloadTimerId); }, diff --git a/browser/modules/SitePermissions.jsm b/browser/modules/SitePermissions.jsm index 38fd1ab93b61..c384a22cfa63 100644 --- a/browser/modules/SitePermissions.jsm +++ b/browser/modules/SitePermissions.jsm @@ -27,7 +27,7 @@ this.SitePermissions = { * * install addon permission is excluded, check bug 1303108 */ - getAllByURI: function(aURI) { + getAllByURI(aURI) { let result = []; if (!this.isSupportedURI(aURI)) { return result; @@ -64,7 +64,7 @@ this.SitePermissions = { * - id: the state constant * - label: the translated label of that state */ - getPermissionItem: function(aId, aState) { + getPermissionItem(aId, aState) { let availableStates = this.getAvailableStates(aId).map(state => { return { id: state, label: this.getStateLabel(aId, state) }; }); @@ -77,7 +77,7 @@ this.SitePermissions = { /* Returns a list of objects representing all permissions that are currently * set for the given URI. See getPermissionItem for the content of each object. */ - getPermissionDetailsByURI: function(aURI) { + getPermissionDetailsByURI(aURI) { let permissions = []; for (let {state, id} of this.getAllByURI(aURI)) { permissions.push(this.getPermissionItem(id, state)); @@ -90,20 +90,20 @@ this.SitePermissions = { * URI. This excludes file URIs, for instance, as they don't have a host, * even though nsIPermissionManager can still handle them. */ - isSupportedURI: function(aURI) { + isSupportedURI(aURI) { return aURI.schemeIs("http") || aURI.schemeIs("https"); }, /* Returns an array of all permission IDs. */ - listPermissions: function() { + listPermissions() { return Object.keys(gPermissionObject); }, /* Returns an array of permission states to be exposed to the user for a * permission with the given ID. */ - getAvailableStates: function(aPermissionID) { + getAvailableStates(aPermissionID) { if (aPermissionID in gPermissionObject && gPermissionObject[aPermissionID].states) return gPermissionObject[aPermissionID].states; @@ -116,7 +116,7 @@ this.SitePermissions = { /* Returns the default state of a particular permission. */ - getDefault: function(aPermissionID) { + getDefault(aPermissionID) { if (aPermissionID in gPermissionObject && gPermissionObject[aPermissionID].getDefault) return gPermissionObject[aPermissionID].getDefault(); @@ -126,7 +126,7 @@ this.SitePermissions = { /* Returns the state of a particular permission for a given URI. */ - get: function(aURI, aPermissionID) { + get(aURI, aPermissionID) { if (!this.isSupportedURI(aURI)) return this.UNKNOWN; @@ -141,7 +141,7 @@ this.SitePermissions = { /* Sets the state of a particular permission for a given URI. */ - set: function(aURI, aPermissionID, aState) { + set(aURI, aPermissionID, aState) { if (!this.isSupportedURI(aURI)) return; @@ -155,7 +155,7 @@ this.SitePermissions = { /* Removes the saved state of a particular permission for a given URI. */ - remove: function(aURI, aPermissionID) { + remove(aURI, aPermissionID) { if (!this.isSupportedURI(aURI)) return; @@ -165,7 +165,7 @@ this.SitePermissions = { /* Returns the localized label for the permission with the given ID, to be * used in a UI for managing permissions. */ - getPermissionLabel: function(aPermissionID) { + getPermissionLabel(aPermissionID) { let labelID = gPermissionObject[aPermissionID].labelID || aPermissionID; return gStringBundle.GetStringFromName("permission." + labelID + ".label"); }, @@ -173,7 +173,7 @@ this.SitePermissions = { /* Returns the localized label for the given permission state, to be used in * a UI for managing permissions. */ - getStateLabel: function(aPermissionID, aState, aInUse = false) { + getStateLabel(aPermissionID, aState, aInUse = false) { switch (aState) { case this.UNKNOWN: if (aInUse) @@ -215,7 +215,7 @@ var gPermissionObject = { */ "image": { - getDefault: function() { + getDefault() { return Services.prefs.getIntPref("permissions.default.image") == 2 ? SitePermissions.BLOCK : SitePermissions.ALLOW; } @@ -223,7 +223,7 @@ var gPermissionObject = { "cookie": { states: [ SitePermissions.ALLOW, SitePermissions.SESSION, SitePermissions.BLOCK ], - getDefault: function() { + getDefault() { if (Services.prefs.getIntPref("network.cookie.cookieBehavior") == 2) return SitePermissions.BLOCK; @@ -246,14 +246,14 @@ var gPermissionObject = { }, "popup": { - getDefault: function() { + getDefault() { return Services.prefs.getBoolPref("dom.disable_open_during_load") ? SitePermissions.BLOCK : SitePermissions.ALLOW; } }, "install": { - getDefault: function() { + getDefault() { return Services.prefs.getBoolPref("xpinstall.whitelist.required") ? SitePermissions.BLOCK : SitePermissions.ALLOW; } diff --git a/browser/modules/Social.jsm b/browser/modules/Social.jsm index 25e9a6f41614..510c2d4acf4d 100644 --- a/browser/modules/Social.jsm +++ b/browser/modules/Social.jsm @@ -92,14 +92,14 @@ this.Social = { return deferred.promise; }, - _updateEnabledState: function(enable) { + _updateEnabledState(enable) { for (let p of Social.providers) { p.enabled = enable; } }, // Called to update our cache of providers and set the current provider - _updateProviderCache: function(providers) { + _updateProviderCache(providers) { this.providers = providers; Services.obs.notifyObservers(null, "social:providers-changed", null); }, @@ -108,7 +108,7 @@ this.Social = { return !this._disabledForSafeMode && this.providers.length > 0; }, - _getProviderFromOrigin: function(origin) { + _getProviderFromOrigin(origin) { for (let p of this.providers) { if (p.origin == origin) { return p; @@ -117,20 +117,20 @@ this.Social = { return null; }, - getManifestByOrigin: function(origin) { + getManifestByOrigin(origin) { return SocialService.getManifestByOrigin(origin); }, - installProvider: function(data, installCallback, options = {}) { + installProvider(data, installCallback, options = {}) { SocialService.installProvider(data, installCallback, options); }, - uninstallProvider: function(origin, aCallback) { + uninstallProvider(origin, aCallback) { SocialService.uninstallProvider(origin, aCallback); }, // Activation functionality - activateFromOrigin: function(origin, callback) { + activateFromOrigin(origin, callback) { // It's OK if the provider has already been activated - we still get called // back with it. SocialService.enableProvider(origin, callback); @@ -225,7 +225,7 @@ DynamicResizeWatcher.prototype = { this.OpenGraphBuilder = { - generateEndpointURL: function(URLTemplate, pageData) { + generateEndpointURL(URLTemplate, pageData) { // support for existing oexchange style endpoints by supporting their // querystring arguments. parse the query string template and do // replacements where necessary the query names may be different than ours, diff --git a/browser/modules/SocialService.jsm b/browser/modules/SocialService.jsm index 2cc4255d1f00..c1dfce37fc20 100644 --- a/browser/modules/SocialService.jsm +++ b/browser/modules/SocialService.jsm @@ -58,7 +58,7 @@ var SocialServiceInternal = { get manifests() { return this.manifestsGenerator(); }, - getManifestPrefname: function(origin) { + getManifestPrefname(origin) { // Retrieve the prefname for a given origin/manifest. // If no existing pref, return a generated prefname. let MANIFEST_PREFS = Services.prefs.getBranch("social.manifest."); @@ -77,7 +77,7 @@ var SocialServiceInternal = { let originUri = Services.io.newURI(origin, null, null); return originUri.hostPort.replace('.', '-'); }, - orderedProviders: function(aCallback) { + orderedProviders(aCallback) { if (SocialServiceInternal.providerArray.length < 2) { schedule(function() { aCallback(SocialServiceInternal.providerArray); @@ -106,7 +106,7 @@ var SocialServiceInternal = { try { stmt.executeAsync({ - handleResult: function(aResultSet) { + handleResult(aResultSet) { let row; while ((row = aResultSet.getNextRow())) { let rh = row.getResultByName("host"); @@ -114,10 +114,10 @@ var SocialServiceInternal = { providers[rh].frecency = parseInt(frecency) || 0; } }, - handleError: function(aError) { + handleError(aError) { Cu.reportError(aError.message + " (Result = " + aError.result + ")"); }, - handleCompletion: function(aReason) { + handleCompletion(aReason) { // the query may not have returned all our providers, so we have // stamped the frecency on the provider and sort here. This makes sure // all enabled providers get sorted even with frecency zero. @@ -177,21 +177,21 @@ var ActiveProviders = { return this._providers; }, - has: function(origin) { + has(origin) { return (origin in this._providers); }, - add: function(origin) { + add(origin) { this._providers[origin] = 1; this._deferredTask.arm(); }, - delete: function(origin) { + delete(origin) { delete this._providers[origin]; this._deferredTask.arm(); }, - flush: function() { + flush() { this._deferredTask.disarm(); this._persist(); }, @@ -201,7 +201,7 @@ var ActiveProviders = { return this._deferredTask = new DeferredTask(this._persist.bind(this), 0); }, - _persist: function() { + _persist() { let string = Cc["@mozilla.org/supports-string;1"]. createInstance(Ci.nsISupportsString); string.data = JSON.stringify(this._providers); @@ -454,13 +454,13 @@ this.SocialService = { }, // Returns an unordered array of installed providers - getProviderList: function(onDone) { + getProviderList(onDone) { schedule(function() { onDone(SocialServiceInternal.providerArray); }); }, - getManifestByOrigin: function(origin) { + getManifestByOrigin(origin) { for (let manifest of SocialServiceInternal.manifests) { if (origin == manifest.origin) { return manifest; @@ -470,11 +470,11 @@ this.SocialService = { }, // Returns an array of installed providers, sorted by frecency - getOrderedProviderList: function(onDone) { + getOrderedProviderList(onDone) { SocialServiceInternal.orderedProviders(onDone); }, - getOriginActivationType: function(origin) { + getOriginActivationType(origin) { return getOriginActivationType(origin); }, @@ -486,7 +486,7 @@ this.SocialService = { this._providerListeners.delete(listener); }, - _notifyProviderListeners: function(topic, origin, providers) { + _notifyProviderListeners(topic, origin, providers) { for (let [listener, ] of this._providerListeners) { try { listener(topic, origin, providers); @@ -496,7 +496,7 @@ this.SocialService = { } }, - _manifestFromData: function(type, data, installOrigin) { + _manifestFromData(type, data, installOrigin) { let featureURLs = ['shareURL']; let resolveURLs = featureURLs.concat(['postActivationURL']); @@ -541,7 +541,7 @@ this.SocialService = { return data; }, - _showInstallNotification: function(data, aAddonInstaller) { + _showInstallNotification(data, aAddonInstaller) { let brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties"); let browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties"); @@ -560,7 +560,7 @@ this.SocialService = { let action = { label: browserBundle.GetStringFromName("service.install.ok.label"), accessKey: browserBundle.GetStringFromName("service.install.ok.accesskey"), - callback: function() { + callback() { aAddonInstaller.install(); }, }; @@ -576,7 +576,7 @@ this.SocialService = { action, [], options); }, - installProvider: function(data, installCallback, options = {}) { + installProvider(data, installCallback, options = {}) { data.installType = getOriginActivationType(data.origin); // if we get data, we MUST have a valid manifest generated from the data let manifest = this._manifestFromData(data.installType, data.manifest, data.origin); @@ -611,7 +611,7 @@ this.SocialService = { }.bind(this)); }, - _installProvider: function(data, options, installCallback) { + _installProvider(data, options, installCallback) { if (!data.manifest) throw new Error("Cannot install provider without manifest data"); @@ -633,7 +633,7 @@ this.SocialService = { this._showInstallNotification(data, installer); }, - createWrapper: function(manifest) { + createWrapper(manifest) { return new AddonWrapper(manifest); }, @@ -642,7 +642,7 @@ this.SocialService = { * have knowledge of the currently selected provider here, we will notify * the front end to deal with any reload. */ - updateProvider: function(aUpdateOrigin, aManifest) { + updateProvider(aUpdateOrigin, aManifest) { let installType = this.getOriginActivationType(aUpdateOrigin); // if we get data, we MUST have a valid manifest generated from the data let manifest = this._manifestFromData(installType, aManifest, aUpdateOrigin); @@ -670,7 +670,7 @@ this.SocialService = { }, - uninstallProvider: function(origin, aCallback) { + uninstallProvider(origin, aCallback) { let manifest = SocialService.getManifestByOrigin(origin); let addon = new AddonWrapper(manifest); addon.uninstall(aCallback); @@ -716,7 +716,7 @@ function SocialProvider(input) { } SocialProvider.prototype = { - reload: function() { + reload() { // calling terminate/activate does not set the enabled state whereas setting // enabled will call terminate/activate this.enabled = false; @@ -747,7 +747,7 @@ SocialProvider.prototype = { return SocialService.getManifestByOrigin(this.origin); }, - getPageSize: function(name) { + getPageSize(name) { let manifest = this.manifest; if (manifest && manifest.pageSize) return manifest.pageSize[name]; @@ -854,11 +854,11 @@ function AddonInstaller(sourceURI, aManifest, installCallback) { } var SocialAddonProvider = { - startup: function() {}, + startup() {}, - shutdown: function() {}, + shutdown() {}, - updateAddonAppDisabledStates: function() { + updateAddonAppDisabledStates() { // we wont bother with "enabling" services that are released from blocklist for (let manifest of SocialServiceInternal.manifests) { try { @@ -874,7 +874,7 @@ var SocialAddonProvider = { } }, - getAddonByID: function(aId, aCallback) { + getAddonByID(aId, aCallback) { for (let manifest of SocialServiceInternal.manifests) { if (aId == getAddonIDFromOrigin(manifest.origin)) { aCallback(new AddonWrapper(manifest)); @@ -884,7 +884,7 @@ var SocialAddonProvider = { aCallback(null); }, - getAddonsByTypes: function(aTypes, aCallback) { + getAddonsByTypes(aTypes, aCallback) { if (aTypes && aTypes.indexOf(ADDON_TYPE_SERVICE) == -1) { aCallback([]); return; @@ -892,7 +892,7 @@ var SocialAddonProvider = { aCallback([...SocialServiceInternal.manifests].map(a => new AddonWrapper(a))); }, - removeAddon: function(aAddon, aCallback) { + removeAddon(aAddon, aCallback) { AddonManagerPrivate.callAddonListeners("onUninstalling", aAddon, false); aAddon.pendingOperations |= AddonManager.PENDING_UNINSTALL; Services.prefs.clearUserPref(getPrefnameFromOrigin(aAddon.manifest.origin)); @@ -943,7 +943,7 @@ AddonWrapper.prototype = { return false; }, - isCompatibleWith: function(appVersion, platformVersion) { + isCompatibleWith(appVersion, platformVersion) { return true; }, @@ -993,7 +993,7 @@ AddonWrapper.prototype = { return permissions; }, - findUpdates: function(listener, reason, appVersion, platformVersion) { + findUpdates(listener, reason, appVersion, platformVersion) { if ("onNoCompatibilityUpdateAvailable" in listener) listener.onNoCompatibilityUpdateAvailable(this); if ("onNoUpdateAvailable" in listener) @@ -1069,7 +1069,7 @@ AddonWrapper.prototype = { return val; }, - uninstall: function(aCallback) { + uninstall(aCallback) { let prefName = getPrefnameFromOrigin(this.manifest.origin); if (Services.prefs.prefHasUserValue(prefName)) { if (ActiveProviders.has(this.manifest.origin)) { @@ -1084,7 +1084,7 @@ AddonWrapper.prototype = { } }, - cancelUninstall: function() { + cancelUninstall() { this._pending -= AddonManager.PENDING_UNINSTALL; AddonManagerPrivate.callAddonListeners("onOperationCancelled", this); } diff --git a/browser/modules/TransientPrefs.jsm b/browser/modules/TransientPrefs.jsm index aa2bd20c9ab2..a12c3c2c94d6 100644 --- a/browser/modules/TransientPrefs.jsm +++ b/browser/modules/TransientPrefs.jsm @@ -15,7 +15,7 @@ var prefVisibility = new Map; application. */ this.TransientPrefs = { - prefShouldBeVisible: function(prefName) { + prefShouldBeVisible(prefName) { if (Preferences.isSet(prefName)) prefVisibility.set(prefName, true); diff --git a/browser/modules/URLBarZoom.jsm b/browser/modules/URLBarZoom.jsm index 3e1c0f70761c..c496c339bbbc 100644 --- a/browser/modules/URLBarZoom.jsm +++ b/browser/modules/URLBarZoom.jsm @@ -11,7 +11,7 @@ Components.utils.import("resource://gre/modules/Services.jsm"); var URLBarZoom = { - init: function(aWindow) { + init(aWindow) { // Register ourselves with the service so we know when the zoom prefs change. Services.obs.addObserver(updateZoomButton, "browser-fullZoom:zoomChange", false); Services.obs.addObserver(updateZoomButton, "browser-fullZoom:zoomReset", false); diff --git a/browser/modules/Windows8WindowFrameColor.jsm b/browser/modules/Windows8WindowFrameColor.jsm index 911333747f6f..245ced4aea5e 100644 --- a/browser/modules/Windows8WindowFrameColor.jsm +++ b/browser/modules/Windows8WindowFrameColor.jsm @@ -14,7 +14,7 @@ var Registry = Cu.import("resource://gre/modules/WindowsRegistry.jsm").WindowsRe var Windows8WindowFrameColor = { _windowFrameColor: null, - get: function() { + get() { if (this._windowFrameColor) return this._windowFrameColor; diff --git a/browser/modules/WindowsJumpLists.jsm b/browser/modules/WindowsJumpLists.jsm index fff70148690f..8f4088cf257f 100644 --- a/browser/modules/WindowsJumpLists.jsm +++ b/browser/modules/WindowsJumpLists.jsm @@ -426,7 +426,7 @@ this.WinTaskbarJumpList = // Return the pending statement to the caller, to allow cancelation. return PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase) .asyncExecuteLegacyQueries([query], 1, options, { - handleResult: function(aResultSet) { + handleResult(aResultSet) { for (let row; (row = aResultSet.getNextRow());) { try { aCallback.call(aScope, @@ -436,11 +436,11 @@ this.WinTaskbarJumpList = } catch (e) {} } }, - handleError: function(aError) { + handleError(aError) { Components.utils.reportError( "Async execution error (" + aError.result + "): " + aError.message); }, - handleCompletion: function(aReason) { + handleCompletion(aReason) { aCallback.call(WinTaskbarJumpList, null); }, }); diff --git a/browser/modules/WindowsPreviewPerTab.jsm b/browser/modules/WindowsPreviewPerTab.jsm index 66488310f2eb..04d76feb4fbc 100644 --- a/browser/modules/WindowsPreviewPerTab.jsm +++ b/browser/modules/WindowsPreviewPerTab.jsm @@ -72,7 +72,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "PageThumbs", // nsIURI -> imgIContainer function _imageFromURI(uri, privateMode, callback) { let channel = NetUtil.newChannel({ - uri: uri, + uri, loadUsingSystemPrincipal: true, contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE }); @@ -158,7 +158,7 @@ PreviewController.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsITaskbarPreviewController, Ci.nsIDOMEventListener]), - destroy: function() { + destroy() { this.tab.removeEventListener("TabAttrModified", this, false); // Break cycles, otherwise we end up leaking the window with everything @@ -172,7 +172,7 @@ PreviewController.prototype = { }, // Resizes the canvasPreview to 0x0, essentially freeing its memory. - resetCanvasPreview: function() { + resetCanvasPreview() { this.canvasPreview.width = 0; this.canvasPreview.height = 0; }, @@ -180,7 +180,7 @@ PreviewController.prototype = { /** * Set the canvas dimensions. */ - resizeCanvasPreview: function(aRequestedWidth, aRequestedHeight) { + resizeCanvasPreview(aRequestedWidth, aRequestedHeight) { this.canvasPreview.width = aRequestedWidth; this.canvasPreview.height = aRequestedHeight; }, @@ -204,13 +204,13 @@ PreviewController.prototype = { return this.tab.linkedBrowser.getBoundingClientRect(); }, - cacheBrowserDims: function() { + cacheBrowserDims() { let dims = this.browserDims; this._cachedWidth = dims.width; this._cachedHeight = dims.height; }, - testCacheBrowserDims: function() { + testCacheBrowserDims() { let dims = this.browserDims; return this._cachedWidth == dims.width && this._cachedHeight == dims.height; @@ -220,7 +220,7 @@ PreviewController.prototype = { * Capture a new thumbnail image for this preview. Called by the controller * in response to a request for a new thumbnail image. */ - updateCanvasPreview: function(aFullScale, aCallback) { + updateCanvasPreview(aFullScale, aCallback) { // Update our cached browser dims so that delayed resize // events don't trigger another invalidation if this tab becomes active. this.cacheBrowserDims(); @@ -231,7 +231,7 @@ PreviewController.prototype = { AeroPeek.resetCacheTimer(); }, - updateTitleAndTooltip: function() { + updateTitleAndTooltip() { let title = this.win.tabbrowser.getWindowTitleForBrowser(this.linkedBrowser); this.preview.title = title; this.preview.tooltip = title; @@ -264,7 +264,7 @@ PreviewController.prototype = { * * @param aTaskbarCallback nsITaskbarPreviewCallback results callback */ - requestPreview: function(aTaskbarCallback) { + requestPreview(aTaskbarCallback) { // Grab a high res content preview this.resetCanvasPreview(); this.updateCanvasPreview(true, (aPreviewCanvas) => { @@ -312,7 +312,7 @@ PreviewController.prototype = { * @param aRequestedWidth width of the requested thumbnail * @param aRequestedHeight height of the requested thumbnail */ - requestThumbnail: function(aTaskbarCallback, aRequestedWidth, aRequestedHeight) { + requestThumbnail(aTaskbarCallback, aRequestedWidth, aRequestedHeight) { this.resizeCanvasPreview(aRequestedWidth, aRequestedHeight); this.updateCanvasPreview(false, (aThumbnailCanvas) => { aTaskbarCallback.done(aThumbnailCanvas, false); @@ -321,11 +321,11 @@ PreviewController.prototype = { // Event handling - onClose: function() { + onClose() { this.win.tabbrowser.removeTab(this.tab); }, - onActivate: function() { + onActivate() { this.win.tabbrowser.selectedTab = this.tab; // Accept activation - this will restore the browser window @@ -334,7 +334,7 @@ PreviewController.prototype = { }, // nsIDOMEventListener - handleEvent: function(evt) { + handleEvent(evt) { switch (evt.type) { case "TabAttrModified": this.updateTitleAndTooltip(); @@ -389,7 +389,7 @@ TabWindow.prototype = { tabEvents: ["TabOpen", "TabClose", "TabSelect", "TabMove"], winEvents: ["resize"], - destroy: function() { + destroy() { this._destroying = true; let tabs = this.tabbrowser.tabs; @@ -417,17 +417,17 @@ TabWindow.prototype = { return this.win.innerHeight; }, - cacheDims: function() { + cacheDims() { this._cachedWidth = this.width; this._cachedHeight = this.height; }, - testCacheDims: function() { + testCacheDims() { return this._cachedWidth == this.width && this._cachedHeight == this.height; }, // Invoked when the given tab is added to this window - newTab: function(tab) { + newTab(tab) { let controller = new PreviewController(this, tab); // It's OK to add the preview now while the favicon still loads. this.previews.set(tab, controller.preview); @@ -437,7 +437,7 @@ TabWindow.prototype = { controller.updateTitleAndTooltip(); }, - createTabPreview: function(controller) { + createTabPreview(controller) { let docShell = this.win .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) @@ -451,7 +451,7 @@ TabWindow.prototype = { }, // Invoked when the given tab is closed - removeTab: function(tab) { + removeTab(tab) { let preview = this.previewFromTab(tab); preview.active = false; preview.visible = false; @@ -478,11 +478,11 @@ TabWindow.prototype = { this.updateTabOrdering(); }, - previewFromTab: function(tab) { + previewFromTab(tab) { return this.previews.get(tab); }, - updateTabOrdering: function() { + updateTabOrdering() { let previews = this.previews; let tabs = this.tabbrowser.tabs; @@ -505,7 +505,7 @@ TabWindow.prototype = { }, // nsIDOMEventListener - handleEvent: function(evt) { + handleEvent(evt) { let tab = evt.originalTarget; switch (evt.type) { case "TabOpen": @@ -531,7 +531,7 @@ TabWindow.prototype = { }, // Set or reset a timer that will invalidate visible thumbnails soon. - setInvalidationTimer: function() { + setInvalidationTimer() { if (!this.invalidateTimer) { this.invalidateTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); } @@ -551,7 +551,7 @@ TabWindow.prototype = { }, 1000, Ci.nsITimer.TYPE_ONE_SHOT); }, - onResize: function() { + onResize() { // Specific to a window. // Call invalidate on each tab thumbnail so that Windows will request an @@ -569,7 +569,7 @@ TabWindow.prototype = { this.setInvalidationTimer(); }, - invalidateTabPreview: function(aBrowser) { + invalidateTabPreview(aBrowser) { for (let [tab, preview] of this.previews) { if (aBrowser == tab.linkedBrowser) { preview.invalidate(); @@ -580,13 +580,13 @@ TabWindow.prototype = { // Browser progress listener - onLocationChange: function(aBrowser) { + onLocationChange(aBrowser) { // I'm not sure we need this, onStateChange does a really good job // of picking up page changes. // this.invalidateTabPreview(aBrowser); }, - onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP && aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) { this.invalidateTabPreview(aBrowser); @@ -596,7 +596,7 @@ TabWindow.prototype = { directRequestProtocols: new Set([ "file", "chrome", "resource", "about" ]), - onLinkIconAvailable: function(aBrowser, aIconURL) { + onLinkIconAvailable(aBrowser, aIconURL) { let requestURL = null; if (aIconURL) { let shouldRequestFaviconURL = true; @@ -662,7 +662,7 @@ this.AeroPeek = { // Length of time in seconds that previews are cached cacheLifespan: 20, - initialize: function() { + initialize() { if (!(WINTASKBAR_CONTRACTID in Cc)) return; this.taskbar = Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar); @@ -752,25 +752,25 @@ this.AeroPeek = { } }, - addPreview: function(preview) { + addPreview(preview) { this.previews.push(preview); this.checkPreviewCount(); }, - removePreview: function(preview) { + removePreview(preview) { let idx = this.previews.indexOf(preview); this.previews.splice(idx, 1); this.checkPreviewCount(); }, - checkPreviewCount: function() { + checkPreviewCount() { if (!this._prefenabled) { return; } this.enabled = this.previews.length <= this.maxpreviews; }, - onOpenWindow: function(win) { + onOpenWindow(win) { // This occurs when the taskbar service is not available (xp, vista) if (!this.available || !this._prefenabled) return; @@ -778,7 +778,7 @@ this.AeroPeek = { win.gTaskbarTabGroup = new TabWindow(win); }, - onCloseWindow: function(win) { + onCloseWindow(win) { // This occurs when the taskbar service is not available (xp, vista) if (!this.available || !this._prefenabled) return; @@ -790,13 +790,13 @@ this.AeroPeek = { this.destroy(); }, - resetCacheTimer: function() { + resetCacheTimer() { this.cacheTimer.cancel(); this.cacheTimer.init(this, 1000 * this.cacheLifespan, Ci.nsITimer.TYPE_ONE_SHOT); }, // nsIObserver - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "nsPref:changed" && aData == TOGGLE_PREF_NAME) { this._prefenabled = this.prefs.getBoolPref(TOGGLE_PREF_NAME); } diff --git a/browser/modules/offlineAppCache.jsm b/browser/modules/offlineAppCache.jsm index 5d0e3481a713..cbf561943467 100644 --- a/browser/modules/offlineAppCache.jsm +++ b/browser/modules/offlineAppCache.jsm @@ -10,7 +10,7 @@ const Cc = Components.classes; const Ci = Components.interfaces; this.OfflineAppCacheHelper = { - clear: function() { + clear() { var cacheService = Cc["@mozilla.org/netwerk/cache-storage-service;1"].getService(Ci.nsICacheStorageService); var appCacheStorage = cacheService.appCacheStorage(LoadContextInfo.default, null); try { diff --git a/browser/modules/test/browser_ContentSearch.js b/browser/modules/test/browser_ContentSearch.js index 22665f21bc18..ae2f2b1b8dc8 100644 --- a/browser/modules/test/browser_ContentSearch.js +++ b/browser/modules/test/browser_ContentSearch.js @@ -97,7 +97,7 @@ add_task(function* search() { engine.getSubmission(data.searchString, "", data.whence).uri.spec; gMsgMan.sendAsyncMessage(TEST_MSG, { type: "Search", - data: data, + data, expectedURL: submissionURL, }); let msg = yield waitForTestMsg("loadStopped"); @@ -121,7 +121,7 @@ add_task(function* searchInBackgroundTab() { engine.getSubmission(data.searchString, "", data.whence).uri.spec; gMsgMan.sendAsyncMessage(TEST_MSG, { type: "Search", - data: data, + data, expectedURL: submissionURL, }); @@ -315,11 +315,11 @@ function waitForNewEngine(basename, numImages) { let addDeferred = Promise.defer(); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); addDeferred.resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); addDeferred.reject(); }, diff --git a/browser/modules/test/browser_PermissionUI.js b/browser/modules/test/browser_PermissionUI.js index ddb8832ebfae..f396217f7974 100644 --- a/browser/modules/test/browser_PermissionUI.js +++ b/browser/modules/test/browser_PermissionUI.js @@ -223,7 +223,7 @@ add_task(function* test_with_permission_key() { accessKey: "M", action: Ci.nsIPermissionManager.ALLOW_ACTION, expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION, - callback: function() { + callback() { allowed = true; } }; @@ -234,7 +234,7 @@ add_task(function* test_with_permission_key() { accessKey: "D", action: Ci.nsIPermissionManager.DENY_ACTION, expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION, - callback: function() { + callback() { denied = true; } }; @@ -376,7 +376,7 @@ add_task(function* test_no_request() { let mainAction = { label: "Allow", accessKey: "M", - callback: function() { + callback() { allowed = true; } }; @@ -385,7 +385,7 @@ add_task(function* test_no_request() { let secondaryAction = { label: "Deny", accessKey: "D", - callback: function() { + callback() { denied = true; } }; diff --git a/browser/modules/test/browser_ProcessHangNotifications.js b/browser/modules/test/browser_ProcessHangNotifications.js index 715801b35b66..87a7c8811a8c 100644 --- a/browser/modules/test/browser_ProcessHangNotifications.js +++ b/browser/modules/test/browser_ProcessHangNotifications.js @@ -44,7 +44,7 @@ let gTestHangReport = { TEST_CALLBACK_TERMPLUGIN: 3, _hangType: 1, - _tcb: function(aCallbackType) {}, + _tcb(aCallbackType) {}, get hangType() { return this._hangType; @@ -58,26 +58,26 @@ let gTestHangReport = { this._tcb = aValue; }, - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (aIID.equals(Components.interfaces.nsIHangReport) || aIID.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_NOINTERFACE; }, - userCanceled: function() { + userCanceled() { this._tcb(this.TEST_CALLBACK_CANCELED); }, - terminateScript: function() { + terminateScript() { this._tcb(this.TEST_CALLBACK_TERMSCRIPT); }, - terminatePlugin: function() { + terminatePlugin() { this._tcb(this.TEST_CALLBACK_TERMPLUGIN); }, - isReportForBrowser: function(aFrameLoader) { + isReportForBrowser(aFrameLoader) { return true; } }; diff --git a/browser/modules/test/contentSearch.js b/browser/modules/test/contentSearch.js index fda68a7a4104..8b2b498da7a8 100644 --- a/browser/modules/test/contentSearch.js +++ b/browser/modules/test/contentSearch.js @@ -30,7 +30,7 @@ addMessageListener(TEST_MSG, msg => { waitForLoadAndStopIt(msg.data.expectedURL, url => { sendAsyncMessage(TEST_MSG, { type: "loadStopped", - url: url, + url, }); }); } @@ -41,7 +41,7 @@ function waitForLoadAndStopIt(expectedURL, callback) { let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); let listener = { - onStateChange: function(webProg, req, flags, status) { + onStateChange(webProg, req, flags, status) { if (req instanceof Ci.nsIChannel) { let url = req.originalURI.spec; dump("waitForLoadAndStopIt: onStateChange " + url + "\n"); diff --git a/browser/modules/test/unit/social/head.js b/browser/modules/test/unit/social/head.js index b7f06d33b2d4..0a94f536deec 100644 --- a/browser/modules/test/unit/social/head.js +++ b/browser/modules/test/unit/social/head.js @@ -132,7 +132,7 @@ function AsyncRunner() { this._callbacks = { done: do_test_finished, - error: function(err) { + error(err) { // xpcshell test functions like do_check_eq throw NS_ERROR_ABORT on // failure. Ignore those so they aren't rethrown here. if (err !== Cr.NS_ERROR_ABORT) { @@ -143,7 +143,7 @@ function AsyncRunner() { do_throw(err); } }, - consoleError: function(scriptErr) { + consoleError(scriptErr) { // Try to ensure the error is related to the test. let filename = scriptErr.sourceName || scriptErr.toString() || ""; if (filename.indexOf("/toolkit/components/social/") >= 0) diff --git a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js index b74250fc69c4..a72dbd492e4d 100644 --- a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js +++ b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js @@ -247,7 +247,7 @@ function setTimeout(fun, timeout) { let timer = Components.classes["@mozilla.org/timer;1"] .createInstance(Components.interfaces.nsITimer); var event = { - notify: function() { + notify() { fun(); } }; @@ -1062,7 +1062,7 @@ add_task(function* test_DirectoryLinksProvider_getEnhancedLink() { do_check_eq(links.length, 0); // There are no directory links. function checkEnhanced(url, image) { - let enhanced = DirectoryLinksProvider.getEnhancedLink({url: url}); + let enhanced = DirectoryLinksProvider.getEnhancedLink({url}); do_check_eq(enhanced && enhanced.enhancedImageURI, image); } @@ -1487,7 +1487,7 @@ add_task(function* test_DirectoryLinksProvider_getFrequencyCapReportSiteAction() targetedSite: "foo.com", url: "bar.com" }, - isPinned: function() { return false; }, + isPinned() { return false; }, }], "view", 0); // read file content and ensure that view counters are updated @@ -1531,9 +1531,9 @@ add_task(function* test_DirectoryLinksProvider_ClickRemoval() { }] }, { - handleError: function() { do_check_true(false); }, - handleResult: function() {}, - handleCompletion: function() { resolve(); } + handleError() { do_check_true(false); }, + handleResult() {}, + handleCompletion() { resolve(); } } ); }); @@ -1827,7 +1827,7 @@ add_task(function* test_blockSuggestedTiles() { // block suggested tile in a regular way DirectoryLinksProvider.reportSitesAction([{ - isPinned: function() { return false; }, + isPinned() { return false; }, link: Object.assign({frecency: 1000}, suggestedLink) }], "block", 0); diff --git a/browser/modules/webrtcUI.jsm b/browser/modules/webrtcUI.jsm index 4f818a6194d1..fd40ca0cf1fb 100644 --- a/browser/modules/webrtcUI.jsm +++ b/browser/modules/webrtcUI.jsm @@ -29,7 +29,7 @@ this.webrtcUI = { peerConnectionBlockers: new Set(), emitter: new EventEmitter(), - init: function() { + init() { Services.obs.addObserver(maybeAddMenuIndicator, "browser-delayed-startup-finished", false); let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] @@ -47,7 +47,7 @@ this.webrtcUI = { mm.addMessageListener("webrtc:UpdateBrowserIndicators", this); }, - uninit: function() { + uninit() { Services.obs.removeObserver(maybeAddMenuIndicator, "browser-delayed-startup-finished"); let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] @@ -113,7 +113,7 @@ this.webrtcUI = { _streams: [], // The boolean parameters indicate which streams should be included in the result. - getActiveStreams: function(aCamera, aMicrophone, aScreen) { + getActiveStreams(aCamera, aMicrophone, aScreen) { return webrtcUI._streams.filter(aStream => { let state = aStream.state; return aCamera && state.camera || @@ -127,22 +127,22 @@ this.webrtcUI = { let browserWindow = browser.ownerGlobal; let tab = browserWindow.gBrowser && browserWindow.gBrowser.getTabForBrowser(browser); - return {uri: state.documentURI, tab: tab, browser: browser, types: types}; + return {uri: state.documentURI, tab, browser, types}; }); }, - swapBrowserForNotification: function(aOldBrowser, aNewBrowser) { + swapBrowserForNotification(aOldBrowser, aNewBrowser) { for (let stream of this._streams) { if (stream.browser == aOldBrowser) stream.browser = aNewBrowser; } }, - forgetStreamsFromBrowser: function(aBrowser) { + forgetStreamsFromBrowser(aBrowser) { this._streams = this._streams.filter(stream => stream.browser != aBrowser); }, - showSharingDoorhanger: function(aActiveStream) { + showSharingDoorhanger(aActiveStream) { let browserWindow = aActiveStream.browser.ownerGlobal; if (aActiveStream.tab) { browserWindow.gBrowser.selectedTab = aActiveStream.tab; @@ -165,7 +165,7 @@ this.webrtcUI = { identityBox.click(); }, - updateWarningLabel: function(aMenuList) { + updateWarningLabel(aMenuList) { let type = aMenuList.selectedItem.getAttribute("devicetype"); let document = aMenuList.ownerDocument; document.getElementById("webRTC-all-windows-shared").hidden = type != "Screen"; @@ -195,23 +195,23 @@ this.webrtcUI = { // is canceled. (This would typically be used in // conjunction with a blocking handler to cancel // a user prompt or other work done by the handler) - addPeerConnectionBlocker: function(aCallback) { + addPeerConnectionBlocker(aCallback) { this.peerConnectionBlockers.add(aCallback); }, - removePeerConnectionBlocker: function(aCallback) { + removePeerConnectionBlocker(aCallback) { this.peerConnectionBlockers.delete(aCallback); }, - on: function(...args) { + on(...args) { return this.emitter.on(...args); }, - off: function(...args) { + off(...args) { return this.emitter.off(...args); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "rtcpeer:Request": { @@ -348,14 +348,14 @@ function prompt(aBrowser, aRequest) { // The real callback will be set during the "showing" event. The // empty function here is so that PopupNotifications.show doesn't // reject the action. - callback: function() {} + callback() {} }; let secondaryActions = [ { label: stringBundle.getString("getUserMedia.dontAllow.label"), accessKey: stringBundle.getString("getUserMedia.dontAllow.accesskey"), - callback: function(aState) { + callback(aState) { denyRequest(notification.browser, aRequest); if (aState && aState.checkboxChecked) { let perms = Services.perms; @@ -393,7 +393,7 @@ function prompt(aBrowser, aRequest) { [productName]) } : undefined, }, - eventCallback: function(aTopic, aNewBrowser) { + eventCallback(aTopic, aNewBrowser) { if (aTopic == "swapping") return true; @@ -746,11 +746,11 @@ function getGlobalIndicator() { _statusBar: Cc["@mozilla.org/widget/macsystemstatusbar;1"] .getService(Ci.nsISystemStatusBar), - _command: function(aEvent) { + _command(aEvent) { webrtcUI.showSharingDoorhanger(aEvent.target.stream); }, - _popupShowing: function(aEvent) { + _popupShowing(aEvent) { let type = this.getAttribute("type"); let activeStreams; if (type == "Camera") { @@ -809,12 +809,12 @@ function getGlobalIndicator() { return true; }, - _popupHiding: function(aEvent) { + _popupHiding(aEvent) { while (this.firstChild) this.firstChild.remove(); }, - _setIndicatorState: function(aName, aState) { + _setIndicatorState(aName, aState) { let field = "_" + aName.toLowerCase(); if (aState && !this[field]) { let menu = this._hiddenDoc.createElement("menu"); @@ -840,12 +840,12 @@ function getGlobalIndicator() { this[field] = null } }, - updateIndicatorState: function() { + updateIndicatorState() { this._setIndicatorState("Camera", webrtcUI.showCameraIndicator); this._setIndicatorState("Microphone", webrtcUI.showMicrophoneIndicator); this._setIndicatorState("Screen", webrtcUI.showScreenSharingIndicator); }, - close: function() { + close() { this._setIndicatorState("Camera", false); this._setIndicatorState("Microphone", false); this._setIndicatorState("Screen", false); diff --git a/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm b/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm index 557b867b9bf1..5feb7bd17093 100644 --- a/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm +++ b/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm @@ -150,7 +150,7 @@ this.TestRunner = { // helpers - _performCombo: function*(combo) { + *_performCombo(combo) { let paddedComboIndex = padLeft(this.currentComboIndex + 1, String(this.combos.length).length); log.info("Combination " + paddedComboIndex + "/" + this.combos.length + ": " + this._comboName(combo).substring(1)); diff --git a/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm b/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm index 97d8354d5b0a..f501ea140422 100644 --- a/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm +++ b/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm @@ -64,7 +64,7 @@ this.Buttons = { function createWidget() { let id = "screenshot-widget"; let spec = { - id: id, + id, label: "My Button", removable: true, tooltiptext: "", diff --git a/storage/test/unit/head_storage.js b/storage/test/unit/head_storage.js index 27a4749eda18..ab05e10b593b 100644 --- a/storage/test/unit/head_storage.js +++ b/storage/test/unit/head_storage.js @@ -316,15 +316,15 @@ function openAsyncDatabase(file, options) { function executeAsync(statement, onResult) { let deferred = Promise.defer(); statement.executeAsync({ - handleError: function(error) { + handleError(error) { deferred.reject(error); }, - handleResult: function(result) { + handleResult(result) { if (onResult) { onResult(result); } }, - handleCompletion: function(result) { + handleCompletion(result) { deferred.resolve(result); } }); @@ -334,15 +334,15 @@ function executeAsync(statement, onResult) { function executeMultipleStatementsAsync(db, statements, onResult) { let deferred = Promise.defer(); db.executeAsync(statements, statements.length, { - handleError: function(error) { + handleError(error) { deferred.reject(error); }, - handleResult: function(result) { + handleResult(result) { if (onResult) { onResult(result); } }, - handleCompletion: function(result) { + handleCompletion(result) { deferred.resolve(result); } }); diff --git a/toolkit/.eslintrc.js b/toolkit/.eslintrc.js index c79d8702d966..5eec2b565574 100644 --- a/toolkit/.eslintrc.js +++ b/toolkit/.eslintrc.js @@ -163,6 +163,9 @@ module.exports = { // No using with "no-with": "error", + // Require object-literal shorthand with ES6 method syntax + "object-shorthand": ["error", "always", { "avoidQuotes": true }], + // No spacing inside rest or spread expressions "rest-spread-spacing": "error", diff --git a/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js b/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js index 4cbd141f7662..091a8a6750db 100644 --- a/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js +++ b/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js @@ -114,7 +114,7 @@ function loadData() { if (destIndex == 0) { // create the initial frame renderData.push({ - timestamp: timestamp, + timestamp, rects: {}, }); } else if (renderData[destIndex - 1].timestamp == timestamp) { diff --git a/toolkit/components/aboutmemory/content/aboutMemory.js b/toolkit/components/aboutmemory/content/aboutMemory.js index c62416dc5427..7856aa9feb57 100644 --- a/toolkit/components/aboutmemory/content/aboutMemory.js +++ b/toolkit/components/aboutmemory/content/aboutMemory.js @@ -498,7 +498,7 @@ function dumpGCLogAndCCLog(aVerbose) dumper.dumpGCAndCCLogsToFile("", aVerbose, /* dumpChildProcesses = */ true, { onDump: displayInfo, - onFinish: function() { + onFinish() { inProgress.remove(); } }); @@ -657,12 +657,12 @@ function loadMemoryReportsFromFile(aFilename, aTitleNote, aFn) let converter = new nsGzipConverter(); converter.asyncConvertData("gzip", "uncompressed", { data: [], - onStartRequest: function(aR, aC) {}, - onDataAvailable: function(aR, aC, aStream, aO, aCount) { + onStartRequest(aR, aC) {}, + onDataAvailable(aR, aC, aStream, aO, aCount) { let bi = new nsBinaryStream(aStream); this.data.push(bi.readBytes(aCount)); }, - onStopRequest: function(aR, aC, aStatusCode) { + onStopRequest(aR, aC, aStatusCode) { try { if (!Components.isSuccessCode(aStatusCode)) { throw new Components.Exception("Error while reading gzip file", aStatusCode); @@ -746,7 +746,7 @@ function DReport(aKind, aUnits, aAmount, aDescription, aNMerged, aPresence) } DReport.prototype = { - assertCompatible: function(aKind, aUnits) + assertCompatible(aKind, aUnits) { assert(this._kind == aKind, "Mismatched kinds"); assert(this._units == aUnits, "Mismatched units"); @@ -767,13 +767,13 @@ DReport.prototype = { // the descriptions to differ seems reasonable.) }, - merge: function(aJr) { + merge(aJr) { this.assertCompatible(aJr.kind, aJr.units); this._amount += aJr.amount; this._nMerged++; }, - toJSON: function(aProcess, aPath, aAmount) { + toJSON(aProcess, aPath, aAmount) { return { process: aProcess, path: aPath, @@ -1126,7 +1126,7 @@ function TreeNode(aUnsafeName, aUnits, aIsDegenerate) } TreeNode.prototype = { - findKid: function(aUnsafeName) { + findKid(aUnsafeName) { if (this._kids) { for (let i = 0; i < this._kids.length; i++) { if (this._kids[i]._unsafeName === aUnsafeName) { @@ -1143,7 +1143,7 @@ TreeNode.prototype = { // things. So for a non-leaf node, instead of just looking at _amount, we // instead look at the maximum absolute value of the node and all of its // descendants. - maxAbsDescendant: function() { + maxAbsDescendant() { if (!this._kids) { // No kids? Just return the absolute value of the amount. return Math.abs(this._amount); @@ -1163,7 +1163,7 @@ TreeNode.prototype = { return max; }, - toString: function() { + toString() { switch (this._units) { case UNITS_BYTES: return formatBytes(this._amount); case UNITS_COUNT: diff --git a/toolkit/components/aboutperformance/content/aboutPerformance.js b/toolkit/components/aboutperformance/content/aboutPerformance.js index 862d3cf0e249..f1b04df719df 100644 --- a/toolkit/components/aboutperformance/content/aboutPerformance.js +++ b/toolkit/components/aboutperformance/content/aboutPerformance.js @@ -72,7 +72,7 @@ const MODE_GLOBAL = "global"; const MODE_RECENT = "recent"; let tabFinder = { - update: function() { + update() { this._map = new Map(); let windows = Services.wm.getEnumerator("navigator:browser"); while (windows.hasMoreElements()) { @@ -97,7 +97,7 @@ let tabFinder = { * @return {{tabbrowser: , tab: }} The * tabbrowser and tab if the latter could be found. */ - get: function(id) { + get(id) { let browser = this._map.get(id); if (!browser) { return null; @@ -106,7 +106,7 @@ let tabFinder = { return {tabbrowser, tab:tabbrowser.getTabForBrowser(browser)}; }, - getAny: function(ids) { + getAny(ids) { for (let id of ids) { let result = this.get(id); if (result) { @@ -258,7 +258,7 @@ Delta.prototype = { /** * Initialize, asynchronously. */ - promiseInit: function() { + promiseInit() { if (this.kind == "webpages") { return this._initWebpage(); } else if (this.kind == "addons") { @@ -266,7 +266,7 @@ Delta.prototype = { } throw new TypeError(); }, - _initWebpage: function() { + _initWebpage() { this._initialized = true; let found = tabFinder.getAny(this.diff.windowIds); if (!found || found.tab.linkedBrowser.contentTitle == null) { @@ -296,7 +296,7 @@ Delta.prototype = { this._show = found; this.fullName = this.diff.addonId; }), - toString: function() { + toString() { return `[Delta] ${this.diff.key} => ${this.readableName}, ${this.fullName}`; } }; @@ -444,14 +444,14 @@ var State = { /** * @return {Promise} */ - promiseDeltaSinceStartOfTime: function() { + promiseDeltaSinceStartOfTime() { return this._promiseDeltaSince(this._oldest); }, /** * @return {Promise} */ - promiseDeltaSinceStartOfBuffer: function() { + promiseDeltaSinceStartOfBuffer() { return this._promiseDeltaSince(this._buffer[0]); }, @@ -528,10 +528,10 @@ var View = { * @return {null} If the `deltaKey` doesn't have a component cached yet. * Otherwise, the value stored with `set`. */ - get: function(deltaKey) { + get(deltaKey) { return this._map.get(deltaKey); }, - set: function(deltaKey, value) { + set(deltaKey, value) { this._map.set(deltaKey, value); }, /** @@ -539,7 +539,7 @@ var View = { * * @param {Set} set a set of deltaKey. */ - trimTo: function(set) { + trimTo(set) { let remove = []; for (let key of this._map.keys()) { if (!set.has(key)) { @@ -560,7 +560,7 @@ var View = { * @param {string} nature The nature of the subset. One of "addons", "webpages" or "system". * @param {string} currentMode The current display mode. One of MODE_GLOBAL or MODE_RECENT. */ - updateCategory: function(subset, id, nature, currentMode) { + updateCategory(subset, id, nature, currentMode) { subset = subset.slice().sort(Delta.revCompare); let watcherAlerts = null; @@ -657,7 +657,7 @@ var View = { this._insertElements(toAdd, id); }, - _insertElements: function(elements, id) { + _insertElements(elements, id) { let eltContainer = document.getElementById(id); eltContainer.classList.remove("measuring"); eltContainer.eltVisibleContent.innerHTML = ""; @@ -681,7 +681,7 @@ var View = { eltContainer.textContent = "Nothing"; } }, - _setupStructure: function(id) { + _setupStructure(id) { let eltContainer = document.getElementById(id); if (!eltContainer.eltVisibleContent) { eltContainer.eltVisibleContent = document.createElement("ul"); @@ -712,7 +712,7 @@ var View = { return eltContainer; }, - _grabOrCreateElements: function(delta, nature) { + _grabOrCreateElements(delta, nature) { let cachedElements = this.DOMCache.get(delta.key); if (cachedElements) { if (cachedElements.eltRoot.parentElement) { @@ -857,7 +857,7 @@ var View = { }; var Control = { - init: function() { + init() { this._initAutorefresh(); this._initDisplayMode(); }, @@ -886,7 +886,7 @@ var Control = { // Inform watchers Services.obs.notifyObservers(null, UPDATE_COMPLETE_TOPIC, mode); }), - _setOptions: function(options) { + _setOptions(options) { dump(`about:performance _setOptions ${JSON.stringify(options)}\n`); let eltRefresh = document.getElementById("check-autorefresh"); if ((options.autoRefresh > 0) != eltRefresh.checked) { @@ -897,7 +897,7 @@ var Control = { eltCheckRecent.click(); } }, - _initAutorefresh: function() { + _initAutorefresh() { let onRefreshChange = (shouldUpdateNow = false) => { if (eltRefresh.checked == !!this._autoRefreshInterval) { // Nothing to change. @@ -920,7 +920,7 @@ var Control = { onRefreshChange(false); }, _autoRefreshInterval: null, - _initDisplayMode: function() { + _initDisplayMode() { let onModeChange = (shouldUpdateNow) => { if (eltCheckRecent.checked) { this._displayMode = MODE_RECENT; @@ -956,7 +956,7 @@ var SubprocessMonitor = { * Init will start the process of updating the table if the page is not hidden, * and set up an event listener for handling visibility changes. */ - init: function() { + init() { if (!document.hidden) { SubprocessMonitor.updateTable(); } @@ -967,7 +967,7 @@ var SubprocessMonitor = { * This function updates the table after an interval if the page is visible * and clears the interval otherwise. */ - handleVisibilityChange: function() { + handleVisibilityChange() { if (!document.hidden) { SubprocessMonitor.queueUpdate(); } else { @@ -980,7 +980,7 @@ var SubprocessMonitor = { * This function queues a timer to request the next summary using updateTable * after some delay. */ - queueUpdate: function() { + queueUpdate() { this._timeout = setTimeout(() => this.updateTable(), UPDATE_INTERVAL_MS); }, @@ -990,7 +990,7 @@ var SubprocessMonitor = { * @param {object} summaries The object with the updated RSS and USS values. * @param {string} pid The pid represented by the row for which we update. */ - updateRow: function(row, summaries, pid) { + updateRow(row, summaries, pid) { row.cells[0].textContent = pid; let RSSval = DownloadUtils.convertByteUnits(summaries[pid].rss); row.cells[1].textContent = RSSval.join(" "); @@ -1002,7 +1002,7 @@ var SubprocessMonitor = { * This function adds a row to the subprocess-performance table for every new pid * and populates and regularly updates it with RSS/USS measurements. */ - updateTable: function() { + updateTable() { if (!document.hidden) { Memory.summary().then((summaries) => { if (!(Object.keys(summaries).length)) { diff --git a/toolkit/components/addoncompat/CompatWarning.jsm b/toolkit/components/addoncompat/CompatWarning.jsm index b32409a46b6b..2e9fd5ad6be7 100644 --- a/toolkit/components/addoncompat/CompatWarning.jsm +++ b/toolkit/components/addoncompat/CompatWarning.jsm @@ -27,7 +27,7 @@ var CompatWarning = { // might only want to warn about it if the listener actually // fires. However, we want the warning to show a stack for the // registration site. - delayedWarning: function(msg, addon, warning) { + delayedWarning(msg, addon, warning) { function isShimLayer(filename) { return filename.indexOf("CompatWarning.jsm") != -1 || filename.indexOf("RemoteAddonsParent.jsm") != -1 || @@ -86,7 +86,7 @@ var CompatWarning = { }; }, - warn: function(msg, addon, warning) { + warn(msg, addon, warning) { let delayed = this.delayedWarning(msg, addon, warning); delayed(); }, diff --git a/toolkit/components/addoncompat/Prefetcher.jsm b/toolkit/components/addoncompat/Prefetcher.jsm index 2d836690cc23..3dd59e1f1609 100644 --- a/toolkit/components/addoncompat/Prefetcher.jsm +++ b/toolkit/components/addoncompat/Prefetcher.jsm @@ -314,7 +314,7 @@ function Database(trigger, addons) Database.prototype = { // Add an object to a table. - add: function(table, obj) { + add(table, obj) { if (!this.tables.has(table)) { this.tables.set(table, new Set()); } @@ -327,13 +327,13 @@ Database.prototype = { this.todo.push([table, obj]); }, - cache: function(...args) { + cache(...args) { this.cached.push(args); }, // Run a fixed-point iteration that adds objects to table based on // this.rules until there are no more objects to add. - process: function() { + process() { while (this.todo.length) { let [table, obj] = this.todo.pop(); let rules = this.rules.get(table); @@ -348,7 +348,7 @@ Database.prototype = { }; var Prefetcher = { - init: function() { + init() { // Give an index to each rule and store it in this.ruleMap based // on the index. The index is used to serialize and deserialize // data from content to chrome. @@ -368,7 +368,7 @@ var Prefetcher = { Services.obs.addObserver(this, "xpcom-shutdown", false); }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic == "xpcom-shutdown") { Services.prefs.removeObserver(PREF_PREFETCHING_ENABLED, this); Services.obs.removeObserver(this, "xpcom-shutdown"); @@ -381,7 +381,7 @@ var Prefetcher = { // described by the trigger string. |addons| is a list of addons // that have listeners installed for the event. |args| is // event-specific data (such as the event object). - prefetch: function(trigger, addons, args) { + prefetch(trigger, addons, args) { if (!this.prefetchingEnabled) { return [[], []]; } @@ -425,7 +425,7 @@ var Prefetcher = { // Generate a two-level mapping based on cached data received from // the content process. - generateCache: function(prefetched, cpows) { + generateCache(prefetched, cpows) { let cache = new Map(); for (let item of prefetched) { // Replace anything of the form {cpow: } with the actual @@ -446,7 +446,7 @@ var Prefetcher = { // Run |func|, using the prefetched data in |prefetched| and |cpows| // as a cache. - withPrefetching: function(prefetched, cpows, func) { + withPrefetching(prefetched, cpows, func) { if (!this.prefetchingEnabled) { return func(); } @@ -466,7 +466,7 @@ var Prefetcher = { // Called by shim code in the chrome process to check if target.prop // is cached. - lookupInCache: function(addon, target, prop) { + lookupInCache(addon, target, prop) { if (!this.cache || !Cu.isCrossProcessWrapper(target)) { return null; } diff --git a/toolkit/components/addoncompat/RemoteAddonsChild.jsm b/toolkit/components/addoncompat/RemoteAddonsChild.jsm index 1aacc7f7abf3..9e430a44e90e 100644 --- a/toolkit/components/addoncompat/RemoteAddonsChild.jsm +++ b/toolkit/components/addoncompat/RemoteAddonsChild.jsm @@ -45,7 +45,7 @@ function setDefault(dict, key, default_) // In the child, clients can watch for changes to all paths that start // with a given component. var NotificationTracker = { - init: function() { + init() { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); cpmm.addMessageListener("Addons:ChangeNotification", this); @@ -54,7 +54,7 @@ var NotificationTracker = { this._watchers = {}; }, - receiveMessage: function(msg) { + receiveMessage(msg) { let path = msg.data.path; let count = msg.data.count; @@ -72,7 +72,7 @@ var NotificationTracker = { } }, - runCallback: function(watcher, path, count) { + runCallback(watcher, path, count) { let pathString = path.join("/"); let registeredSet = this._registered.get(watcher); let registered = registeredSet.has(pathString); @@ -85,7 +85,7 @@ var NotificationTracker = { } }, - findPaths: function(prefix) { + findPaths(prefix) { if (!this._paths) { return []; } @@ -117,12 +117,12 @@ var NotificationTracker = { return result; }, - findSuffixes: function(prefix) { + findSuffixes(prefix) { let paths = this.findPaths(prefix); return paths.map(([path, count]) => path[path.length - 1]); }, - watch: function(component1, watcher) { + watch(component1, watcher) { setDefault(this._watchers, component1, []).push(watcher); this._registered.set(watcher, new Set()); @@ -132,7 +132,7 @@ var NotificationTracker = { } }, - unwatch: function(component1, watcher) { + unwatch(component1, watcher) { let watchers = this._watchers[component1]; let index = watchers.lastIndexOf(watcher); if (index > -1) { @@ -156,7 +156,7 @@ var ContentPolicyChild = { _classID: Components.ID("6e869130-635c-11e2-bcfd-0800200c9a66"), _contractID: "@mozilla.org/addon-child/policy;1", - init: function() { + init() { let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); registrar.registerFactory(this._classID, this._classDescription, this._contractID, this); @@ -167,7 +167,7 @@ var ContentPolicyChild = { Ci.nsIChannelEventSink, Ci.nsIFactory, Ci.nsISupportsWeakReference]), - track: function(path, register) { + track(path, register) { let catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager); if (register) { catMan.addCategoryEntry("content-policy", this._contractID, this._contractID, false, true); @@ -176,7 +176,7 @@ var ContentPolicyChild = { } }, - shouldLoad: function(contentType, contentLocation, requestOrigin, + shouldLoad(contentType, contentLocation, requestOrigin, node, mimeTypeGuess, extra, requestPrincipal) { let addons = NotificationTracker.findSuffixes(["content-policy"]); let [prefetched, cpows] = Prefetcher.prefetch("ContentPolicy.shouldLoad", @@ -186,12 +186,12 @@ var ContentPolicyChild = { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); let rval = cpmm.sendRpcMessage("Addons:ContentPolicy:Run", { - contentType: contentType, + contentType, contentLocation: contentLocation.spec, requestOrigin: requestOrigin ? requestOrigin.spec : null, - mimeTypeGuess: mimeTypeGuess, - requestPrincipal: requestPrincipal, - prefetched: prefetched, + mimeTypeGuess, + requestPrincipal, + prefetched, }, cpows); if (rval.length != 1) { return Ci.nsIContentPolicy.ACCEPT; @@ -200,11 +200,11 @@ var ContentPolicyChild = { return rval[0]; }, - shouldProcess: function(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) { + shouldProcess(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) { return Ci.nsIContentPolicy.ACCEPT; }, - createInstance: function(outer, iid) { + createInstance(outer, iid) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -235,7 +235,7 @@ AboutProtocolChannel.prototype = { name: null, status: Cr.NS_OK, - asyncOpen: function(listener, context) { + asyncOpen(listener, context) { // Ask the parent to synchronously read all the data from the channel. let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); @@ -277,33 +277,33 @@ AboutProtocolChannel.prototype = { Services.tm.currentThread.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL); }, - asyncOpen2: function(listener) { + asyncOpen2(listener) { // throws an error if security checks fail var outListener = contentSecManager.performSecurityCheck(this, listener); this.asyncOpen(outListener, null); }, - open: function() { + open() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - open2: function() { + open2() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - isPending: function() { + isPending() { return false; }, - cancel: function() { + cancel() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - suspend: function() { + suspend() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - resume: function() { + resume() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, @@ -318,7 +318,7 @@ function AboutProtocolInstance(contractID) } AboutProtocolInstance.prototype = { - createInstance: function(outer, iid) { + createInstance(outer, iid) { if (outer != null) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -326,7 +326,7 @@ AboutProtocolInstance.prototype = { return this.QueryInterface(iid); }, - getURIFlags: function(uri) { + getURIFlags(uri) { // Cache the result to avoid the extra IPC. if (this._uriFlags !== undefined) { return this._uriFlags; @@ -354,7 +354,7 @@ AboutProtocolInstance.prototype = { // available to CPOWs. Consequently, we return a shim channel that, // when opened, asks the parent to open the channel and read out all // the data. - newChannel: function(uri, loadInfo) { + newChannel(uri, loadInfo) { return new AboutProtocolChannel(uri, this._contractID, loadInfo); }, @@ -364,7 +364,7 @@ AboutProtocolInstance.prototype = { var AboutProtocolChild = { _classDescription: "Addon shim about: protocol handler", - init: function() { + init() { // Maps contractIDs to instances this._instances = new Map(); // Maps contractIDs to classIDs @@ -372,7 +372,7 @@ var AboutProtocolChild = { NotificationTracker.watch("about-protocol", this); }, - track: function(path, register) { + track(path, register) { let contractID = path[1]; let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); if (register) { @@ -397,11 +397,11 @@ var AboutProtocolChild = { // This code registers observers in the child whenever an add-on in // the parent asks for notifications on the given topic. var ObserverChild = { - init: function() { + init() { NotificationTracker.watch("observer", this); }, - track: function(path, register) { + track(path, register) { let topic = path[1]; if (register) { Services.obs.addObserver(this, topic, false); @@ -410,13 +410,13 @@ var ObserverChild = { } }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); cpmm.sendRpcMessage("Addons:Observer:Run", {}, { - topic: topic, - subject: subject, - data: data + topic, + subject, + data }); } }; @@ -433,11 +433,11 @@ function EventTargetChild(childGlobal) } EventTargetChild.prototype = { - uninit: function() { + uninit() { NotificationTracker.unwatch("event", this); }, - track: function(path, register) { + track(path, register) { let eventType = path[1]; let useCapture = path[2]; let listener = useCapture ? this.capturingHandler : this.nonCapturingHandler; @@ -448,7 +448,7 @@ EventTargetChild.prototype = { } }, - handleEvent: function(capturing, event) { + handleEvent(capturing, event) { let addons = NotificationTracker.findSuffixes(["event", event.type, capturing]); let [prefetched, cpows] = Prefetcher.prefetch("EventTarget.handleEvent", addons, @@ -459,9 +459,9 @@ EventTargetChild.prototype = { this._childGlobal.sendRpcMessage("Addons:Event:Run", {type: event.type, - capturing: capturing, + capturing, isTrusted: event.isTrusted, - prefetched: prefetched}, + prefetched}, cpows); } }; @@ -481,34 +481,34 @@ function SandboxChild(chromeGlobal) } SandboxChild.prototype = { - uninit: function() { + uninit() { this.clearSandboxes(); }, - addListener: function() { + addListener() { let webProgress = this.chromeGlobal.docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); webProgress.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION); }, - removeListener: function() { + removeListener() { let webProgress = this.chromeGlobal.docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); webProgress.removeProgressListener(this); }, - onLocationChange: function(webProgress, request, location, flags) { + onLocationChange(webProgress, request, location, flags) { this.clearSandboxes(); }, - addSandbox: function(sandbox) { + addSandbox(sandbox) { if (this.sandboxes.length == 0) { this.addListener(); } this.sandboxes.push(sandbox); }, - clearSandboxes: function() { + clearSandboxes() { if (this.sandboxes.length) { this.removeListener(); } @@ -522,7 +522,7 @@ SandboxChild.prototype = { var RemoteAddonsChild = { _ready: false, - makeReady: function() { + makeReady() { let shims = [ Prefetcher, NotificationTracker, @@ -540,7 +540,7 @@ var RemoteAddonsChild = { } }, - init: function(global) { + init(global) { if (!this._ready) { if (!Services.cpmm.initialProcessData.remoteAddonsParentInitted) { @@ -551,7 +551,7 @@ var RemoteAddonsChild = { this._ready = true; } - global.sendAsyncMessage("Addons:RegisterGlobal", {}, {global: global}); + global.sendAsyncMessage("Addons:RegisterGlobal", {}, {global}); let sandboxChild = new SandboxChild(global); global.addSandbox = sandboxChild.addSandbox.bind(sandboxChild); @@ -560,7 +560,7 @@ var RemoteAddonsChild = { return [new EventTargetChild(global), sandboxChild]; }, - uninit: function(perTabShims) { + uninit(perTabShims) { for (let shim of perTabShims) { try { shim.uninit(); diff --git a/toolkit/components/addoncompat/RemoteAddonsParent.jsm b/toolkit/components/addoncompat/RemoteAddonsParent.jsm index ec2d49758ccf..5f409a832896 100644 --- a/toolkit/components/addoncompat/RemoteAddonsParent.jsm +++ b/toolkit/components/addoncompat/RemoteAddonsParent.jsm @@ -50,13 +50,13 @@ var NotificationTracker = { // given path are present in _paths. _paths: {}, - init: function() { + init() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.initialProcessData.remoteAddonsNotificationPaths = this._paths; }, - add: function(path) { + add(path) { let tracked = this._paths; for (let component of path) { tracked = setDefault(tracked, component, {}); @@ -67,10 +67,10 @@ var NotificationTracker = { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); - ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path: path, count: count}); + ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path, count}); }, - remove: function(path) { + remove(path) { let tracked = this._paths; for (let component of path) { tracked = setDefault(tracked, component, {}); @@ -79,7 +79,7 @@ var NotificationTracker = { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); - ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path: path, count: tracked._count}); + ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path, count: tracked._count}); }, }; NotificationTracker.init(); @@ -106,7 +106,7 @@ function Interposition(name, base) // content policy is added or removed. It also runs all the registered // add-on content policies when the child asks it to do so. var ContentPolicyParent = { - init: function() { + init() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:ContentPolicy:Run", this); @@ -114,17 +114,17 @@ var ContentPolicyParent = { this._policies = new Map(); }, - addContentPolicy: function(addon, name, cid) { + addContentPolicy(addon, name, cid) { this._policies.set(name, cid); NotificationTracker.add(["content-policy", addon]); }, - removeContentPolicy: function(addon, name) { + removeContentPolicy(addon, name) { this._policies.delete(name); NotificationTracker.remove(["content-policy", addon]); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "Addons:ContentPolicy:Run": return this.shouldLoad(aMessage.data, aMessage.objects); @@ -132,7 +132,7 @@ var ContentPolicyParent = { return undefined; }, - shouldLoad: function(aData, aObjects) { + shouldLoad(aData, aObjects) { for (let policyCID of this._policies.values()) { let policy; try { @@ -196,7 +196,7 @@ CategoryManagerInterposition.methods.deleteCategoryEntry = // protocol handler in the parent and we want the child to be able to // use it. This code is pretty specific to Adblock's usage. var AboutProtocolParent = { - init: function() { + init() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:AboutProtocol:GetURIFlags", this); @@ -204,12 +204,12 @@ var AboutProtocolParent = { this._protocols = []; }, - registerFactory: function(addon, class_, className, contractID, factory) { - this._protocols.push({contractID: contractID, factory: factory}); + registerFactory(addon, class_, className, contractID, factory) { + this._protocols.push({contractID, factory}); NotificationTracker.add(["about-protocol", contractID, addon]); }, - unregisterFactory: function(addon, class_, factory) { + unregisterFactory(addon, class_, factory) { for (let i = 0; i < this._protocols.length; i++) { if (this._protocols[i].factory == factory) { NotificationTracker.remove(["about-protocol", this._protocols[i].contractID, addon]); @@ -219,7 +219,7 @@ var AboutProtocolParent = { } }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Addons:AboutProtocol:GetURIFlags": return this.getURIFlags(msg); @@ -229,7 +229,7 @@ var AboutProtocolParent = { return undefined; }, - getURIFlags: function(msg) { + getURIFlags(msg) { let uri = BrowserUtils.makeURI(msg.data.uri); let contractID = msg.data.contractID; let module = Cc[contractID].getService(Ci.nsIAboutModule); @@ -243,10 +243,10 @@ var AboutProtocolParent = { // We immediately read all the data out of the channel here and // return it to the child. - openChannel: function(msg) { + openChannel(msg) { function wrapGetInterface(cpow) { return { - getInterface: function(intf) { return cpow.getInterface(intf); } + getInterface(intf) { return cpow.getInterface(intf); } }; } @@ -292,7 +292,7 @@ var AboutProtocolParent = { let stream = channel.open2(); let data = NetUtil.readInputStreamToString(stream, stream.available(), {}); return { - data: data, + data, contentType: channel.contentType }; } catch (e) { @@ -334,23 +334,23 @@ ComponentRegistrarInterposition.methods.unregisterFactory = // in the parent because there might be non-add-on T observers that // won't expect to get notified in this case. var ObserverParent = { - init: function() { + init() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:Observer:Run", this); }, - addObserver: function(addon, observer, topic, ownsWeak) { + addObserver(addon, observer, topic, ownsWeak) { Services.obs.addObserver(observer, "e10s-" + topic, ownsWeak); NotificationTracker.add(["observer", topic, addon]); }, - removeObserver: function(addon, observer, topic) { + removeObserver(addon, observer, topic) { Services.obs.removeObserver(observer, "e10s-" + topic); NotificationTracker.remove(["observer", topic, addon]); }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Addons:Observer:Run": this.notify(msg.objects.subject, msg.objects.topic, msg.objects.data); @@ -358,7 +358,7 @@ var ObserverParent = { } }, - notify: function(subject, topic, data) { + notify(subject, topic, data) { let e = Services.obs.enumerateObservers("e10s-" + topic); while (e.hasMoreElements()) { let obs = e.getNext().QueryInterface(Ci.nsIObserver); @@ -410,7 +410,7 @@ ObserverInterposition.methods.removeObserver = // This object is responsible for forwarding events from the child to // the parent. var EventTargetParent = { - init: function() { + init() { // The _listeners map goes from targets (either elements // or windows) to a dictionary from event types to listeners. this._listeners = new WeakMap(); @@ -426,7 +426,7 @@ var EventTargetParent = { // (the or elements), then we return the // . If it's some generic element, then we return the // window itself. - redirectEventTarget: function(target) { + redirectEventTarget(target) { if (Cu.isCrossProcessWrapper(target)) { return null; } @@ -456,12 +456,12 @@ var EventTargetParent = { // When a given event fires in the child, we fire it on the // element and the window since those are the two possible // results of redirectEventTarget. - getTargets: function(browser) { + getTargets(browser) { let window = browser.ownerDocument.defaultView; return [browser, window]; }, - addEventListener: function(addon, target, type, listener, useCapture, wantsUntrusted, delayedWarning) { + addEventListener(addon, target, type, listener, useCapture, wantsUntrusted, delayedWarning) { let newTarget = this.redirectEventTarget(target); if (!newTarget) { return; @@ -489,14 +489,14 @@ var EventTargetParent = { } } - forType.push({listener: listener, - target: target, - wantsUntrusted: wantsUntrusted, - useCapture: useCapture, - delayedWarning: delayedWarning}); + forType.push({listener, + target, + wantsUntrusted, + useCapture, + delayedWarning}); }, - removeEventListener: function(addon, target, type, listener, useCapture) { + removeEventListener(addon, target, type, listener, useCapture) { let newTarget = this.redirectEventTarget(target); if (!newTarget) { return; @@ -521,7 +521,7 @@ var EventTargetParent = { } }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Addons:Event:Run": this.dispatch(msg.target, msg.data.type, msg.data.capturing, @@ -530,7 +530,7 @@ var EventTargetParent = { } }, - dispatch: function(browser, type, capturing, isTrusted, prefetched, cpows) { + dispatch(browser, type, capturing, isTrusted, prefetched, cpows) { let event = cpows.event; let eventTarget = cpows.eventTarget; let targets = this.getTargets(browser); @@ -554,7 +554,7 @@ var EventTargetParent = { for (let [handler, target] of handlers) { let EventProxy = { - get: function(knownProps, name) { + get(knownProps, name) { if (knownProps.hasOwnProperty(name)) return knownProps[name]; return event[name]; @@ -563,8 +563,8 @@ var EventTargetParent = { let proxyEvent = new Proxy({ currentTarget: target, target: eventTarget, - type: type, - QueryInterface: function(iid) { + type, + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIDOMEventTarget)) return proxyEvent; @@ -698,7 +698,7 @@ function chromeGlobalForContentWindow(window) var SandboxParent = { componentsMap: new WeakMap(), - makeContentSandbox: function(addon, chromeGlobal, principals, ...rest) { + makeContentSandbox(addon, chromeGlobal, principals, ...rest) { CompatWarning.warn("This sandbox should be created from the child process.", addon, CompatWarning.warnings.sandboxes); if (rest.length) { @@ -733,7 +733,7 @@ var SandboxParent = { return sandbox; }, - evalInSandbox: function(code, sandbox, ...rest) { + evalInSandbox(code, sandbox, ...rest) { let cu = this.componentsMap.get(sandbox); return cu.evalInSandbox(code, sandbox, ...rest); } @@ -933,7 +933,7 @@ function wrapProgressListener(kind, listener) } let ListenerHandler = { - get: function(target, name) { + get(target, name) { if (name.startsWith("on")) { return function(...args) { listener[name].apply(listener, RemoteWebProgressManager.argumentsForAddonListener(kind, args)); @@ -1026,7 +1026,7 @@ RemoteWebNavigationInterposition.getters.sessionHistory = function(addon, target } var RemoteAddonsParent = { - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Addons:RegisterGlobal", this); @@ -1036,7 +1036,7 @@ var RemoteAddonsParent = { this.browserToGlobal = new WeakMap(); }, - getInterfaceInterpositions: function() { + getInterfaceInterpositions() { let result = {}; function register(intf, interp) { @@ -1052,7 +1052,7 @@ var RemoteAddonsParent = { return result; }, - getTaggedInterpositions: function() { + getTaggedInterpositions() { let result = {}; function register(tag, interp) { @@ -1069,7 +1069,7 @@ var RemoteAddonsParent = { return result; }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Addons:RegisterGlobal": this.browserToGlobal.set(msg.target, msg.objects.global); diff --git a/toolkit/components/addoncompat/ShimWaiver.jsm b/toolkit/components/addoncompat/ShimWaiver.jsm index 402ab4c32247..67db8f60f5aa 100644 --- a/toolkit/components/addoncompat/ShimWaiver.jsm +++ b/toolkit/components/addoncompat/ShimWaiver.jsm @@ -5,7 +5,7 @@ this.EXPORTED_SYMBOLS = ["ShimWaiver"]; this.ShimWaiver = { - getProperty: function(obj, prop) { + getProperty(obj, prop) { let rv = obj[prop]; if (rv instanceof Function) { rv = rv.bind(obj); diff --git a/toolkit/components/addoncompat/defaultShims.js b/toolkit/components/addoncompat/defaultShims.js index a786efed7d39..c7675cad5135 100644 --- a/toolkit/components/addoncompat/defaultShims.js +++ b/toolkit/components/addoncompat/defaultShims.js @@ -22,15 +22,15 @@ DefaultInterpositionService.prototype = { classID: Components.ID("{50bc93ce-602a-4bef-bf3a-61fc749c4caf}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonInterposition, Ci.nsISupportsWeakReference]), - getWhitelist: function() { + getWhitelist() { return []; }, - interposeProperty: function(addon, target, iid, prop) { + interposeProperty(addon, target, iid, prop) { return null; }, - interposeCall: function(addonId, originalFunc, originalThis, args) { + interposeCall(addonId, originalFunc, originalThis, args) { args.splice(0, 0, addonId); return originalFunc.apply(originalThis, args); }, diff --git a/toolkit/components/addoncompat/multiprocessShims.js b/toolkit/components/addoncompat/multiprocessShims.js index 8b252a0c484a..1e5ea4f72752 100644 --- a/toolkit/components/addoncompat/multiprocessShims.js +++ b/toolkit/components/addoncompat/multiprocessShims.js @@ -102,13 +102,13 @@ AddonInterpositionService.prototype = { classID: Components.ID("{1363d5f0-d95e-11e3-9c1a-0800200c9a66}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonInterposition, Ci.nsISupportsWeakReference]), - getWhitelist: function() { + getWhitelist() { return this._whitelist; }, // When the interface is not known for a method call, this code // determines the type of the target object. - getObjectTag: function(target) { + getObjectTag(target) { if (Cu.isCrossProcessWrapper(target)) { return Cu.getCrossProcessWrapperTag(target); } @@ -134,7 +134,7 @@ AddonInterpositionService.prototype = { return "generic"; }, - interposeProperty: function(addon, target, iid, prop) { + interposeProperty(addon, target, iid, prop) { let interp; if (iid) { interp = this._interfaceInterpositions[iid]; @@ -173,7 +173,7 @@ AddonInterpositionService.prototype = { return Prefetcher.lookupInCache(addon, target, prop); }, - interposeCall: function(addonId, originalFunc, originalThis, args) { + interposeCall(addonId, originalFunc, originalThis, args) { args.splice(0, 0, addonId); return originalFunc.apply(originalThis, args); }, diff --git a/toolkit/components/addoncompat/tests/addon/bootstrap.js b/toolkit/components/addoncompat/tests/addon/bootstrap.js index 5e69fee22cf9..1364346bfed7 100644 --- a/toolkit/components/addoncompat/tests/addon/bootstrap.js +++ b/toolkit/components/addoncompat/tests/addon/bootstrap.js @@ -283,7 +283,7 @@ function testAboutModuleRegistration() } TestChannel.prototype = { - asyncOpen: function(listener, context) { + asyncOpen(listener, context) { let stream = this.open(); let runnable = { run: () => { @@ -301,13 +301,13 @@ function testAboutModuleRegistration() Services.tm.currentThread.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL); }, - asyncOpen2: function(listener) { + asyncOpen2(listener) { // throws an error if security checks fail var outListener = contentSecManager.performSecurityCheck(this, listener); return this.asyncOpen(outListener, null); }, - open: function() { + open() { function getWindow(channel) { try { @@ -334,22 +334,22 @@ function testAboutModuleRegistration() return stream; }, - open2: function() { + open2() { // throws an error if security checks fail contentSecManager.performSecurityCheck(this, null); return this.open(); }, - isPending: function() { + isPending() { return false; }, - cancel: function() { + cancel() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - suspend: function() { + suspend() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - resume: function() { + resume() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, @@ -391,7 +391,7 @@ function testAboutModuleRegistration() }; let factory = { - createInstance: function(outer, iid) { + createInstance(outer, iid) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -519,7 +519,7 @@ function testProgressListener() let sawTabsLocChange = false; let globalListener = { - onLocationChange: function(webProgress, request, uri) { + onLocationChange(webProgress, request, uri) { if (uri.spec == url) { sawGlobalLocChange = true; ok(request instanceof Ci.nsIHttpChannel, "Global listener channel is an HTTP channel"); @@ -528,7 +528,7 @@ function testProgressListener() }; let tabsListener = { - onLocationChange: function(browser, webProgress, request, uri) { + onLocationChange(browser, webProgress, request, uri) { if (uri.spec == url) { sawTabsLocChange = true; ok(request instanceof Ci.nsIHttpChannel, "Tab listener channel is an HTTP channel"); diff --git a/toolkit/components/addoncompat/tests/browser/browser_addonShims.js b/toolkit/components/addoncompat/tests/browser/browser_addonShims.js index ca28782cd0c6..d2326ac16206 100644 --- a/toolkit/components/addoncompat/tests/browser/browser_addonShims.js +++ b/toolkit/components/addoncompat/tests/browser/browser_addonShims.js @@ -14,7 +14,7 @@ function addAddon(url) AddonManager.getInstallForURL(url, installer => { installer.install(); let listener = { - onInstallEnded: function(addon, addonInstall) { + onInstallEnded(addon, addonInstall) { installer.removeListener(listener); // Wait for add-on's startup scripts to execute. See bug 997408 @@ -36,7 +36,7 @@ function removeAddon(addon) return new Promise(function(resolve, reject) { let listener = { - onUninstalled: function(uninstalledAddon) { + onUninstalled(uninstalledAddon) { if (uninstalledAddon != addon) { return; } @@ -53,12 +53,12 @@ add_task(function* test_addon_shims() { yield SpecialPowers.pushPrefEnv({set: [["dom.ipc.shims.enabledWarnings", true]]}); let addon = yield addAddon(ADDON_URL); - yield window.runAddonShimTests({ok: ok, is: is, info: info}); + yield window.runAddonShimTests({ok, is, info}); yield removeAddon(addon); if (Services.appinfo.browserTabsRemoteAutostart) { addon = yield addAddon(COMPAT_ADDON_URL); - yield window.runAddonTests({ok: ok, is: is, info: info}); + yield window.runAddonTests({ok, is, info}); yield removeAddon(addon); } }); diff --git a/toolkit/components/asyncshutdown/AsyncShutdown.jsm b/toolkit/components/asyncshutdown/AsyncShutdown.jsm index 8a341edb1ba4..755cffbf1a01 100644 --- a/toolkit/components/asyncshutdown/AsyncShutdown.jsm +++ b/toolkit/components/asyncshutdown/AsyncShutdown.jsm @@ -53,7 +53,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task", XPCOMUtils.defineLazyServiceGetter(this, "gDebug", "@mozilla.org/xpcom/debug;1", "nsIDebug2"); Object.defineProperty(this, "gCrashReporter", { - get: function() { + get() { delete this.gCrashReporter; try { let reporter = Cc["@mozilla.org/xre/app-info;1"]. @@ -116,7 +116,7 @@ PromiseSet.prototype = { * @return {Promise} Resolved once all Promise have been resolved or removed, * or rejected after at least one Promise has rejected. */ - wait: function() { + wait() { // Pick an arbitrary element in the map, if any exists. let entry = this._indirections.entries().next(); if (entry.done) { @@ -139,7 +139,7 @@ PromiseSet.prototype = { * Calls to wait (including ongoing calls) will only return once * `key` has either resolved or been removed. */ - add: function(key) { + add(key) { this._ensurePromise(key); let indirection = PromiseUtils.defer(); key.then( @@ -163,7 +163,7 @@ PromiseSet.prototype = { * Calls to wait (including ongoing calls) will ignore this promise, * unless it is added again. */ - delete: function(key) { + delete(key) { this._ensurePromise(key); let value = this._indirections.get(key); if (!value) { @@ -174,7 +174,7 @@ PromiseSet.prototype = { return true; }, - _ensurePromise: function(key) { + _ensurePromise(key) { if (!key || typeof key != "object") { throw new Error("Expected an object"); } @@ -335,9 +335,9 @@ function getOrigin(topFrame, filename = null, lineNumber = null, stack = null) { } return { - filename: filename, - lineNumber: lineNumber, - stack: stack, + filename, + lineNumber, + stack, }; } catch (ex) { return { @@ -436,7 +436,7 @@ function getPhase(topic) { * // No specific guarantee about completion of profileBeforeChange * }); */ - addBlocker: function(name, condition, details = null) { + addBlocker(name, condition, details = null) { spinner.addBlocker(name, condition, details); }, /** @@ -451,7 +451,7 @@ function getPhase(topic) { * the blocker has never been installed or that the phase has * completed and the blocker has already been resolved. */ - removeBlocker: function(condition) { + removeBlocker(condition) { return spinner.removeBlocker(condition); }, @@ -499,7 +499,7 @@ Spinner.prototype = { * See the documentation of `addBlocker` in property `client` * of instances of `Barrier`. */ - addBlocker: function(name, condition, details) { + addBlocker(name, condition, details) { this._barrier.client.addBlocker(name, condition, details); }, /** @@ -513,7 +513,7 @@ Spinner.prototype = { * the blocker has never been installed or that the phase has * completed and the blocker has already been resolved. */ - removeBlocker: function(condition) { + removeBlocker(condition) { return this._barrier.client.removeBlocker(condition); }, @@ -522,7 +522,7 @@ Spinner.prototype = { }, // nsIObserver.observe - observe: function() { + observe() { let topic = this._topic; debug(`Starting phase ${ topic }`); Services.obs.removeObserver(this, topic); @@ -751,10 +751,10 @@ function Barrier(name) { } let blocker = { - trigger: trigger, - promise: promise, - name: name, - fetchState: fetchState, + trigger, + promise, + name, + fetchState, getOrigin: () => getOrigin(topFrame, filename, lineNumber, stack), }; @@ -810,11 +810,11 @@ Barrier.prototype = Object.freeze({ let {name, fetchState} = blocker; let {stack, filename, lineNumber} = blocker.getOrigin(); frozen.push({ - name: name, + name, state: safeGetState(fetchState), - filename: filename, - lineNumber: lineNumber, - stack: stack + filename, + lineNumber, + stack }); } return frozen; @@ -842,14 +842,14 @@ Barrier.prototype = Object.freeze({ * * @return {Promise} A promise satisfied once all blockers are complete. */ - wait: function(options = {}) { + wait(options = {}) { // This method only implements caching on top of _wait() if (this._promise) { return this._promise; } return this._promise = this._wait(options); }, - _wait: function(options) { + _wait(options) { // Sanity checks if (this._isStarted) { @@ -990,7 +990,7 @@ Barrier.prototype = Object.freeze({ return promise; }, - _removeBlocker: function(condition) { + _removeBlocker(condition) { if (!this._waitForMe || !this._promiseToBlocker || !this._conditionToPromise) { // We have already cleaned up everything. return false; diff --git a/toolkit/components/asyncshutdown/nsAsyncShutdown.js b/toolkit/components/asyncshutdown/nsAsyncShutdown.js index bd2c9a2fdf3a..349fd175d3a3 100644 --- a/toolkit/components/asyncshutdown/nsAsyncShutdown.js +++ b/toolkit/components/asyncshutdown/nsAsyncShutdown.js @@ -27,7 +27,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task", */ var PropertyBagConverter = { // From nsIPropertyBag to JS - toObject: function(bag) { + toObject(bag) { if (!(bag instanceof Ci.nsIPropertyBag)) { throw new TypeError("Not a property bag"); } @@ -40,7 +40,7 @@ var PropertyBagConverter = { } return result; }, - toValue: function(property) { + toValue(property) { if (typeof property != "object") { return property; } @@ -54,7 +54,7 @@ var PropertyBagConverter = { }, // From JS to nsIPropertyBag - fromObject: function(obj) { + fromObject(obj) { if (obj == null || typeof obj != "object") { throw new TypeError("Invalid object: " + obj); } @@ -66,7 +66,7 @@ var PropertyBagConverter = { } return bag; }, - fromValue: function(value) { + fromValue(value) { if (typeof value == "function") { return null; // Emulating the behavior of JSON.stringify with functions } @@ -100,7 +100,7 @@ function nsAsyncShutdownClient(moduleClient) { this._byName = new Map(); } nsAsyncShutdownClient.prototype = { - _getPromisified: function(xpcomBlocker) { + _getPromisified(xpcomBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate) { return null; @@ -110,7 +110,7 @@ nsAsyncShutdownClient.prototype = { } return null; }, - _setPromisified: function(xpcomBlocker, moduleBlocker) { + _setPromisified(xpcomBlocker, moduleBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate) { this._byName.set(xpcomBlocker.name, {xpcom: xpcomBlocker, @@ -122,7 +122,7 @@ nsAsyncShutdownClient.prototype = { } throw new Error("We have already registered a distinct blocker with the same name: " + xpcomBlocker.name); }, - _deletePromisified: function(xpcomBlocker) { + _deletePromisified(xpcomBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate || candidate.xpcom !== xpcomBlocker) { return false; @@ -136,7 +136,7 @@ nsAsyncShutdownClient.prototype = { get name() { return this._moduleClient.name; }, - addBlocker: function(/* nsIAsyncShutdownBlocker*/ xpcomBlocker, + addBlocker(/* nsIAsyncShutdownBlocker*/ xpcomBlocker, fileName, lineNumber, stack) { // We need a Promise-based function with the same behavior as // `xpcomBlocker`. Furthermore, to support `removeBlocker`, we @@ -171,12 +171,12 @@ nsAsyncShutdownClient.prototype = { return null; }, filename: fileName, - lineNumber: lineNumber, - stack: stack, + lineNumber, + stack, }); }, - removeBlocker: function(xpcomBlocker) { + removeBlocker(xpcomBlocker) { let moduleBlocker = this._getPromisified(xpcomBlocker); if (!moduleBlocker) { return false; @@ -210,7 +210,7 @@ nsAsyncShutdownBarrier.prototype = { get client() { return this._client; }, - wait: function(onReady) { + wait(onReady) { this._moduleBarrier.wait().then(() => { onReady.done(); }); @@ -242,7 +242,7 @@ function nsAsyncShutdownService() { let k = _k; Object.defineProperty(this, k, { configurable: true, - get: function() { + get() { delete this[k]; let wrapped = AsyncShutdown[k]; // May be undefined, if we're on the wrong process. let result = wrapped ? new nsAsyncShutdownClient(wrapped) : undefined; @@ -260,7 +260,7 @@ function nsAsyncShutdownService() { }; } nsAsyncShutdownService.prototype = { - makeBarrier: function(name) { + makeBarrier(name) { return new nsAsyncShutdownBarrier(new AsyncShutdown.Barrier(name)); }, diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/head.js b/toolkit/components/asyncshutdown/tests/xpcshell/head.js index 9de489808d91..735dea9fa5fc 100644 --- a/toolkit/components/asyncshutdown/tests/xpcshell/head.js +++ b/toolkit/components/asyncshutdown/tests/xpcshell/head.js @@ -37,13 +37,13 @@ function makeLock(kind) { let topic = "test-Phase-" + ++makeLock.counter; let phase = AsyncShutdown._getPhase(topic); return { - addBlocker: function(...args) { + addBlocker(...args) { return phase.addBlocker(...args); }, - removeBlocker: function(blocker) { + removeBlocker(blocker) { return phase.removeBlocker(blocker); }, - wait: function() { + wait() { Services.obs.notifyObservers(null, topic, null); return Promise.resolve(); } @@ -54,7 +54,7 @@ function makeLock(kind) { return { addBlocker: barrier.client.addBlocker, removeBlocker: barrier.client.removeBlocker, - wait: function() { + wait() { return barrier.wait(); } }; @@ -62,7 +62,7 @@ function makeLock(kind) { let name = "test-xpcom-Barrier-" + ++makeLock.counter; let barrier = asyncShutdownService.makeBarrier(name); return { - addBlocker: function(blockerName, condition, state) { + addBlocker(blockerName, condition, state) { if (condition == null) { // Slight trick as `null` or `undefined` cannot be used as keys // for `xpcomMap`. Note that this has no incidence on the result @@ -74,8 +74,8 @@ function makeLock(kind) { if (!blocker) { blocker = { name: blockerName, - state: state, - blockShutdown: function(aBarrierClient) { + state, + blockShutdown(aBarrierClient) { return Task.spawn(function*() { try { if (typeof condition == "function") { @@ -94,14 +94,14 @@ function makeLock(kind) { let {fileName, lineNumber, stack} = (new Error()); return barrier.client.addBlocker(blocker, fileName, lineNumber, stack); }, - removeBlocker: function(condition) { + removeBlocker(condition) { let blocker = makeLock.xpcomMap.get(condition); if (!blocker) { return; } barrier.client.removeBlocker(blocker); }, - wait: function() { + wait() { return new Promise(resolve => { barrier.wait(resolve); }); @@ -114,7 +114,7 @@ function makeLock(kind) { return { addBlocker: client.addBlocker, removeBlocker: client.removeBlocker, - wait: function() { + wait() { return new Promise(resolve => { barrier.wait(resolve); }); diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js index 33da1f53fbd4..9df2425ba26a 100644 --- a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js +++ b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js @@ -27,7 +27,7 @@ add_task(function* test_phase_simple_async() { throw new Error("State BOOM"); }], [function() { return { - toJSON: function() { + toJSON() { throw new Error("State.toJSON BOOM"); } }; diff --git a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js index 478f4d4d13f0..581ca77a8d81 100644 --- a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js +++ b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js @@ -37,7 +37,7 @@ AutoCompleteInputBase.prototype = { get selectionEnd() { return this._selEnd; }, - selectTextRange: function(aStart, aEnd) { + selectTextRange(aStart, aEnd) { this._selStart = aStart; this._selEnd = aEnd; }, @@ -46,12 +46,12 @@ AutoCompleteInputBase.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, @@ -89,31 +89,31 @@ AutoCompleteResultBase.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this._finalCompleteValues[aIndex] || this._values[aIndex]; }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteResult]) @@ -135,7 +135,7 @@ AutoCompleteSearchBase.prototype = { // AutoCompleteResult _result: null, - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) { @@ -145,14 +145,14 @@ AutoCompleteSearchBase.prototype = { aListener.onSearchResult(this, result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory, Ci.nsIAutoCompleteSearch]), // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_330578.js b/toolkit/components/autocomplete/tests/unit/test_330578.js index c422dbb6a0c8..29b368269aab 100644 --- a/toolkit/components/autocomplete/tests/unit/test_330578.js +++ b/toolkit/components/autocomplete/tests/unit/test_330578.js @@ -9,7 +9,7 @@ var gResultListener = { _lastValue: "", _lastRemoveFromDb: false, - onValueRemoved: function(aResult, aValue, aRemoveFromDb) { + onValueRemoved(aResult, aValue, aRemoveFromDb) { this._lastResult = aResult; this._lastValue = aValue; this._lastRemoveFromDb = aRemoveFromDb; diff --git a/toolkit/components/autocomplete/tests/unit/test_378079.js b/toolkit/components/autocomplete/tests/unit/test_378079.js index b8b734884187..b5ac52e0ac80 100644 --- a/toolkit/components/autocomplete/tests/unit/test_378079.js +++ b/toolkit/components/autocomplete/tests/unit/test_378079.js @@ -37,21 +37,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -61,7 +61,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -103,34 +103,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -162,7 +162,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_393191.js b/toolkit/components/autocomplete/tests/unit/test_393191.js index 750bcbd9abb4..ce32b4261787 100644 --- a/toolkit/components/autocomplete/tests/unit/test_393191.js +++ b/toolkit/components/autocomplete/tests/unit/test_393191.js @@ -36,21 +36,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -60,7 +60,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -102,34 +102,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -161,7 +161,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -169,10 +169,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -182,7 +182,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_440866.js b/toolkit/components/autocomplete/tests/unit/test_440866.js index e42dd8831c90..558ac78b7d29 100644 --- a/toolkit/components/autocomplete/tests/unit/test_440866.js +++ b/toolkit/components/autocomplete/tests/unit/test_440866.js @@ -35,21 +35,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -59,7 +59,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -101,34 +101,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -160,7 +160,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -168,10 +168,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -181,7 +181,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js index 15274140fcd4..6186df34d8f4 100644 --- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js +++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js @@ -30,21 +30,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -54,7 +54,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -90,34 +90,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -149,7 +149,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_previousResult.js b/toolkit/components/autocomplete/tests/unit/test_previousResult.js index a9c6da31a4b2..0367f782de14 100644 --- a/toolkit/components/autocomplete/tests/unit/test_previousResult.js +++ b/toolkit/components/autocomplete/tests/unit/test_previousResult.js @@ -36,21 +36,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -60,7 +60,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -101,34 +101,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -161,7 +161,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js index 0972092bb63e..4ef0294b73bc 100644 --- a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js +++ b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js @@ -32,14 +32,14 @@ AutoCompleteInput.prototype = { set popupOpen(val) { return val; }, // ignore get popupOpen() { return false; }, get searchCount() { return this.searches.length; }, - getSearchAt: function(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, - onTextReverted: function() {}, - onTextEntered: function() {}, + getSearchAt(aIndex) { return this.searches[aIndex]; }, + onSearchBegin() {}, + onSearchComplete() {}, + onTextReverted() {}, + onTextEntered() {}, popup: { - selectBy: function() {}, - invalidate: function() {}, + selectBy() {}, + invalidate() {}, set selectedIndex(val) { return val; }, // ignore get selectedIndex() { return -1 }, QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup]) @@ -58,13 +58,13 @@ function AutoCompleteSearch(aName) AutoCompleteSearch.prototype = { constructor: AutoCompleteSearch, stopSearchInvoked: true, - startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) { print("Check stop search has been called"); do_check_true(this.stopSearchInvoked); this.stopSearchInvoked = false; }, - stopSearch: function() + stopSearch() { this.stopSearchInvoked = true; }, @@ -72,7 +72,7 @@ AutoCompleteSearch.prototype = { Ci.nsIFactory , Ci.nsIAutoCompleteSearch ]), - createInstance: function(outer, iid) + createInstance(outer, iid) { return this.QueryInterface(iid); } diff --git a/toolkit/components/captivedetect/captivedetect.js b/toolkit/components/captivedetect/captivedetect.js index f347736b39aa..4362f8e790d7 100644 --- a/toolkit/components/captivedetect/captivedetect.js +++ b/toolkit/components/captivedetect/captivedetect.js @@ -66,9 +66,9 @@ function URLFetcher(url, timeout) { URLFetcher.prototype = { _isAborted: false, - ontimeout: function() {}, - onerror: function() {}, - abort: function() { + ontimeout() {}, + onerror() {}, + abort() { if (!this._isAborted) { this._isAborted = true; this._xhr.abort(); @@ -339,7 +339,7 @@ CaptivePortalDetector.prototype = { let id = this._allocateRequestId(); let details = { type: kOpenCaptivePortalLoginEvent, - id: id, + id, url: this._canonicalSiteURL, }; this._loginObserver.attach(); diff --git a/toolkit/components/contentprefs/ContentPrefService2.jsm b/toolkit/components/contentprefs/ContentPrefService2.jsm index 5d4287897024..69180fe13101 100644 --- a/toolkit/components/contentprefs/ContentPrefService2.jsm +++ b/toolkit/components/contentprefs/ContentPrefService2.jsm @@ -418,7 +418,7 @@ ContentPrefService2.prototype = { }, // Deletes settings and groups that are no longer used. - _settingsAndGroupsCleanupStmts: function() { + _settingsAndGroupsCleanupStmts() { // The NOTNULL term in the subquery of the second statment is needed because of // SQLite's weird IN behavior vis-a-vis NULLs. See http://sqlite.org/lang_expr.html. return [ diff --git a/toolkit/components/contentprefs/ContentPrefServiceChild.jsm b/toolkit/components/contentprefs/ContentPrefServiceChild.jsm index ea1f969dfd64..cad1c71caf67 100644 --- a/toolkit/components/contentprefs/ContentPrefServiceChild.jsm +++ b/toolkit/components/contentprefs/ContentPrefServiceChild.jsm @@ -31,18 +31,18 @@ function CallbackCaller(callback) { } CallbackCaller.prototype = { - handleResult: function(contentPref) { + handleResult(contentPref) { cbHandleResult(this._callback, new ContentPref(contentPref.domain, contentPref.name, contentPref.value)); }, - handleError: function(result) { + handleError(result) { cbHandleError(this._callback, result); }, - handleCompletion: function(reason) { + handleCompletion(reason) { cbHandleCompletion(this._callback, reason); }, }; @@ -56,7 +56,7 @@ var ContentPrefServiceChild = { _mm: Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsIMessageSender), - _getRandomId: function() { + _getRandomId() { return Cc["@mozilla.org/uuid-generator;1"] .getService(Ci.nsIUUIDGenerator).generateUUID().toString(); }, @@ -64,13 +64,13 @@ var ContentPrefServiceChild = { // Map from random ID string -> CallbackCaller, per request _requests: new Map(), - init: function() { + init() { this._mm.addMessageListener("ContentPrefs:HandleResult", this); this._mm.addMessageListener("ContentPrefs:HandleError", this); this._mm.addMessageListener("ContentPrefs:HandleCompletion", this); }, - receiveMessage: function(msg) { + receiveMessage(msg) { let data = msg.data; let callback; switch (msg.name) { @@ -104,34 +104,34 @@ var ContentPrefServiceChild = { } }, - _callFunction: function(call, args, callback) { + _callFunction(call, args, callback) { let requestId = this._getRandomId(); - let data = { call: call, args: args, requestId: requestId }; + let data = { call, args, requestId }; this._mm.sendAsyncMessage("ContentPrefs:FunctionCall", data); this._requests.set(requestId, new CallbackCaller(callback)); }, - getByName: function(name, context, callback) { + getByName(name, context, callback) { return this._callFunction("getByName", [ name, contextArg(context) ], callback); }, - getByDomainAndName: function(domain, name, context, callback) { + getByDomainAndName(domain, name, context, callback) { return this._callFunction("getByDomainAndName", [ domain, name, contextArg(context) ], callback); }, - getBySubdomainAndName: function(domain, name, context, callback) { + getBySubdomainAndName(domain, name, context, callback) { return this._callFunction("getBySubdomainAndName", [ domain, name, contextArg(context) ], callback); }, - getGlobal: function(name, context, callback) { + getGlobal(name, context, callback) { return this._callFunction("getGlobal", [ name, contextArg(context) ], callback); @@ -141,59 +141,59 @@ var ContentPrefServiceChild = { getCachedBySubdomainAndName: NYI, getCachedGlobal: NYI, - set: function(domain, name, value, context, callback) { + set(domain, name, value, context, callback) { this._callFunction("set", [ domain, name, value, contextArg(context) ], callback); }, - setGlobal: function(name, value, context, callback) { + setGlobal(name, value, context, callback) { this._callFunction("setGlobal", [ name, value, contextArg(context) ], callback); }, - removeByDomainAndName: function(domain, name, context, callback) { + removeByDomainAndName(domain, name, context, callback) { this._callFunction("removeByDomainAndName", [ domain, name, contextArg(context) ], callback); }, - removeBySubdomainAndName: function(domain, name, context, callback) { + removeBySubdomainAndName(domain, name, context, callback) { this._callFunction("removeBySubdomainAndName", [ domain, name, contextArg(context) ], callback); }, - removeGlobal: function(name, context, callback) { + removeGlobal(name, context, callback) { this._callFunction("removeGlobal", [ name, contextArg(context) ], callback); }, - removeByDomain: function(domain, context, callback) { + removeByDomain(domain, context, callback) { this._callFunction("removeByDomain", [ domain, contextArg(context) ], callback); }, - removeBySubdomain: function(domain, context, callback) { + removeBySubdomain(domain, context, callback) { this._callFunction("removeBySubdomain", [ domain, contextArg(context) ], callback); }, - removeByName: function(name, context, callback) { + removeByName(name, context, callback) { this._callFunction("removeByName", [ name, value, contextArg(context) ], callback); }, - removeAllDomains: function(context, callback) { + removeAllDomains(context, callback) { this._callFunction("removeAllDomains", [ contextArg(context) ], callback); }, - removeAllGlobals: function(context, callback) { + removeAllGlobals(context, callback) { this._callFunction("removeAllGlobals", [ contextArg(context) ], callback); }, - addObserverForName: function(name, observer) { + addObserverForName(name, observer) { let set = this._observers.get(name); if (!set) { set = new Set(); @@ -204,14 +204,14 @@ var ContentPrefServiceChild = { // This is the first observer for this name. Start listening for changes // to it. - this._mm.sendAsyncMessage("ContentPrefs:AddObserverForName", { name: name }); + this._mm.sendAsyncMessage("ContentPrefs:AddObserverForName", { name }); this._observers.set(name, set); } set.add(observer); }, - removeObserverForName: function(name, observer) { + removeObserverForName(name, observer) { let set = this._observers.get(name); if (!set) return; @@ -219,7 +219,7 @@ var ContentPrefServiceChild = { set.delete(observer); if (set.size === 0) { // This was the last observer for this name. Stop listening for changes. - this._mm.sendAsyncMessage("ContentPrefs:RemoveObserverForName", { name: name }); + this._mm.sendAsyncMessage("ContentPrefs:RemoveObserverForName", { name }); this._observers.delete(name); if (this._observers.size === 0) { diff --git a/toolkit/components/contentprefs/ContentPrefServiceParent.jsm b/toolkit/components/contentprefs/ContentPrefServiceParent.jsm index f4b02f018ace..e0cb15e58491 100644 --- a/toolkit/components/contentprefs/ContentPrefServiceParent.jsm +++ b/toolkit/components/contentprefs/ContentPrefServiceParent.jsm @@ -14,7 +14,7 @@ const Cu = Components.utils; var ContentPrefServiceParent = { _cps2: null, - init: function() { + init() { let globalMM = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageListenerManager); @@ -32,7 +32,7 @@ var ContentPrefServiceParent = { // Map from message manager -> content pref observer. _observers: new Map(), - handleObserverChange: function(msg) { + handleObserverChange(msg) { let observer = this._observers.get(msg.target); if (msg.name === "child-process-shutdown") { // If we didn't have any observers for this child process, don't do @@ -54,15 +54,15 @@ var ContentPrefServiceParent = { // observers for the same name. if (!observer) { observer = { - onContentPrefSet: function(group, name, value, isPrivate) { + onContentPrefSet(group, name, value, isPrivate) { msg.target.sendAsyncMessage("ContentPrefs:NotifyObservers", - { name: name, callback: "onContentPrefSet", + { name, callback: "onContentPrefSet", args: [ group, name, value, isPrivate ] }); }, - onContentPrefRemoved: function(group, name, isPrivate) { + onContentPrefRemoved(group, name, isPrivate) { msg.target.sendAsyncMessage("ContentPrefs:NotifyObservers", - { name: name, callback: "onContentPrefRemoved", + { name, callback: "onContentPrefRemoved", args: [ group, name, isPrivate ] }); }, @@ -92,16 +92,16 @@ var ContentPrefServiceParent = { } }, - receiveMessage: function(msg) { + receiveMessage(msg) { let data = msg.data; let args = data.args; let requestId = data.requestId; let listener = { - handleResult: function(pref) { + handleResult(pref) { msg.target.sendAsyncMessage("ContentPrefs:HandleResult", - { requestId: requestId, + { requestId, contentPref: { domain: pref.domain, name: pref.name, @@ -110,15 +110,15 @@ var ContentPrefServiceParent = { }); }, - handleError: function(error) { + handleError(error) { msg.target.sendAsyncMessage("ContentPrefs:HandleError", - { requestId: requestId, - error: error }); + { requestId, + error }); }, - handleCompletion: function(reason) { + handleCompletion(reason) { msg.target.sendAsyncMessage("ContentPrefs:HandleCompletion", - { requestId: requestId, - reason: reason }); + { requestId, + reason }); } }; diff --git a/toolkit/components/contentprefs/nsContentPrefService.js b/toolkit/components/contentprefs/nsContentPrefService.js index 4f5726e6ea44..8e92432e9f2c 100644 --- a/toolkit/components/contentprefs/nsContentPrefService.js +++ b/toolkit/components/contentprefs/nsContentPrefService.js @@ -580,7 +580,7 @@ ContentPrefService.prototype = { return this.__stmtSelectPref; }, - _scheduleCallback: function(func) { + _scheduleCallback(func) { let tm = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); tm.mainThread.dispatch(func, Ci.nsIThread.DISPATCH_NORMAL); }, @@ -602,7 +602,7 @@ ContentPrefService.prototype = { if (aCallback) { let cache = this._cache; - new AsyncStatement(this._stmtSelectPref).execute({onResult: function(aResult) { + new AsyncStatement(this._stmtSelectPref).execute({onResult(aResult) { cache.set(aGroup, aSetting, aResult); aCallback.onResult(aResult); }}); @@ -651,7 +651,7 @@ ContentPrefService.prototype = { if (aCallback) { let cache = this._cache; - new AsyncStatement(this._stmtSelectGlobalPref).execute({onResult: function(aResult) { + new AsyncStatement(this._stmtSelectGlobalPref).execute({onResult(aResult) { cache.set(null, aName, aResult); aCallback.onResult(aResult); }}); @@ -1309,19 +1309,19 @@ AsyncStatement.prototype = { stmt.executeAsync({ _callback: aCallback, _hadResult: false, - handleResult: function(aResult) { + handleResult(aResult) { this._hadResult = true; if (this._callback) { let row = aResult.getNextRow(); this._callback.onResult(row.getResultByName("value")); } }, - handleCompletion: function(aReason) { + handleCompletion(aReason) { if (!this._hadResult && this._callback && aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) this._callback.onResult(undefined); }, - handleError: function(aError) {} + handleError(aError) {} }); } }; diff --git a/toolkit/components/contentprefs/tests/unit/test_bug679784.js b/toolkit/components/contentprefs/tests/unit/test_bug679784.js index 97251d87ba9c..123c8712acb7 100644 --- a/toolkit/components/contentprefs/tests/unit/test_bug679784.js +++ b/toolkit/components/contentprefs/tests/unit/test_bug679784.js @@ -5,11 +5,11 @@ var prefObserver = { setCalledNum: 0, - onContentPrefSet: function(aGroup, aName, aValue) { + onContentPrefSet(aGroup, aName, aValue) { this.setCalledNum++; }, removedCalledNum: 0, - onContentPrefRemoved: function(aGroup, aName) { + onContentPrefRemoved(aGroup, aName) { this.removedCalledNum++; } }; diff --git a/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js b/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js index 27d239f793f5..826619ed740d 100644 --- a/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js +++ b/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js @@ -18,7 +18,7 @@ function run_test() { function testCallbackObj() { cps.getPref(uri, "asynctest", { - onResult: function(aValue) { + onResult(aValue) { do_check_eq(aValue, "pie"); cps.removePref(uri, "asynctest"); testNoResult(); diff --git a/toolkit/components/contentprefs/tests/unit_cps2/head.js b/toolkit/components/contentprefs/tests/unit_cps2/head.js index 6ce75d997753..50cc9ae37622 100644 --- a/toolkit/components/contentprefs/tests/unit_cps2/head.js +++ b/toolkit/components/contentprefs/tests/unit_cps2/head.js @@ -25,7 +25,7 @@ function runAsyncTests(tests, dontResetBefore = false) { Cu.import("resource://test/AsyncRunner.jsm", s); asyncRunner = new s.AsyncRunner({ done: do_test_finished, - error: function(err) { + error(err) { // xpcshell test functions like equal throw NS_ERROR_ABORT on // failure. Ignore those and catch only uncaught exceptions. if (err !== Cr.NS_ERROR_ABORT) { @@ -36,7 +36,7 @@ function runAsyncTests(tests, dontResetBefore = false) { do_throw(err); } }, - consoleError: function(scriptErr) { + consoleError(scriptErr) { // Previously, this code checked for console errors related to the test, // and treated them as failures. This was problematic, because our current // very-broken exception reporting machinery in XPCWrappedJSClass reports @@ -138,10 +138,10 @@ function setWithDate(group, name, val, timestamp, context) { stmt.params.group = group; stmt.executeAsync({ - handleCompletion: function(reason) { + handleCompletion(reason) { next(); }, - handleError: function(err) { + handleError(err) { do_throw(err); } }); @@ -164,14 +164,14 @@ function getDate(group, name, context) { let res; stmt.executeAsync({ - handleResult: function(results) { + handleResult(results) { let row = results.getNextRow(); res = row.getResultByName("timestamp"); }, - handleCompletion: function(reason) { + handleCompletion(reason) { next(res * 1000); }, - handleError: function(err) { + handleError(err) { do_throw(err); } }); @@ -336,17 +336,17 @@ function dbOK(expectedRows) { let cols = ["grp", "name", "value"]; db.executeAsync([stmt], 1, { - handleCompletion: function(reason) { + handleCompletion(reason) { arraysOfArraysOK(actualRows, expectedRows); next(); }, - handleResult: function(results) { + handleResult(results) { let row = null; while (row = results.getNextRow()) { actualRows.push(cols.map(c => row.getResultByName(c))); } }, - handleError: function(err) { + handleError(err) { do_throw(err); } }); @@ -355,7 +355,7 @@ function dbOK(expectedRows) { function on(event, names, dontRemove) { let args = { - reset: function() { + reset() { for (let prop in this) { if (Array.isArray(this[prop])) this[prop].splice(0, this[prop].length); diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js b/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js index 0fdc3b7adf32..546ff0b2bd2b 100644 --- a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js +++ b/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js @@ -143,7 +143,7 @@ var tests = [ // (3) Set the pref to a new value but don't wait for it to finish. cps.set("a.com", "foo", 2, null, { - handleCompletion: function() { + handleCompletion() { // (6) The pref should be cached after setting it. getCachedOK(["a.com", "foo"], true, 2); }, @@ -155,10 +155,10 @@ var tests = [ // (5) Call getByDomainAndName. var fetchedPref; cps.getByDomainAndName("a.com", "foo", null, { - handleResult: function(pref) { + handleResult(pref) { fetchedPref = pref; }, - handleCompletion: function() { + handleCompletion() { // (7) Finally, this callback should be called after set's above. do_check_true(!!fetchedPref); do_check_eq(fetchedPref.value, 2); diff --git a/toolkit/components/crashes/CrashManager.jsm b/toolkit/components/crashes/CrashManager.jsm index 1df8ed739db9..65216391c8d8 100644 --- a/toolkit/components/crashes/CrashManager.jsm +++ b/toolkit/components/crashes/CrashManager.jsm @@ -262,7 +262,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return Promise */ - pendingDumps: function() { + pendingDumps() { return this._getDirectoryEntries(this._pendingDumpsDir, this.DUMP_REGEX); }, @@ -286,7 +286,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return Promise */ - submittedDumps: function() { + submittedDumps() { return this._getDirectoryEntries(this._submittedDumpsDir, this.SUBMITTED_REGEX); }, @@ -306,7 +306,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return promise The number of event files that were examined. */ - aggregateEventsFiles: function() { + aggregateEventsFiles() { if (this._aggregatePromise) { return this._aggregatePromise; } @@ -389,7 +389,7 @@ this.CrashManager.prototype = Object.freeze({ * (Date) The cutoff point for pruning. Crashes without data newer * than this will be pruned. */ - pruneOldCrashes: function(date) { + pruneOldCrashes(date) { return Task.spawn(function* () { let store = yield this._getStore(); store.pruneOldCrashes(date); @@ -400,7 +400,7 @@ this.CrashManager.prototype = Object.freeze({ /** * Run tasks that should be periodically performed. */ - runMaintenanceTasks: function() { + runMaintenanceTasks() { return Task.spawn(function* () { yield this.aggregateEventsFiles(); @@ -415,7 +415,7 @@ this.CrashManager.prototype = Object.freeze({ * @param delay * (integer) Delay in milliseconds when maintenance should occur. */ - scheduleMaintenance: function(delay) { + scheduleMaintenance(delay) { let deferred = PromiseUtils.defer(); setTimeout(() => { @@ -439,7 +439,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return promise Resolved when the store has been saved. */ - addCrash: function(processType, crashType, id, date, metadata) { + addCrash(processType, crashType, id, date, metadata) { let promise = Task.spawn(function* () { let store = yield this._getStore(); if (store.addCrash(processType, crashType, id, date, metadata)) { @@ -561,7 +561,7 @@ this.CrashManager.prototype = Object.freeze({ * * The promise-resolved array is sorted by file mtime, oldest to newest. */ - _getUnprocessedEventsFiles: function() { + _getUnprocessedEventsFiles() { return Task.spawn(function* () { let entries = []; @@ -578,7 +578,7 @@ this.CrashManager.prototype = Object.freeze({ }, // See docs/crash-events.rst for the file format specification. - _processEventFile: function(entry) { + _processEventFile(entry) { return Task.spawn(function* () { let data = yield OS.File.read(entry.path); let store = yield this._getStore(); @@ -617,7 +617,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - _filterAnnotations: function(annotations) { + _filterAnnotations(annotations) { let filteredAnnotations = {}; for (let line in annotations) { @@ -629,7 +629,7 @@ this.CrashManager.prototype = Object.freeze({ return filteredAnnotations; }, - _sendCrashPing: function(crashId, type, date, metadata = {}) { + _sendCrashPing(crashId, type, date, metadata = {}) { // If we have a saved environment, use it. Otherwise report // the current environment. let reportMeta = Cu.cloneInto(metadata, myScope); @@ -646,10 +646,10 @@ this.CrashManager.prototype = Object.freeze({ { version: 1, crashDate: date.toISOString().slice(0, 10), // YYYY-MM-DD - sessionId: sessionId, - crashId: crashId, + sessionId, + crashId, processType: type, - stackTraces: stackTraces, + stackTraces, metadata: reportMeta, hasCrashEnvironment: (crashEnvironment !== null), }, @@ -662,7 +662,7 @@ this.CrashManager.prototype = Object.freeze({ ); }, - _handleEventFilePayload: function(store, entry, type, date, payload) { + _handleEventFilePayload(store, entry, type, date, payload) { // The payload types and formats are documented in docs/crash-events.rst. // Do not change the format of an existing type. Instead, invent a new // type. @@ -720,7 +720,7 @@ this.CrashManager.prototype = Object.freeze({ * id -- regexp.match()[1] (likely the crash ID) * date -- Date mtime of the file */ - _getDirectoryEntries: function(path, re) { + _getDirectoryEntries(path, re) { return Task.spawn(function* () { try { yield OS.File.stat(path); @@ -763,7 +763,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - _getStore: function() { + _getStore() { if (this._getStoreTask) { return this._getStoreTask; } @@ -823,7 +823,7 @@ this.CrashManager.prototype = Object.freeze({ * * Returns an array of CrashRecord instances. Instances are read-only. */ - getCrashes: function() { + getCrashes() { return Task.spawn(function* () { let store = yield this._getStore(); @@ -831,7 +831,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - getCrashCountsByDay: function() { + getCrashCountsByDay() { return Task.spawn(function* () { let store = yield this._getStore(); @@ -908,7 +908,7 @@ CrashStore.prototype = Object.freeze({ * * @return Promise */ - load: function() { + load() { return Task.spawn(function* () { // Loading replaces data. this.reset(); @@ -1008,7 +1008,7 @@ CrashStore.prototype = Object.freeze({ * * @return Promise */ - save: function() { + save() { return Task.spawn(function* () { if (!this._data) { return; @@ -1078,7 +1078,7 @@ CrashStore.prototype = Object.freeze({ * We convert these to milliseconds since epoch on output and back to * Date on input. */ - _normalize: function(o) { + _normalize(o) { let normalized = {}; for (let k in o) { @@ -1096,7 +1096,7 @@ CrashStore.prototype = Object.freeze({ /** * Convert a serialized object back to its native form. */ - _denormalize: function(o) { + _denormalize(o) { let n = {}; for (let k in o) { @@ -1122,7 +1122,7 @@ CrashStore.prototype = Object.freeze({ * (Date) The cutoff at which data will be pruned. If an entry * doesn't have data newer than this, it will be pruned. */ - pruneOldCrashes: function(date) { + pruneOldCrashes(date) { for (let crash of this.crashes) { let newest = crash.newestDate; if (!newest || newest.getTime() < date.getTime()) { @@ -1167,7 +1167,7 @@ CrashStore.prototype = Object.freeze({ * A CrashRecord will be returned if the crash exists. null will be returned * if the crash is unknown. */ - getCrash: function(id) { + getCrash(id) { for (let crash of this.crashes) { if (crash.id == id) { return crash; @@ -1177,7 +1177,7 @@ CrashStore.prototype = Object.freeze({ return null; }, - _ensureCountsForDay: function(day) { + _ensureCountsForDay(day) { if (!this._countsByDay.has(day)) { this._countsByDay.set(day, new Map()); } @@ -1202,7 +1202,7 @@ CrashStore.prototype = Object.freeze({ * * @return null | object crash record */ - _ensureCrashRecord: function(processType, crashType, id, date, metadata) { + _ensureCrashRecord(processType, crashType, id, date, metadata) { if (!id) { // Crashes are keyed on ID, so it's not really helpful to store crashes // without IDs. @@ -1232,13 +1232,13 @@ CrashStore.prototype = Object.freeze({ } this._data.crashes.set(id, { - id: id, + id, remoteID: null, - type: type, + type, crashDate: date, submissions: new Map(), classifications: [], - metadata: metadata, + metadata, }); } @@ -1260,14 +1260,14 @@ CrashStore.prototype = Object.freeze({ * * @return boolean True if the crash was recorded and false if not. */ - addCrash: function(processType, crashType, id, date, metadata) { + addCrash(processType, crashType, id, date, metadata) { return !!this._ensureCrashRecord(processType, crashType, id, date, metadata); }, /** * @return boolean True if the remote ID was recorded and false if not. */ - setRemoteCrashID: function(crashID, remoteID) { + setRemoteCrashID(crashID, remoteID) { let crash = this._data.crashes.get(crashID); if (!crash || !remoteID) { return false; @@ -1277,7 +1277,7 @@ CrashStore.prototype = Object.freeze({ return true; }, - getCrashesOfType: function(processType, crashType) { + getCrashesOfType(processType, crashType) { let crashes = []; for (let crash of this.crashes) { if (crash.isOfType(processType, crashType)) { @@ -1292,7 +1292,7 @@ CrashStore.prototype = Object.freeze({ * Ensure the submission record is present in storage. * @returns [submission, crash] */ - _ensureSubmissionRecord: function(crashID, submissionID) { + _ensureSubmissionRecord(crashID, submissionID) { let crash = this._data.crashes.get(crashID); if (!crash || !submissionID) { return null; @@ -1312,7 +1312,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the attempt was recorded. */ - addSubmissionAttempt: function(crashID, submissionID, date) { + addSubmissionAttempt(crashID, submissionID, date) { let [submission, crash] = this._ensureSubmissionRecord(crashID, submissionID); if (!submission) { @@ -1328,7 +1328,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the response was recorded. */ - addSubmissionResult: function(crashID, submissionID, date, result) { + addSubmissionResult(crashID, submissionID, date, result) { let crash = this._data.crashes.get(crashID); if (!crash || !submissionID) { return false; @@ -1348,7 +1348,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the classifications were set. */ - setCrashClassifications: function(crashID, classifications) { + setCrashClassifications(crashID, classifications) { let crash = this._data.crashes.get(crashID); if (!crash) { return false; @@ -1407,7 +1407,7 @@ CrashRecord.prototype = Object.freeze({ return this._o.type; }, - isOfType: function(processType, crashType) { + isOfType(processType, crashType) { return processType + "-" + crashType == this.type; }, diff --git a/toolkit/components/crashes/CrashManagerTest.jsm b/toolkit/components/crashes/CrashManagerTest.jsm index e55da45468fd..f7fa11d8e0cf 100644 --- a/toolkit/components/crashes/CrashManagerTest.jsm +++ b/toolkit/components/crashes/CrashManagerTest.jsm @@ -57,7 +57,7 @@ this.TestingCrashManager = function(options) { this.TestingCrashManager.prototype = { __proto__: CrashManager.prototype, - createDummyDump: function(submitted = false, date = new Date(), hr = false) { + createDummyDump(submitted = false, date = new Date(), hr = false) { let uuid = Cc["@mozilla.org/uuid-generator;1"] .getService(Ci.nsIUUIDGenerator) .generateUUID() @@ -89,7 +89,7 @@ this.TestingCrashManager.prototype = { }); }, - createIgnoredDumpFile: function(filename, submitted = false) { + createIgnoredDumpFile(filename, submitted = false) { let path; if (submitted) { path = OS.Path.join(this._submittedDumpsDir, filename); @@ -104,7 +104,7 @@ this.TestingCrashManager.prototype = { }); }, - createEventsFile: function(filename, type, date, content, index = 0) { + createEventsFile(filename, type, date, content, index = 0) { let path = OS.Path.join(this._eventsDirs[index], filename); let data = type + "\n" + @@ -124,7 +124,7 @@ this.TestingCrashManager.prototype = { * * We can probably delete this once we have actual events defined. */ - _handleEventFilePayload: function(store, entry, type, date, payload) { + _handleEventFilePayload(store, entry, type, date, payload) { if (type == "test.1") { if (payload == "malformed") { return this.EVENT_FILE_ERROR_MALFORMED; diff --git a/toolkit/components/crashes/CrashService.js b/toolkit/components/crashes/CrashService.js index 72f804fc079d..76713524b81b 100644 --- a/toolkit/components/crashes/CrashService.js +++ b/toolkit/components/crashes/CrashService.js @@ -57,7 +57,7 @@ CrashService.prototype = Object.freeze({ Ci.nsIObserver, ]), - addCrash: function(processType, crashType, id) { + addCrash(processType, crashType, id) { switch (processType) { case Ci.nsICrashService.PROCESS_TYPE_MAIN: processType = Services.crashmanager.PROCESS_TYPE_MAIN; @@ -98,7 +98,7 @@ CrashService.prototype = Object.freeze({ ); }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "profile-after-change": // Side-effect is the singleton is instantiated. diff --git a/toolkit/components/crashmonitor/CrashMonitor.jsm b/toolkit/components/crashmonitor/CrashMonitor.jsm index 6540d516fc2b..2ee173527507 100644 --- a/toolkit/components/crashmonitor/CrashMonitor.jsm +++ b/toolkit/components/crashmonitor/CrashMonitor.jsm @@ -93,7 +93,7 @@ var CrashMonitorInternal = { * * @return {Promise} A promise that resolves/rejects once loading is complete */ - loadPreviousCheckpoints: function() { + loadPreviousCheckpoints() { this.previousCheckpoints = Task.spawn(function*() { let data; try { @@ -155,7 +155,7 @@ this.CrashMonitor = { * * @return {Promise} */ - init: function() { + init() { if (CrashMonitorInternal.initialized) { throw new Error("CrashMonitor.init() must only be called once!"); } @@ -185,7 +185,7 @@ this.CrashMonitor = { * * Update checkpoint file for every new notification received. */ - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (!(aTopic in CrashMonitorInternal.checkpoints)) { // If this is the first time this notification is received, // remember it and write it to file diff --git a/toolkit/components/crashmonitor/nsCrashMonitor.js b/toolkit/components/crashmonitor/nsCrashMonitor.js index fe29a9c8eaea..d53fecd6d067 100644 --- a/toolkit/components/crashmonitor/nsCrashMonitor.js +++ b/toolkit/components/crashmonitor/nsCrashMonitor.js @@ -18,7 +18,7 @@ CrashMonitor.prototype = { QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]), - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "profile-after-change": MonitorAPI.init(); diff --git a/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js b/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js index eec85025b5c5..7163e2755415 100644 --- a/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js +++ b/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js @@ -13,7 +13,7 @@ var Components = { caller: null }, utils: { - import: function() { } + import() { } } }; @@ -72,7 +72,7 @@ FileFaker.prototype = { this._path = this._path.substring(0, lastSlash); return this; }, - append: function(leaf) { + append(leaf) { this._path = this._path + "/" + leaf; } }; diff --git a/toolkit/components/ctypes/tests/unit/head.js b/toolkit/components/ctypes/tests/unit/head.js index 4e51b22a2ab5..e2c2ea4683c0 100644 --- a/toolkit/components/ctypes/tests/unit/head.js +++ b/toolkit/components/ctypes/tests/unit/head.js @@ -44,7 +44,7 @@ function ResourceTester(start, stop) { this._stop = stop; } ResourceTester.prototype = { - launch: function(size, test, args) { + launch(size, test, args) { trigger_gc(); let cleaner = new ResourceCleaner(); this._start(size); diff --git a/toolkit/components/ctypes/tests/unit/test_finalizer.js b/toolkit/components/ctypes/tests/unit/test_finalizer.js index d50437da6eb5..d19c82eed1fc 100644 --- a/toolkit/components/ctypes/tests/unit/test_finalizer.js +++ b/toolkit/components/ctypes/tests/unit/test_finalizer.js @@ -34,8 +34,8 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status: status, - released: released + status, + released }); samples.push( { @@ -53,8 +53,8 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status: status, - released: released + status, + released }); samples.push( { @@ -72,8 +72,8 @@ function run_test() ctypes.bool, ctypes.int32_t, ctypes.int32_t), - status: status, - released: released + status, + released } ); samples.push( @@ -92,8 +92,8 @@ function run_test() ctypes.bool, ctypes.int64_t, ctypes.int64_t), - status: status, - released: released + status, + released } ); samples.push( @@ -112,8 +112,8 @@ function run_test() ctypes.bool, ctypes.void_t.ptr, ctypes.void_t.ptr), - status: status, - released: released + status, + released } ); samples.push( @@ -132,8 +132,8 @@ function run_test() ctypes.bool, ctypes.char.ptr, ctypes.char.ptr), - status: status, - released: released + status, + released } ); const rect_t = new ctypes.StructType("myRECT", @@ -157,8 +157,8 @@ function run_test() ctypes.bool, rect_t, rect_t), - status: status, - released: released + status, + released } ); samples.push( @@ -177,7 +177,7 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status: status, + status, released: function released_eq(i, witness) { return i == witness; } @@ -199,7 +199,7 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status: status, + status, released: function released_rect_eq(i, witness) { return witness.top == i && witness.bottom == i @@ -228,7 +228,7 @@ function run_test() ctypes.bool, ctypes.void_t.ptr, ctypes.void_t.ptr), - released: released + released } ); @@ -397,8 +397,8 @@ function test_executing_forget(size, tc, cleanup) let finalizer = ctypes.CDataFinalizer(original, tc.release); ref.push( { - original: original, - finalizer: finalizer + original, + finalizer } ); cleanup.add(finalizer); diff --git a/toolkit/components/ctypes/tests/unit/test_jsctypes.js b/toolkit/components/ctypes/tests/unit/test_jsctypes.js index 18861a185c3c..f91f40992d24 100644 --- a/toolkit/components/ctypes/tests/unit/test_jsctypes.js +++ b/toolkit/components/ctypes/tests/unit/test_jsctypes.js @@ -413,8 +413,8 @@ function run_Int64_tests() { ctypes.UInt64("0x8000000000000000"), Infinity, -Infinity, NaN, 0.1, 5.68e21, null, undefined, "", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { ctypes.Int64(vals[i]); }, TypeError); @@ -563,8 +563,8 @@ function run_UInt64_tests() { let vals = [-1, 0x10000000000000000, "-1", "-0x1", ctypes.Int64("-1"), Infinity, -Infinity, NaN, 0.1, 5.68e21, null, undefined, "", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { ctypes.UInt64(vals[i]); }, TypeError); @@ -778,8 +778,8 @@ function run_bool_tests(library) { let vals = [-1, 2, Infinity, -Infinity, NaN, 0.1, ctypes.Int64(0), ctypes.UInt64(0), null, undefined, "", "0", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -858,8 +858,8 @@ function run_integer_tests(library, t, name, size, signed, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "0", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -945,8 +945,8 @@ function run_float_tests(library, t, name, size) { // don't convert anything else let vals = [true, false, null, undefined, "", "0", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1045,8 +1045,8 @@ function run_wrapped_integer_tests(library, t, name, size, signed, w, wname, lim // don't convert anything else let vals = [limits[2], limits[3], Infinity, -Infinity, NaN, 0.1, null, undefined, "", "0", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1128,8 +1128,8 @@ function run_char_tests(library, t, name, size, signed, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "aa", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1220,8 +1220,8 @@ function run_char16_tests(library, t, name, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "aa", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -2223,7 +2223,7 @@ function run_string_tests(library) { do_check_eq(test_ansi_len("hello world"), 11); // don't convert anything else to a string - let vals = [true, 0, 1 / 3, undefined, {}, {toString: function() { return "bad"; }}, []]; + let vals = [true, 0, 1 / 3, undefined, {}, {toString() { return "bad"; }}, []]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { test_ansi_len(vals[i]); }, TypeError); diff --git a/toolkit/components/downloads/test/unit/test_app_rep_windows.js b/toolkit/components/downloads/test/unit/test_app_rep_windows.js index 49d89751bc83..44fd26999830 100644 --- a/toolkit/components/downloads/test/unit/test_app_rep_windows.js +++ b/toolkit/components/downloads/test/unit/test_app_rep_windows.js @@ -119,8 +119,8 @@ function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) { copier.init(inputStream, aSaverOutputStream, null, false, true, 0x8000, true, aCloseWhenDone); copier.asyncCopy({ - onStartRequest: function() { }, - onStopRequest: function(aRequest, aContext, aStatusCode) + onStartRequest() { }, + onStopRequest(aRequest, aContext, aStatusCode) { if (Components.isSuccessCode(aStatusCode)) { deferred.resolve(); diff --git a/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js b/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js index 7e9c715f69a1..f1f32995fa5f 100644 --- a/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js +++ b/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js @@ -513,7 +513,6 @@ add_task(function* ensureKeysFor_posts_new_keys() { const newBody = yield assertPostedEncryptedKeys(newPost); ok(newBody.keys.collections[extensionId], `keys object should have a key for ${extensionId}`); ok(newBody.keys.collections[extensionId2], `keys object should have a key for ${extensionId2}`); - }); }); }); diff --git a/toolkit/components/exthelper/extApplication.js b/toolkit/components/exthelper/extApplication.js index ff17f37e5234..b592e8cdc782 100644 --- a/toolkit/components/exthelper/extApplication.js +++ b/toolkit/components/exthelper/extApplication.js @@ -663,7 +663,7 @@ extApplication.prototype = { return this.prefs; }, - getExtensions: function(callback) { + getExtensions(callback) { AddonManager.getAddonsByTypes(["extension"], function(addons) { callback.callback(new Extensions(addons)); }); diff --git a/toolkit/components/feeds/test/test_xml.js b/toolkit/components/feeds/test/test_xml.js index 5bc0d759d12a..5a6f350ef011 100644 --- a/toolkit/components/feeds/test/test_xml.js +++ b/toolkit/components/feeds/test/test_xml.js @@ -32,7 +32,7 @@ function FeedListener(testcase) { } FeedListener.prototype = { - handleResult: function(result) { + handleResult(result) { var feed = result.doc; try { do_print("Testing feed " + this.testcase.file.path); diff --git a/toolkit/components/filepicker/content/filepicker.js b/toolkit/components/filepicker/content/filepicker.js index 7dc0a936e616..1069a7b2cfa4 100644 --- a/toolkit/components/filepicker/content/filepicker.js +++ b/toolkit/components/filepicker/content/filepicker.js @@ -368,11 +368,11 @@ var gFilesEnumerator = { mFiles: null, mIndex: 0, - hasMoreElements: function() + hasMoreElements() { return (this.mIndex < this.mFiles.length); }, - getNext: function() + getNext() { if (this.mIndex >= this.mFiles.length) throw Components.results.NS_ERROR_FAILURE; diff --git a/toolkit/components/filepicker/nsFilePicker.js b/toolkit/components/filepicker/nsFilePicker.js index 97bb78e7631f..f40b0562765d 100644 --- a/toolkit/components/filepicker/nsFilePicker.js +++ b/toolkit/components/filepicker/nsFilePicker.js @@ -68,7 +68,7 @@ function nsFilePicker() nsFilePicker.prototype = { classID: Components.ID("{54ae32f8-1dd2-11b2-a209-df7c505370f8}"), - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(nsIFilePicker) || iid.equals(nsISupports)) return this; @@ -113,11 +113,11 @@ nsFilePicker.prototype = { mFiles: [], mIndex: 0, - hasMoreElements: function() { + hasMoreElements() { return (this.mIndex < this.mFiles.length); }, - getNext: function() { + getNext() { if (this.mIndex >= this.mFiles.length) { throw Components.results.NS_ERROR_FAILURE; } @@ -176,13 +176,13 @@ nsFilePicker.prototype = { mParentWindow: null, /* methods */ - init: function(parent, title, mode) { + init(parent, title, mode) { this.mParentWindow = parent; this.mTitle = title; this.mMode = mode; }, - appendFilters: function(filterMask) { + appendFilters(filterMask) { if (filterMask & nsIFilePicker.filterHTML) { this.appendFilter(titleBundle.GetStringFromName("htmlTitle"), filterBundle.GetStringFromName("htmlFilter")); @@ -223,12 +223,12 @@ nsFilePicker.prototype = { } }, - appendFilter: function(title, extensions) { + appendFilter(title, extensions) { this.mFilterTitles.push(title); this.mFilters.push(extensions); }, - open: function(aFilePickerShownCallback) { + open(aFilePickerShownCallback) { var tm = Components.classes["@mozilla.org/thread-manager;1"] .getService(Components.interfaces.nsIThreadManager); tm.mainThread.dispatch(function() { @@ -243,7 +243,7 @@ nsFilePicker.prototype = { }.bind(this), Components.interfaces.nsIThread.DISPATCH_NORMAL); }, - show: function() { + show() { var o = {}; o.title = this.mTitle; o.mode = this.mMode; diff --git a/toolkit/components/filepicker/test/unit/test_filecomplete.js b/toolkit/components/filepicker/test/unit/test_filecomplete.js index d1e18d533748..8e15f4ac2bbf 100644 --- a/toolkit/components/filepicker/test/unit/test_filecomplete.js +++ b/toolkit/components/filepicker/test/unit/test_filecomplete.js @@ -19,7 +19,7 @@ dir.append("test_dir"); dir.create(dir.DIRECTORY_TYPE, -1); var gListener = { - onSearchResult: function(aSearch, aResult) { + onSearchResult(aSearch, aResult) { // Check that we got same search string back. do_check_eq(aResult.searchString, "test"); // Check that the search succeeded. diff --git a/toolkit/components/formautofill/FormAutofillContentService.js b/toolkit/components/formautofill/FormAutofillContentService.js index 2b64e19663a3..1de839f54d63 100644 --- a/toolkit/components/formautofill/FormAutofillContentService.js +++ b/toolkit/components/formautofill/FormAutofillContentService.js @@ -76,7 +76,7 @@ FormHandler.prototype = { ? new this.window.Event("autocomplete", { bubbles: true }) : new this.window.AutocompleteErrorEvent("autocompleteerror", { bubbles: true, - reason: reason }); + reason }); yield this.waitForTick(); this.form.dispatchEvent(event); }), @@ -143,7 +143,7 @@ FormHandler.prototype = { * interface, or null if the operation failed because the constraints * on the allowed fields were not honored. */ - collectFormFields: function() { + collectFormFields() { let autofillData = { sections: [], }; @@ -173,7 +173,7 @@ FormHandler.prototype = { addressType: info.addressType, contactType: info.contactType, fieldName: info.fieldName, - element: element, + element, }); // The first level is the custom section. @@ -225,7 +225,7 @@ FormHandler.prototype = { * ], * } */ - autofillFormFields: function(aAutofillResult) { + autofillFormFields(aAutofillResult) { for (let field of aAutofillResult.fields) { // Get the field details, if it was processed by the user interface. let fieldDetail = this.fieldDetails @@ -244,7 +244,7 @@ FormHandler.prototype = { /** * Waits for one tick of the event loop before resolving the returned promise. */ - waitForTick: function() { + waitForTick() { return new Promise(function(resolve) { Services.tm.currentThread.dispatch(resolve, Ci.nsIThread.DISPATCH_NORMAL); }); @@ -263,7 +263,7 @@ FormAutofillContentService.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIFormAutofillContentService]), // nsIFormAutofillContentService - requestAutocomplete: function(aForm, aWindow) { + requestAutocomplete(aForm, aWindow) { new FormHandler(aForm, aWindow).handleRequestAutocomplete() .catch(Cu.reportError); }, diff --git a/toolkit/components/formautofill/FormAutofillStartup.js b/toolkit/components/formautofill/FormAutofillStartup.js index a2c3b125774f..b459bc67fa61 100644 --- a/toolkit/components/formautofill/FormAutofillStartup.js +++ b/toolkit/components/formautofill/FormAutofillStartup.js @@ -31,7 +31,7 @@ FormAutofillStartup.prototype = { ]), // nsIObserver - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { // This method is called by the "profile-after-change" category on startup, // which is called before any web page loads. At this time, we need to // register a global message listener in the parent process preemptively, @@ -44,7 +44,7 @@ FormAutofillStartup.prototype = { }, // nsIFrameMessageListener - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { // Process the "FormAutofill:RequestAutocomplete" message. Any exception // raised in the parent process is caught and serialized into the reply // message that is sent to the requesting child process. diff --git a/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm b/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm index f2f2ddded104..23743f49e056 100644 --- a/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm +++ b/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm @@ -40,7 +40,7 @@ this.RequestAutocompleteUI.prototype = { // Wrap the callback function so that it survives XPCOM. let args = { - resolveFn: resolveFn, + resolveFn, autofillData: this._autofillData, }; args.wrappedJSObject = args; diff --git a/toolkit/components/formautofill/content/requestAutocomplete.js b/toolkit/components/formautofill/content/requestAutocomplete.js index 5dbbdc9c182d..269018d8ffb9 100644 --- a/toolkit/components/formautofill/content/requestAutocomplete.js +++ b/toolkit/components/formautofill/content/requestAutocomplete.js @@ -22,7 +22,7 @@ const RequestAutocompleteDialog = { resolveFn: null, autofillData: null, - onLoad: function() { + onLoad() { Task.spawn(function* () { let args = window.arguments[0].wrappedJSObject; this.resolveFn = args.resolveFn; @@ -35,7 +35,7 @@ const RequestAutocompleteDialog = { }.bind(this)).catch(Cu.reportError); }, - onAccept: function() { + onAccept() { // TODO: Replace with autofill storage module (bug 1018304). const dummyDB = { "": { @@ -65,7 +65,7 @@ const RequestAutocompleteDialog = { result.fields.push({ section: section.name, - addressType: addressType, + addressType, contactType: field.contactType, fieldName: field.fieldName, value: dummyDB[addressType][fieldName], @@ -78,7 +78,7 @@ const RequestAutocompleteDialog = { this.resolveFn(result); }, - onCancel: function() { + onCancel() { window.close(); this.resolveFn({ canceled: true }); }, diff --git a/toolkit/components/formautofill/test/chrome/loader.js b/toolkit/components/formautofill/test/chrome/loader.js index 556211e3df30..4cdc3cd6ed59 100644 --- a/toolkit/components/formautofill/test/chrome/loader.js +++ b/toolkit/components/formautofill/test/chrome/loader.js @@ -33,7 +33,7 @@ var testUrl = location.href.replace(/\.\w+$/, ".js"); var promiseParentInitFinished = new Promise(function(resolve) { parentScript.addMessageListener("finish_load_in_parent", resolve); }); -parentScript.sendAsyncMessage("start_load_in_parent", { testUrl: testUrl }); +parentScript.sendAsyncMessage("start_load_in_parent", { testUrl }); // Define output functions so they look the same across all frameworks. var Output = { diff --git a/toolkit/components/formautofill/test/head_common.js b/toolkit/components/formautofill/test/head_common.js index f3fec4293929..87a23f0756a1 100644 --- a/toolkit/components/formautofill/test/head_common.js +++ b/toolkit/components/formautofill/test/head_common.js @@ -42,7 +42,7 @@ var TestUtils = { * @resolves When pending events have been processed. * @rejects Never. */ - waitForTick: function() { + waitForTick() { return new Promise(resolve => executeSoon(resolve)); }, @@ -58,7 +58,7 @@ var TestUtils = { * @resolves When the specified time has passed. * @rejects Never. */ - waitMs: function(aTimeMs) { + waitMs(aTimeMs) { return new Promise(resolve => setTimeout(resolve, aTimeMs)); }, @@ -72,7 +72,7 @@ var TestUtils = { * @resolves The array [aSubject, aData] from the observed notification. * @rejects Never. */ - waitForNotification: function(aTopic) { + waitForNotification(aTopic) { Output.print("Waiting for notification: '" + aTopic + "'."); return new Promise(resolve => Services.obs.addObserver( @@ -96,7 +96,7 @@ var TestUtils = { * @resolves The arguments from the observed event. * @rejects Never. */ - waitForEvent: function(aTarget, aEventName, aUseCapture = false) { + waitForEvent(aTarget, aEventName, aUseCapture = false) { Output.print("Waiting for event: '" + aEventName + "' on " + aTarget + "."); return new Promise(resolve => aTarget.addEventListener(aEventName, @@ -183,7 +183,7 @@ var FormAutofillTest = { // The window is the subject of the observer notification. return { uiWindow: (yield promiseUIWindow)[0], - promiseResult: promiseResult, + promiseResult, }; }), }; diff --git a/toolkit/components/formautofill/test/loader_common.js b/toolkit/components/formautofill/test/loader_common.js index 3f5fae5b2f49..33a838b4a31b 100644 --- a/toolkit/components/formautofill/test/loader_common.js +++ b/toolkit/components/formautofill/test/loader_common.js @@ -104,12 +104,12 @@ function getTaskId(stackFrame) { // This is a shared helper for mochitest-chrome and mochitest-browser. var _mochitestAssert = { - ok: function(actual) { + ok(actual) { let stack = Components.stack.caller; ok(actual, "[" + stack.name + " : " + stack.lineNumber + "] " + actual + " == true"); }, - equal: function(actual, expected) { + equal(actual, expected) { let stack = Components.stack.caller; is(actual, expected, "[" + stack.name + " : " + stack.lineNumber + "] " + actual + " == " + expected); diff --git a/toolkit/components/gfx/SanityTest.js b/toolkit/components/gfx/SanityTest.js index f600d2bd4e56..3f43202cd163 100644 --- a/toolkit/components/gfx/SanityTest.js +++ b/toolkit/components/gfx/SanityTest.js @@ -153,7 +153,7 @@ var listener = { "gfxSanity:ContentLoaded", ], - scheduleTest: function(win) { + scheduleTest(win) { this.win = win; this.win.onload = this.onWindowLoaded.bind(this); this.utils = this.win.QueryInterface(Ci.nsIInterfaceRequestor) @@ -166,7 +166,7 @@ var listener = { }); }, - runSanityTest: function() { + runSanityTest() { this.canvas = this.win.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); this.canvas.setAttribute("width", PAGE_WIDTH); this.canvas.setAttribute("height", PAGE_HEIGHT); @@ -187,7 +187,7 @@ var listener = { } }, - onWindowLoaded: function() { + onWindowLoaded() { let browser = this.win.document.createElementNS(XUL_NS, "browser"); browser.setAttribute("type", "content"); @@ -208,7 +208,7 @@ var listener = { this.mm.loadFrameScript(FRAME_SCRIPT_URL, false); }, - endTest: function() { + endTest() { if (!this.win) { return; } @@ -240,7 +240,7 @@ SanityTest.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - shouldRunTest: function() { + shouldRunTest() { // Only test gfx features if firefox has updated, or if the user has a new // gpu or drivers. var buildId = Services.appinfo.platformBuildID; @@ -286,7 +286,7 @@ SanityTest.prototype = { return true; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic != "profile-after-change") return; // profile-after-change fires only at startup, so we won't need diff --git a/toolkit/components/gfx/content/gfxFrameScript.js b/toolkit/components/gfx/content/gfxFrameScript.js index 4b48dc11ac7e..eaac257ceff7 100644 --- a/toolkit/components/gfx/content/gfxFrameScript.js +++ b/toolkit/components/gfx/content/gfxFrameScript.js @@ -3,7 +3,7 @@ var { classes: Cc, interfaces: Ci, utils: Cu } = Components; const gfxFrameScript = { domUtils: null, - init: function() { + init() { let webNav = docShell.QueryInterface(Ci.nsIWebNavigation); let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); @@ -18,7 +18,7 @@ const gfxFrameScript = { }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "MozAfterPaint": sendAsyncMessage('gfxSanity:ContentLoaded'); @@ -27,7 +27,7 @@ const gfxFrameScript = { } }, - isSanityTest: function(aUri) { + isSanityTest(aUri) { if (!aUri) { return false; } @@ -35,7 +35,7 @@ const gfxFrameScript = { return aUri.endsWith("/sanitytest.html"); }, - onStateChange: function(webProgress, req, flags, status) { + onStateChange(webProgress, req, flags, status) { if (webProgress.isTopLevel && (flags & Ci.nsIWebProgressListener.STATE_STOP) && this.isSanityTest(req.name)) { diff --git a/toolkit/components/jsdownloads/src/DownloadCore.jsm b/toolkit/components/jsdownloads/src/DownloadCore.jsm index 043f20cc18e9..ef10dec742b9 100644 --- a/toolkit/components/jsdownloads/src/DownloadCore.jsm +++ b/toolkit/components/jsdownloads/src/DownloadCore.jsm @@ -622,7 +622,7 @@ this.Download.prototype = { * @resolves When the Download has been unblocked and succeeded. * @rejects JavaScript exception if any of the operations failed. */ - unblock: function() { + unblock() { if (this._promiseUnblock) { return this._promiseUnblock; } @@ -666,7 +666,7 @@ this.Download.prototype = { * @resolves When the Download's data has been removed. * @rejects JavaScript exception if any of the operations failed. */ - confirmBlock: function() { + confirmBlock() { if (this._promiseConfirmBlock) { return this._promiseConfirmBlock; } @@ -711,7 +711,7 @@ this.Download.prototype = { * @rejects JavaScript exception if there was an error trying to launch * the file. */ - launch: function() { + launch() { if (!this.succeeded) { return Promise.reject( new Error("launch can only be called if the download succeeded") @@ -845,7 +845,7 @@ this.Download.prototype = { * @resolves When the partial data has been successfully removed. * @rejects JavaScript exception if the operation could not be completed. */ - removePartialData: function() + removePartialData() { if (!this.canceled && !this.error) { return Promise.resolve(); @@ -920,7 +920,7 @@ this.Download.prototype = { * @resolves When the operation has completed. * @rejects Never. */ - refresh: function() + refresh() { return Task.spawn(function* () { if (!this.stopped || this._finalized) { @@ -999,7 +999,7 @@ this.Download.prototype = { * @rejects JavaScript exception if an error occurred while removing the * partially downloaded data. */ - finalize: function(aRemovePartialData) + finalize(aRemovePartialData) { // Prevents the download from starting again after having been stopped. this._finalized = true; @@ -1096,7 +1096,7 @@ this.Download.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { let serializable = { source: this.source.toSerializable(), @@ -1148,7 +1148,7 @@ this.Download.prototype = { * * @return String representing the relevant download state. */ - getSerializationHash: function() + getSerializationHash() { // The "succeeded", "canceled", "error", and startTime properties are not // taken into account because they all change before the "stopped" property @@ -1296,7 +1296,7 @@ this.DownloadSource.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { if (this.adjustChannel) { // If the callback was used, we can't reproduce this across sessions. @@ -1452,7 +1452,7 @@ this.DownloadTarget.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { // Simplify the representation if we don't have other details. if (!this.partFilePath && !this._unknownProperties) { @@ -1654,7 +1654,7 @@ this.DownloadError.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { let serializable = { result: this.result, @@ -1769,7 +1769,7 @@ this.DownloadSaver.prototype = { * started, to add it to the browsing history. This method has no effect if * the download is private. */ - addToHistory: function() + addToHistory() { if (this.download.source.isPrivate) { return; @@ -1806,7 +1806,7 @@ this.DownloadSaver.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { throw new Error("Not implemented."); }, @@ -1814,12 +1814,12 @@ this.DownloadSaver.prototype = { /** * Returns the SHA-256 hash of the downloaded file, if it exists. */ - getSha256Hash: function() + getSha256Hash() { throw new Error("Not implemented."); }, - getSignatureInfo: function() + getSignatureInfo() { throw new Error("Not implemented."); }, @@ -1968,7 +1968,7 @@ this.DownloadCopySaver.prototype = { // When the operation completes, reflect the status in the promise // returned by this download execution function. backgroundFileSaver.observer = { - onTargetChange: function() { }, + onTargetChange() { }, onSaveComplete: (aSaver, aStatus) => { // Send notifications now that we can restart if needed. if (Components.isSuccessCode(aStatus)) { @@ -2033,7 +2033,7 @@ this.DownloadCopySaver.prototype = { aSetProgressBytesFn(currentBytes, totalBytes, aProgress > 0 && partFilePath && keepPartialData); }, - onStatus: function() { }, + onStatus() { }, }; // If the callback was set, handle it now before opening the channel. @@ -2257,7 +2257,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.removePartialData". */ - removePartialData: function() + removePartialData() { return Task.spawn(function* task_DCS_removePartialData() { if (this.download.target.partFilePath) { @@ -2275,7 +2275,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable: function() + toSerializable() { // Simplify the representation if we don't have other details. if (!this.entityID && !this._unknownProperties) { @@ -2291,7 +2291,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.getSha256Hash" */ - getSha256Hash: function() + getSha256Hash() { return this._sha256Hash; }, @@ -2299,7 +2299,7 @@ this.DownloadCopySaver.prototype = { /* * Implements DownloadSaver.getSignatureInfo. */ - getSignatureInfo: function() + getSignatureInfo() { return this._signatureInfo; }, @@ -2307,7 +2307,7 @@ this.DownloadCopySaver.prototype = { /* * Implements DownloadSaver.getRedirects. */ - getRedirects: function() + getRedirects() { return this._redirects; } @@ -2440,7 +2440,7 @@ this.DownloadLegacySaver.prototype = { * download is added to the browsing history here. Private downloads * are never added to history even if this parameter is false. */ - onTransferStarted: function(aRequest, aAlreadyAddedToHistory) + onTransferStarted(aRequest, aAlreadyAddedToHistory) { // Store the entity ID to use for resuming if required. if (this.download.tryToKeepPartialData && @@ -2603,7 +2603,7 @@ this.DownloadLegacySaver.prototype = { }.bind(this)); }, - _checkReputationAndMove: function() { + _checkReputationAndMove() { return DownloadCopySaver.prototype._checkReputationAndMove .apply(this, arguments); }, @@ -2629,7 +2629,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.removePartialData". */ - removePartialData: function() + removePartialData() { // DownloadCopySaver and DownloadLeagcySaver use the same logic for removing // partially downloaded data, though this implementation isn't shared by @@ -2640,7 +2640,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable: function() + toSerializable() { // This object depends on legacy components that are created externally, // thus it cannot be rebuilt during deserialization. To support resuming @@ -2652,7 +2652,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getSha256Hash". */ - getSha256Hash: function() + getSha256Hash() { if (this.copySaver) { return this.copySaver.getSha256Hash(); @@ -2663,7 +2663,7 @@ this.DownloadLegacySaver.prototype = { /** * Called by the nsITransfer implementation when the hash is available. */ - setSha256Hash: function(hash) + setSha256Hash(hash) { this._sha256Hash = hash; }, @@ -2671,7 +2671,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getSignatureInfo". */ - getSignatureInfo: function() + getSignatureInfo() { if (this.copySaver) { return this.copySaver.getSignatureInfo(); @@ -2682,7 +2682,7 @@ this.DownloadLegacySaver.prototype = { /** * Called by the nsITransfer implementation when the hash is available. */ - setSignatureInfo: function(signatureInfo) + setSignatureInfo(signatureInfo) { this._signatureInfo = signatureInfo; }, @@ -2690,7 +2690,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getRedirects". */ - getRedirects: function() + getRedirects() { if (this.copySaver) { return this.copySaver.getRedirects(); @@ -2702,7 +2702,7 @@ this.DownloadLegacySaver.prototype = { * Called by the nsITransfer implementation when the redirect chain is * available. */ - setRedirects: function(redirects) + setRedirects(redirects) { this._redirects = redirects; }, @@ -2746,7 +2746,7 @@ this.DownloadPDFSaver.prototype = { /** * Implements "DownloadSaver.execute". */ - execute: function(aSetProgressBytesFn, aSetPropertiesFn) + execute(aSetProgressBytesFn, aSetPropertiesFn) { return Task.spawn(function* task_DCS_execute() { if (!this.download.source.windowRef) { @@ -2801,7 +2801,7 @@ this.DownloadPDFSaver.prototype = { try { yield new Promise((resolve, reject) => { this._webBrowserPrint.print(printSettings, { - onStateChange: function(webProgress, request, stateFlags, status) { + onStateChange(webProgress, request, stateFlags, status) { if (stateFlags & Ci.nsIWebProgressListener.STATE_STOP) { if (!Components.isSuccessCode(status)) { reject(new DownloadError({ result: status, @@ -2811,14 +2811,14 @@ this.DownloadPDFSaver.prototype = { } } }, - onProgressChange: function(webProgress, request, curSelfProgress, + onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) { aSetProgressBytesFn(curTotalProgress, maxTotalProgress, false); }, - onLocationChange: function() {}, - onStatusChange: function() {}, - onSecurityChange: function() {}, + onLocationChange() {}, + onStatusChange() {}, + onSecurityChange() {}, }); }); } finally { @@ -2845,7 +2845,7 @@ this.DownloadPDFSaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable: function() + toSerializable() { if (this.download.succeeded) { return DownloadCopySaver.prototype.toSerializable.call(this); diff --git a/toolkit/components/jsdownloads/src/DownloadImport.jsm b/toolkit/components/jsdownloads/src/DownloadImport.jsm index c1c81cc6e617..fec2348fe499 100644 --- a/toolkit/components/jsdownloads/src/DownloadImport.jsm +++ b/toolkit/components/jsdownloads/src/DownloadImport.jsm @@ -68,7 +68,7 @@ this.DownloadImport.prototype = { * from the previous database has been read and added to * the DownloadList) */ - import: function() { + import() { return Task.spawn(function* task_DI_import() { let connection = yield Sqlite.openConnection({ path: this.path }); @@ -142,7 +142,7 @@ this.DownloadImport.prototype = { let downloadOptions = { source: { url: source, - referrer: referrer + referrer }, target: { path: targetPath, @@ -150,13 +150,13 @@ this.DownloadImport.prototype = { }, saver: { type: "copy", - entityID: entityID + entityID }, startTime: new Date(startTime / 1000), totalBytes: maxBytes, hasPartialData: !!tempPath, tryToKeepPartialData: true, - launchWhenSucceeded: launchWhenSucceeded, + launchWhenSucceeded, contentType: mimeType, launcherPath: preferredApplication }; diff --git a/toolkit/components/jsdownloads/src/DownloadLegacy.js b/toolkit/components/jsdownloads/src/DownloadLegacy.js index c9bcbdd82e15..368215524eaf 100644 --- a/toolkit/components/jsdownloads/src/DownloadLegacy.js +++ b/toolkit/components/jsdownloads/src/DownloadLegacy.js @@ -166,7 +166,7 @@ DownloadLegacyTransfer.prototype = { aMaxTotalProgress); }, - onLocationChange: function() { }, + onLocationChange() { }, onStatusChange: function DLT_onStatusChange(aWebProgress, aRequest, aStatus, aMessage) @@ -184,7 +184,7 @@ DownloadLegacyTransfer.prototype = { } }, - onSecurityChange: function() { }, + onSecurityChange() { }, // nsIWebProgressListener2 @@ -237,9 +237,9 @@ DownloadLegacyTransfer.prototype = { target: { path: aTarget.QueryInterface(Ci.nsIFileURL).file.path, partFilePath: aTempFile && aTempFile.path }, saver: "legacy", - launchWhenSucceeded: launchWhenSucceeded, - contentType: contentType, - launcherPath: launcherPath + launchWhenSucceeded, + contentType, + launcherPath }).then(function DLT_I_onDownload(aDownload) { // Legacy components keep partial data when they use a ".part" file. if (aTempFile) { @@ -257,17 +257,17 @@ DownloadLegacyTransfer.prototype = { }.bind(this)).then(null, Cu.reportError); }, - setSha256Hash: function(hash) + setSha256Hash(hash) { this._sha256Hash = hash; }, - setSignatureInfo: function(signatureInfo) + setSignatureInfo(signatureInfo) { this._signatureInfo = signatureInfo; }, - setRedirects: function(redirects) + setRedirects(redirects) { this._redirects = redirects; }, diff --git a/toolkit/components/jsdownloads/src/DownloadList.jsm b/toolkit/components/jsdownloads/src/DownloadList.jsm index 4ab42e18648a..32fbfe5966bf 100644 --- a/toolkit/components/jsdownloads/src/DownloadList.jsm +++ b/toolkit/components/jsdownloads/src/DownloadList.jsm @@ -204,7 +204,7 @@ this.DownloadList.prototype = { * @param aDownload * The Download object that changed. */ - _notifyAllViews: function(aMethodName, aDownload) { + _notifyAllViews(aMethodName, aDownload) { for (let view of this._views) { try { if (aMethodName in view) { @@ -305,7 +305,7 @@ this.DownloadCombinedList.prototype = { * @resolves When the download has been added. * @rejects JavaScript exception. */ - add: function(aDownload) + add(aDownload) { if (aDownload.source.isPrivate) { return this._privateList.add(aDownload); @@ -329,7 +329,7 @@ this.DownloadCombinedList.prototype = { * @resolves When the download has been removed. * @rejects JavaScript exception. */ - remove: function(aDownload) + remove(aDownload) { if (aDownload.source.isPrivate) { return this._privateList.remove(aDownload); @@ -339,18 +339,18 @@ this.DownloadCombinedList.prototype = { // DownloadList view - onDownloadAdded: function(aDownload) + onDownloadAdded(aDownload) { this._downloads.push(aDownload); this._notifyAllViews("onDownloadAdded", aDownload); }, - onDownloadChanged: function(aDownload) + onDownloadChanged(aDownload) { this._notifyAllViews("onDownloadChanged", aDownload); }, - onDownloadRemoved: function(aDownload) + onDownloadRemoved(aDownload) { let index = this._downloads.indexOf(aDownload); if (index != -1) { @@ -396,7 +396,7 @@ this.DownloadSummary.prototype = { * @resolves When the view on the underlying list has been registered. * @rejects JavaScript exception. */ - bindToList: function(aList) + bindToList(aList) { if (this._list) { throw new Error("bindToList may be called only once."); @@ -432,7 +432,7 @@ this.DownloadSummary.prototype = { * notification has been sent. * @rejects JavaScript exception. */ - addView: function(aView) + addView(aView) { this._views.add(aView); @@ -458,7 +458,7 @@ this.DownloadSummary.prototype = { * will not receive any more notifications. * @rejects JavaScript exception. */ - removeView: function(aView) + removeView(aView) { this._views.delete(aView); @@ -494,7 +494,7 @@ this.DownloadSummary.prototype = { * and will recalculate the summary and notify the views in case the * aggregated properties are different. */ - _onListChanged: function() { + _onListChanged() { let allHaveStopped = true; let progressTotalBytes = 0; let progressCurrentBytes = 0; @@ -535,7 +535,7 @@ this.DownloadSummary.prototype = { // DownloadList view - onDownloadAdded: function(aDownload) + onDownloadAdded(aDownload) { this._downloads.push(aDownload); if (this._list) { @@ -543,12 +543,12 @@ this.DownloadSummary.prototype = { } }, - onDownloadChanged: function(aDownload) + onDownloadChanged(aDownload) { this._onListChanged(); }, - onDownloadRemoved: function(aDownload) + onDownloadRemoved(aDownload) { let index = this._downloads.indexOf(aDownload); if (index != -1) { diff --git a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm index 6e85d0b04b25..9eb05dd6367d 100644 --- a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm +++ b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm @@ -63,7 +63,7 @@ this.DownloadUIHelper = { * * @return A DownloadPrompter object. */ - getPrompter: function(aParent) + getPrompter(aParent) { return new DownloadPrompter(aParent || null); }, @@ -139,7 +139,7 @@ this.DownloadPrompter.prototype = { * @resolves Boolean indicating whether the launch operation can continue. * @rejects JavaScript exception. */ - confirmLaunchExecutable: function(aPath) + confirmLaunchExecutable(aPath) { const kPrefAlertOnEXEOpen = "browser.download.manager.alertOnEXEOpen"; diff --git a/toolkit/components/jsdownloads/src/Downloads.jsm b/toolkit/components/jsdownloads/src/Downloads.jsm index 174f807a5977..cbbb79a6309b 100644 --- a/toolkit/components/jsdownloads/src/Downloads.jsm +++ b/toolkit/components/jsdownloads/src/Downloads.jsm @@ -139,7 +139,7 @@ this.Downloads = { * @resolves When the download has finished successfully. * @rejects JavaScript exception if the download failed. */ - fetch: function(aSource, aTarget, aOptions) { + fetch(aSource, aTarget, aOptions) { return this.createDownload({ source: aSource, target: aTarget, @@ -170,7 +170,7 @@ this.Downloads = { * @resolves The requested DownloadList or DownloadCombinedList object. * @rejects JavaScript exception. */ - getList: function(aType) + getList(aType) { if (!this._promiseListsInitialized) { this._promiseListsInitialized = Task.spawn(function* () { @@ -232,7 +232,7 @@ this.Downloads = { * @resolves The requested DownloadList or DownloadCombinedList object. * @rejects JavaScript exception. */ - getSummary: function(aType) + getSummary(aType) { if (aType != Downloads.PUBLIC && aType != Downloads.PRIVATE && aType != Downloads.ALL) { diff --git a/toolkit/components/jsdownloads/test/unit/common_test_Download.js b/toolkit/components/jsdownloads/test/unit/common_test_Download.js index 3310eef05a19..1b0ad82c32c0 100644 --- a/toolkit/components/jsdownloads/test/unit/common_test_Download.js +++ b/toolkit/components/jsdownloads/test/unit/common_test_Download.js @@ -200,7 +200,7 @@ add_task(function* test_basic() // When testing DownloadLegacySaver, the download is already started when it // is created, thus we must check its basic properties while in progress. download = yield promiseStartLegacyDownload(null, - { targetFile: targetFile }); + { targetFile }); do_check_eq(download.source.url, httpUrl("source.txt")); do_check_eq(download.target.path, targetFile.path); @@ -1391,7 +1391,7 @@ add_task(function* test_error_target() // the "error" property checked by promiseDownloadStopped. This happens // because we don't have control over when the download is started. download = yield promiseStartLegacyDownload(null, - { targetFile: targetFile }); + { targetFile }); yield promiseDownloadStopped(download); } do_throw("The download should have failed."); @@ -1438,7 +1438,7 @@ add_task(function* test_error_restart() download.start().catch(() => {}); } else { download = yield promiseStartLegacyDownload(null, - { targetFile: targetFile }); + { targetFile }); } yield promiseDownloadStopped(download); do_throw("The download should have failed."); @@ -2167,7 +2167,7 @@ add_task(function* test_launch() { download = yield Downloads.createDownload({ source: httpUrl("source.txt"), target: getTempFile(TEST_TARGET_FILE_NAME).path, - launcherPath: launcherPath, + launcherPath, launchWhenSucceeded: true }); @@ -2185,7 +2185,7 @@ add_task(function* test_launch() { // it is created, thus we don't test calling "launch" before starting. download = yield promiseStartLegacyDownload( httpUrl("source.txt"), - { launcherPath: launcherPath, + { launcherPath, launchWhenSucceeded: true }); yield promiseDownloadStopped(download); } @@ -2266,13 +2266,13 @@ add_task(function* test_launchWhenSucceeded() { source: httpUrl("source.txt"), target: getTempFile(TEST_TARGET_FILE_NAME).path, launchWhenSucceeded: true, - launcherPath: launcherPath, + launcherPath, }); yield download.start(); } else { let download = yield promiseStartLegacyDownload( httpUrl("source.txt"), - { launcherPath: launcherPath, + { launcherPath, launchWhenSucceeded: true }); yield promiseDownloadStopped(download); } @@ -2338,7 +2338,7 @@ add_task(function* test_platform_integration() } let downloadWatcherNotified = false; let observer = { - observe: function(subject, topic, data) { + observe(subject, topic, data) { do_check_eq(topic, "download-watcher-notify"); do_check_eq(data, "modified"); downloadWatcherNotified = true; diff --git a/toolkit/components/jsdownloads/test/unit/head.js b/toolkit/components/jsdownloads/test/unit/head.js index 42fa2bb96f87..866392c79ebd 100644 --- a/toolkit/components/jsdownloads/test/unit/head.js +++ b/toolkit/components/jsdownloads/test/unit/head.js @@ -203,20 +203,20 @@ function promiseWaitForVisit(aUrl) PlacesUtils.history.addObserver({ QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver]), - onBeginUpdateBatch: function() {}, - onEndUpdateBatch: function() {}, - onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID, + onBeginUpdateBatch() {}, + onEndUpdateBatch() {}, + onVisit(aURI, aVisitID, aTime, aSessionID, aReferringID, aTransitionType, aGUID, aHidden) { if (aURI.equals(uri)) { PlacesUtils.history.removeObserver(this); deferred.resolve([aTime, aTransitionType]); } }, - onTitleChanged: function() {}, - onDeleteURI: function() {}, - onClearHistory: function() {}, - onPageChanged: function() {}, - onDeleteVisits: function() {}, + onTitleChanged() {}, + onDeleteURI() {}, + onClearHistory() {}, + onPageChanged() {}, + onDeleteVisits() {}, }, false); return deferred.promise; @@ -342,7 +342,7 @@ function promiseStartLegacyDownload(aSourceUrl, aOptions) { // Temporarily register a view that will get notified when the download we // are controlling becomes visible in the list of downloads. aList.addView({ - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { aList.removeView(this).then(null, do_report_unexpected_exception); // Remove the download to keep the list empty for the next test. This @@ -395,7 +395,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { // Temporarily register a view that will get notified when the download we // are controlling becomes visible in the list of downloads. aList.addView({ - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { aList.removeView(this).then(null, do_report_unexpected_exception); // Remove the download to keep the list empty for the next test. This @@ -417,7 +417,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { channel.asyncOpen2({ contentListener: null, - onStartRequest: function(aRequest, aContext) + onStartRequest(aRequest, aContext) { let requestChannel = aRequest.QueryInterface(Ci.nsIChannel); this.contentListener = gExternalHelperAppService.doContent( @@ -425,12 +425,12 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { this.contentListener.onStartRequest(aRequest, aContext); }, - onStopRequest: function(aRequest, aContext, aStatusCode) + onStopRequest(aRequest, aContext, aStatusCode) { this.contentListener.onStopRequest(aRequest, aContext, aStatusCode); }, - onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, + onDataAvailable(aRequest, aContext, aInputStream, aOffset, aCount) { this.contentListener.onDataAvailable(aRequest, aContext, aInputStream, @@ -577,10 +577,10 @@ function startFakeServer() { let serverSocket = new ServerSocket(-1, true, -1); serverSocket.asyncListen({ - onSocketAccepted: function(aServ, aTransport) { + onSocketAccepted(aServ, aTransport) { aTransport.close(Cr.NS_BINDING_ABORTED); }, - onStopListening: function() { }, + onStopListening() { }, }); return serverSocket; } diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js b/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js index cce155716fd6..d470d33da908 100644 --- a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js +++ b/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js @@ -169,14 +169,14 @@ function promiseEntityID(aUrl) { }); channel.asyncOpen2({ - onStartRequest: function(aRequest) { + onStartRequest(aRequest) { if (aRequest instanceof Ci.nsIResumableChannel) { entityID = aRequest.entityID; } aRequest.cancel(Cr.NS_BINDING_ABORTED); }, - onStopRequest: function(aRequest, aContext, aStatusCode) { + onStopRequest(aRequest, aContext, aStatusCode) { if (aStatusCode == Cr.NS_BINDING_ABORTED) { deferred.resolve(entityID); } else { @@ -184,7 +184,7 @@ function promiseEntityID(aUrl) { } }, - onDataAvailable: function() {} + onDataAvailable() {} }); return deferred.promise; diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js b/toolkit/components/jsdownloads/test/unit/test_DownloadList.js index b3e24b0dba67..42cd77e784ee 100644 --- a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js +++ b/toolkit/components/jsdownloads/test/unit/test_DownloadList.js @@ -56,7 +56,7 @@ function promiseExpirableDownloadVisit(aSourceUrl) aResultCode); deferred.reject(ex); }, - handleResult: function() {}, + handleResult() {}, handleCompletion: function handleCompletion() { deferred.resolve(); } @@ -192,7 +192,7 @@ add_task(function* test_notifications_add_remove() // Check that we receive add notifications for existing elements. let addNotifications = 0; let viewOne = { - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { // The first download to be notified should be the first that was added. if (addNotifications == 0) { do_check_eq(aDownload, downloadOne); @@ -212,7 +212,7 @@ add_task(function* test_notifications_add_remove() // Check that we receive remove notifications. let removeNotifications = 0; let viewTwo = { - onDownloadRemoved: function(aDownload) { + onDownloadRemoved(aDownload) { do_check_eq(aDownload, downloadOne); removeNotifications++; }, @@ -257,7 +257,7 @@ add_task(function* test_notifications_change() // Check that we receive change notifications. let receivedOnDownloadChanged = false; yield list.addView({ - onDownloadChanged: function(aDownload) { + onDownloadChanged(aDownload) { do_check_eq(aDownload, downloadOne); receivedOnDownloadChanged = true; }, @@ -285,18 +285,18 @@ add_task(function* test_notifications_this() let receivedOnDownloadChanged = false; let receivedOnDownloadRemoved = false; let view = { - onDownloadAdded: function() { + onDownloadAdded() { do_check_eq(this, view); receivedOnDownloadAdded = true; }, - onDownloadChanged: function() { + onDownloadChanged() { // Only do this check once. if (!receivedOnDownloadChanged) { do_check_eq(this, view); receivedOnDownloadChanged = true; } }, - onDownloadRemoved: function() { + onDownloadRemoved() { do_check_eq(this, view); receivedOnDownloadRemoved = true; }, @@ -336,7 +336,7 @@ add_task(function* test_history_expiration() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved: function(aDownload) { + onDownloadRemoved(aDownload) { if (++removeNotifications == 2) { deferred.resolve(); } @@ -383,7 +383,7 @@ add_task(function* test_history_clear() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved: function(aDownload) { + onDownloadRemoved(aDownload) { if (++removeNotifications == 2) { deferred.resolve(); } @@ -419,7 +419,7 @@ add_task(function* test_removeFinished() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved: function(aDownload) { + onDownloadRemoved(aDownload) { do_check_true(aDownload == downloadOne || aDownload == downloadTwo || aDownload == downloadThree); @@ -555,7 +555,7 @@ add_task(function* test_DownloadSummary_notifications() // Check that we receive change notifications. let receivedOnSummaryChanged = false; yield summary.addView({ - onSummaryChanged: function() { + onSummaryChanged() { receivedOnSummaryChanged = true; }, }); diff --git a/toolkit/components/lz4/lz4.js b/toolkit/components/lz4/lz4.js index 8d4ffcf8e58e..70dd758e8537 100644 --- a/toolkit/components/lz4/lz4.js +++ b/toolkit/components/lz4/lz4.js @@ -150,7 +150,7 @@ exports.decompressFileContent = decompressFileContent; if (typeof Components != "undefined") { this.Lz4 = { - compressFileContent: compressFileContent, - decompressFileContent: decompressFileContent + compressFileContent, + decompressFileContent }; } diff --git a/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js b/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js index b26d554a8e6a..745f44dd81cd 100644 --- a/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js +++ b/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js @@ -45,12 +45,12 @@ const tests = [ // A basic listener that reads checks the if we sniffed properly. var listener = { - onStartRequest: function(request, context) { + onStartRequest(request, context) { do_check_eq(request.QueryInterface(Ci.nsIChannel).contentType, tests[testRan].expectedContentType); }, - onDataAvailable: function(request, context, stream, offset, count) { + onDataAvailable(request, context, stream, offset, count) { try { var bis = Components.classes["@mozilla.org/binaryinputstream;1"] .createInstance(Components.interfaces.nsIBinaryInputStream); @@ -61,7 +61,7 @@ var listener = { } }, - onStopRequest: function(request, context, status) { + onStopRequest(request, context, status) { testRan++; runNext(); } @@ -72,7 +72,7 @@ function setupChannel(url, flags) let uri = "http://localhost:" + httpserver.identity.primaryPort + url; var chan = NetUtil.newChannel({ - uri: uri, + uri, loadUsingSystemPrincipal: true, contentPolicyType: Ci.nsIContentPolicy.TYPE_MEDIA }); diff --git a/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js b/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js index ce30a5c1ba18..78cb68c038a3 100644 --- a/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js +++ b/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js @@ -46,12 +46,12 @@ const tests = [ // A basic listener that reads checks the if we sniffed properly. var listener = { - onStartRequest: function(request, context) { + onStartRequest(request, context) { do_print("Sniffing " + tests[testRan].path); do_check_eq(request.QueryInterface(Ci.nsIChannel).contentType, tests[testRan].expected); }, - onDataAvailable: function(request, context, stream, offset, count) { + onDataAvailable(request, context, stream, offset, count) { try { var bis = Components.classes["@mozilla.org/binaryinputstream;1"] .createInstance(Components.interfaces.nsIBinaryInputStream); @@ -62,7 +62,7 @@ var listener = { } }, - onStopRequest: function(request, context, status) { + onStopRequest(request, context, status) { testRan++; runNext(); } diff --git a/toolkit/components/microformats/microformat-shiv.js b/toolkit/components/microformats/microformat-shiv.js index f12d5208ad48..47651bbb88f8 100644 --- a/toolkit/components/microformats/microformat-shiv.js +++ b/toolkit/components/microformats/microformat-shiv.js @@ -43,7 +43,7 @@ var Microformats; // jshint ignore:line modules.Parser.prototype = { - init: function() { + init() { this.rootNode = null; this.document = null; this.options = { @@ -67,7 +67,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Object} */ - get: function(options) { + get(options) { var out = this.formatEmpty(), data = [], rels; @@ -126,7 +126,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Object} */ - getParent: function(node, options) { + getParent(node, options) { this.init(); options = (options) ? options : {}; @@ -144,7 +144,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} rootNode * @return {Int} */ - count: function( options ) { + count( options ) { var out = {}, items, classItems, @@ -194,7 +194,7 @@ var Microformats; // jshint ignore:line * @param {Objecte} options * @return {Boolean} */ - isMicroformat: function( node, options ) { + isMicroformat( node, options ) { var classes, i; @@ -227,7 +227,7 @@ var Microformats; // jshint ignore:line * @param {Objecte} options * @return {Boolean} */ - hasMicroformats: function( node, options ) { + hasMicroformats( node, options ) { var items, i; @@ -258,7 +258,7 @@ var Microformats; // jshint ignore:line * * @param {Array} maps */ - add: function( maps ) { + add( maps ) { maps.forEach(function(map) { if (map && map.root && map.name && map.properties) { modules.maps[map.name] = JSON.parse(JSON.stringify(map)); @@ -275,7 +275,7 @@ var Microformats; // jshint ignore:line * @param {Int} recursive * @return {Object} */ - getParentTreeWalk: function(node, options, recursive) { + getParentTreeWalk(node, options, recursive) { options = (options) ? options : {}; // recursive calls @@ -303,7 +303,7 @@ var Microformats; // jshint ignore:line * * @param {Object} options */ - getDOMContext: function( options ) { + getDOMContext( options ) { var nodes = modules.domUtils.getDOMContext( options ); this.rootNode = nodes.rootNode; this.document = nodes.document; @@ -316,7 +316,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Boolean} */ - prepareDOM: function( options ) { + prepareDOM( options ) { var baseTag, href; @@ -370,7 +370,7 @@ var Microformats; // jshint ignore:line * * @return {Object} */ - formatError: function() { + formatError() { var out = this.formatEmpty(); out.errors = this.errors; return out; @@ -382,7 +382,7 @@ var Microformats; // jshint ignore:line * * @return {Object} */ - formatEmpty: function() { + formatEmpty() { return { 'items': [], 'rels': {}, @@ -392,7 +392,7 @@ var Microformats; // jshint ignore:line // find microformats of a given type and return node structures - findFilterNodes: function(rootNode, filters) { + findFilterNodes(rootNode, filters) { if (modules.utils.isString(filters)) { filters = [filters]; } @@ -438,7 +438,7 @@ var Microformats; // jshint ignore:line * @param {Int} count * @param {Object} */ - appendCount: function(name, count, out) { + appendCount(name, count, out) { if (out[name]) { out[name] = out[name] + count; } else { @@ -454,7 +454,7 @@ var Microformats; // jshint ignore:line * @param {Array} filters * @return {Boolean} */ - shouldInclude: function(uf, filters) { + shouldInclude(uf, filters) { var i; if (modules.utils.isArray(filters) && filters.length > 0) { @@ -477,7 +477,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} includeRoot * @return {Array} */ - findRootNodes: function(rootNode, includeRoot) { + findRootNodes(rootNode, includeRoot) { var arr = null, out = [], classList = [], @@ -538,7 +538,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - walkRoot: function(node) { + walkRoot(node) { var context = this, children = [], child, @@ -577,7 +577,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - walkTree: function(node) { + walkTree(node) { var classes, out = [], obj, @@ -612,7 +612,7 @@ var Microformats; // jshint ignore:line * @param {Int} rootID * @param {Object} parentClasses */ - walkChildren: function(node, out, ufName, rootID, parentClasses) { + walkChildren(node, out, ufName, rootID, parentClasses) { var context = this, children = [], rootItem, @@ -777,7 +777,7 @@ var Microformats; // jshint ignore:line * @param {Object} uf * @return {String || Object} */ - getValue: function(node, className, uf) { + getValue(node, className, uf) { var value = ''; if (modules.utils.startWith(className, 'p-')) { @@ -806,7 +806,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getPValue: function(node, valueParse) { + getPValue(node, valueParse) { var out = ''; if (valueParse) { out = this.getValueClass(node, 'p'); @@ -846,7 +846,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Object} */ - getEValue: function(node) { + getEValue(node) { var out = {value: '', html: ''}; @@ -867,7 +867,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getUValue: function(node, valueParse) { + getUValue(node, valueParse) { var out = ''; if (valueParse) { out = this.getValueClass(node, 'u'); @@ -919,7 +919,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getDTValue: function(node, className, uf, valueParse) { + getDTValue(node, className, uf, valueParse) { var out = ''; if (valueParse) { @@ -974,7 +974,7 @@ var Microformats; // jshint ignore:line * @param {String} id * @param {String} propertyName */ - appendRootID: function(node, id, propertyName) { + appendRootID(node, id, propertyName) { if (this.hasRootID(node, id, propertyName) === false) { var rootids = []; if (modules.domUtils.hasAttribute(node, 'rootids')) { @@ -994,7 +994,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyName * @return {Boolean} */ - hasRootID: function(node, id, propertyName) { + hasRootID(node, id, propertyName) { var rootids = []; if (!modules.domUtils.hasAttribute(node, 'rootids')) { return false; @@ -1012,7 +1012,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyName * @return {String || null} */ - getValueClass: function(node, propertyType) { + getValueClass(node, propertyType) { var context = this, children = [], out = [], @@ -1068,7 +1068,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - getValueTitle: function(node) { + getValueTitle(node) { var out = [], items, i, @@ -1093,7 +1093,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Boolean} */ - hasHClass: function(node) { + hasHClass(node) { var classes = this.getUfClassNames(node); if (classes.root && classes.root.length > 0) { return true; @@ -1109,7 +1109,7 @@ var Microformats; // jshint ignore:line * @param {Array} ufNameArr * @return {Object} */ - getUfClassNames: function(node, ufNameArr) { + getUfClassNames(node, ufNameArr) { var context = this, out = { 'root': [], @@ -1258,7 +1258,7 @@ var Microformats; // jshint ignore:line * @param {String} name * @return {Object || null} */ - getMapping: function(name) { + getMapping(name) { var key; for (key in modules.maps) { if (modules.maps[key].root === name || key === name) { @@ -1275,7 +1275,7 @@ var Microformats; // jshint ignore:line * @param {String} name * @return {String || null} */ - getV2RootName: function(name) { + getV2RootName(name) { var key; for (key in modules.maps) { if (modules.maps[key].root === name) { @@ -1293,7 +1293,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyVersion * @return {Boolean} */ - isAllowedPropertyVersion: function(typeVersion, propertyVersion) { + isAllowedPropertyVersion(typeVersion, propertyVersion) { if (this.options.overlappingVersions === true) { return true; } @@ -1308,7 +1308,7 @@ var Microformats; // jshint ignore:line * @param {String} value * @return {Object} */ - createUfObject: function(names, typeVersion, value) { + createUfObject(names, typeVersion, value) { var out = {}; // is more than just whitespace @@ -1337,7 +1337,7 @@ var Microformats; // jshint ignore:line * * @param {Object} microformat */ - cleanUfObject: function( microformat ) { + cleanUfObject( microformat ) { delete microformat.times; delete microformat.dates; delete microformat.typeVersion; @@ -1353,7 +1353,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - removePropPrefix: function(text) { + removePropPrefix(text) { var i; i = this.propertyPrefixes.length; @@ -1374,7 +1374,7 @@ var Microformats; // jshint ignore:line * @param {String} attrName * @param {String} baseUrl */ - expandURLs: function(node, attrName, baseUrl) { + expandURLs(node, attrName, baseUrl) { var i, nodes, attr; @@ -1403,7 +1403,7 @@ var Microformats; // jshint ignore:line * * @param {Object} options */ - mergeOptions: function(options) { + mergeOptions(options) { var key; for (key in options) { if (options.hasOwnProperty(key)) { @@ -1418,7 +1418,7 @@ var Microformats; // jshint ignore:line * * @param {DOM Node} rootNode */ - removeRootIds: function(rootNode) { + removeRootIds(rootNode) { var arr, i; @@ -1435,7 +1435,7 @@ var Microformats; // jshint ignore:line * * @param {DOM Node} rootNode */ - clearUpDom: function(rootNode) { + clearUpDom(rootNode) { if (this.removeIncludes) { this.removeIncludes(rootNode); } @@ -1751,15 +1751,15 @@ var Microformats; // jshint ignore:line if (uf.value && !uf.altValue) { // first p-name of the h-* child if (modules.utils.startWith(parentPropertyName, 'p-') && propertyName === 'p-name') { - uf.altValue = {name: propertyName, value: value}; + uf.altValue = {name: propertyName, value}; } // if it's an e-* property element if (modules.utils.startWith(parentPropertyName, 'e-') && modules.utils.startWith(propertyName, 'e-')) { - uf.altValue = {name: propertyName, value: value}; + uf.altValue = {name: propertyName, value}; } // if it's an u-* property element if (modules.utils.startWith(parentPropertyName, 'u-') && propertyName === 'u-url') { - uf.altValue = {name: propertyName, value: value}; + uf.altValue = {name: propertyName, value}; } } return uf; @@ -2205,7 +2205,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isString: function( obj ) { + isString( obj ) { return typeof( obj ) === 'string'; }, @@ -2215,7 +2215,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isNumber: function( obj ) { + isNumber( obj ) { return !isNaN(parseFloat( obj )) && isFinite( obj ); }, @@ -2226,7 +2226,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isArray: function( obj ) { + isArray( obj ) { return obj && !( obj.propertyIsEnumerable( 'length' ) ) && typeof obj === 'object' && typeof obj.length === 'number'; }, @@ -2237,7 +2237,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isFunction: function(obj) { + isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }, @@ -2249,7 +2249,7 @@ var Microformats; // jshint ignore:line * @param {String} test * @return {Boolean} */ - startWith: function( text, test ) { + startWith( text, test ) { return (text.indexOf(test) === 0); }, @@ -2260,7 +2260,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - trim: function( text ) { + trim( text ) { if (text && this.isString(text)) { return (text.trim()) ? text.trim() : text.replace(/^\s+|\s+$/g, ''); } @@ -2276,7 +2276,7 @@ var Microformats; // jshint ignore:line * @param {String} character * @return {String} */ - replaceCharAt: function( text, index, character ) { + replaceCharAt( text, index, character ) { if (text && text.length > index) { return text.substr(0, index) + character + text.substr(index + character.length); } @@ -2290,7 +2290,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - trimWhitespace: function( text ) { + trimWhitespace( text ) { if (text && text.length) { var i = text.length, x = 0; @@ -2325,7 +2325,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isOnlyWhiteSpace: function( text ) { + isOnlyWhiteSpace( text ) { return !(/[^\t\n\r ]/.test( text )); }, @@ -2336,7 +2336,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Sring} */ - collapseWhiteSpace: function( text ) { + collapseWhiteSpace( text ) { return text.replace(/[\t\n\r ]+/g, ' '); }, @@ -2347,7 +2347,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - hasProperties: function( obj ) { + hasProperties( obj ) { var key; for (key in obj) { if ( obj.hasOwnProperty( key ) ) { @@ -2365,7 +2365,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} reverse * @return {Int} */ - sortObjects: function(property, reverse) { + sortObjects(property, reverse) { reverse = (reverse) ? -1 : 1; return function(a, b) { a = a[property]; @@ -2395,7 +2395,7 @@ var Microformats; // jshint ignore:line * * @return {Object || undefined} */ - getDOMParser: function() { + getDOMParser() { if (typeof DOMParser === "undefined") { try { return Components.classes["@mozilla.org/xmlextras/domparser;1"] @@ -2415,7 +2415,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {DOM Node} node */ - getDOMContext: function( options ) { + getDOMContext( options ) { // if a node is passed if (options.node) { @@ -2465,7 +2465,7 @@ var Microformats; // jshint ignore:line * @param {Dom Document} * @return {DOM Node} node */ - getTopMostNode: function( node ) { + getTopMostNode( node ) { // var doc = this.ownerDocument(node); // if(doc && doc.nodeType && doc.nodeType === 9 && doc.documentElement){ // return doc.documentElement; @@ -2481,7 +2481,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Dom Document} */ - ownerDocument: function(node) { + ownerDocument(node) { return node.ownerDocument; }, @@ -2492,7 +2492,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - textContent: function(node) { + textContent(node) { if (node.textContent) { return node.textContent; } else if (node.innerText) { @@ -2508,7 +2508,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - innerHTML: function(node) { + innerHTML(node) { return node.innerHTML; }, @@ -2520,7 +2520,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {Boolean} */ - hasAttribute: function(node, attributeName) { + hasAttribute(node, attributeName) { return node.hasAttribute(attributeName); }, @@ -2533,7 +2533,7 @@ var Microformats; // jshint ignore:line * @param {String} value * @return {Boolean} */ - hasAttributeValue: function(node, attributeName, value) { + hasAttributeValue(node, attributeName, value) { return (this.getAttributeList(node, attributeName).indexOf(value) > -1); }, @@ -2545,7 +2545,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {String || null} */ - getAttribute: function(node, attributeName) { + getAttribute(node, attributeName) { return node.getAttribute(attributeName); }, @@ -2557,7 +2557,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @param {String} attributeValue */ - setAttribute: function(node, attributeName, attributeValue) { + setAttribute(node, attributeName, attributeValue) { node.setAttribute(attributeName, attributeValue); }, @@ -2568,7 +2568,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @param {String} attributeName */ - removeAttribute: function(node, attributeName) { + removeAttribute(node, attributeName) { node.removeAttribute(attributeName); }, @@ -2580,7 +2580,7 @@ var Microformats; // jshint ignore:line * @param {String} id * @return {DOM Node} */ - getElementById: function(docNode, id) { + getElementById(docNode, id) { return docNode.querySelector( '#' + id ); }, @@ -2592,7 +2592,7 @@ var Microformats; // jshint ignore:line * @param {String} selector * @return {DOM Node} */ - querySelector: function(docNode, selector) { + querySelector(docNode, selector) { return docNode.querySelector( selector ); }, @@ -2604,7 +2604,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {Array} */ - getAttributeList: function(node, attributeName) { + getAttributeList(node, attributeName) { var out = [], attList; @@ -2627,7 +2627,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {NodeList} */ - getNodesByAttribute: function(node, attributeName) { + getNodesByAttribute(node, attributeName) { var selector = '[' + attributeName + ']'; return node.querySelectorAll(selector); }, @@ -2640,7 +2640,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {DOM NodeList} */ - getNodesByAttributeValue: function(rootNode, name, value) { + getNodesByAttributeValue(rootNode, name, value) { var arr = [], x = 0, i, @@ -2667,7 +2667,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {String || null} */ - getAttrValFromTagList: function(node, tagNames, attributeName) { + getAttrValFromTagList(node, tagNames, attributeName) { var i = tagNames.length; while (i--) { @@ -2689,7 +2689,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getSingleDescendant: function(node) { + getSingleDescendant(node) { return this.getDescendant( node, null, false ); }, @@ -2701,7 +2701,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getSingleDescendantOfType: function(node, tagNames) { + getSingleDescendantOfType(node, tagNames) { return this.getDescendant( node, tagNames, true ); }, @@ -2713,7 +2713,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getDescendant: function( node, tagNames, onlyOfType ) { + getDescendant( node, tagNames, onlyOfType ) { var i = node.children.length, countAll = 0, countOfType = 0, @@ -2750,7 +2750,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {Boolean} */ - hasTagName: function(node, tagNames) { + hasTagName(node, tagNames) { var i = tagNames.length; while (i--) { if (node.tagName.toLowerCase() === tagNames[i]) { @@ -2768,7 +2768,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} childNode * @return {DOM Node} */ - appendChild: function(node, childNode) { + appendChild(node, childNode) { return node.appendChild(childNode); }, @@ -2779,7 +2779,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} childNode * @return {DOM Node || null} */ - removeChild: function(childNode) { + removeChild(childNode) { if (childNode.parentNode) { return childNode.parentNode.removeChild(childNode); } @@ -2793,7 +2793,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {DOM Node} */ - clone: function(node) { + clone(node) { var newNode = node.cloneNode(true); newNode.removeAttribute('id'); return newNode; @@ -2806,7 +2806,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - getElementText: function( node ) { + getElementText( node ) { if (node && node.data) { return node.data; } @@ -2820,7 +2820,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - getOrderedAttributes: function( node ) { + getOrderedAttributes( node ) { var nodeStr = node.outerHTML, attrs = []; @@ -2841,7 +2841,7 @@ var Microformats; // jshint ignore:line * @param String} text * @return {String} */ - decodeEntities: function( doc, text ) { + decodeEntities( doc, text ) { // return text; return doc.createTextNode( text ).nodeValue; }, @@ -2853,7 +2853,7 @@ var Microformats; // jshint ignore:line * @param {DOM Document} document * @return {DOM Document} */ - cloneDocument: function( document ) { + cloneDocument( document ) { var newNode, newDocument = null; @@ -2872,7 +2872,7 @@ var Microformats; // jshint ignore:line * @param {DOM Document} document * @return {Boolean} */ - canCloneDocument: function( document ) { + canCloneDocument( document ) { return (document && document.importNode && document.implementation && document.implementation.createHTMLDocument); }, @@ -2883,7 +2883,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Int} */ - getChildIndex: function(node) { + getChildIndex(node) { var parent = node.parentNode, i = -1, child; @@ -2902,7 +2902,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - getNodePath: function(node) { + getNodePath(node) { var parent = node.parentNode, path = [], index = this.getChildIndex(node); @@ -2923,7 +2923,7 @@ var Microformats; // jshint ignore:line * @param {Array} path * @return {DOM Node} */ - getNodeByPath: function(document, path) { + getNodeByPath(document, path) { var node = document.documentElement, i = 0, index; @@ -2940,7 +2940,7 @@ var Microformats; // jshint ignore:line * @param {DOM node} node * @return {Array} */ - getChildren: function( node ) { + getChildren( node ) { return node.children; }, @@ -2951,7 +2951,7 @@ var Microformats; // jshint ignore:line * @param {String} tagName * @return {DOM node} */ - createNode: function( tagName ) { + createNode( tagName ) { return this.document.createElement(tagName); }, @@ -2963,7 +2963,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {DOM node} */ - createNodeWithText: function( tagName, text ) { + createNodeWithText( tagName, text ) { var node = this.document.createElement(tagName); node.innerHTML = text; return node; @@ -2980,7 +2980,7 @@ var Microformats; // jshint ignore:line /** * creates DOM objects needed to resolve URLs */ - init: function() { + init() { // this._domParser = new DOMParser(); this._domParser = modules.domUtils.getDOMParser(); // do not use a head tag it does not work with IE9 @@ -2998,7 +2998,7 @@ var Microformats; // jshint ignore:line * @param {String} baseUrl * @return {String} */ - resolve: function(url, baseUrl) { + resolve(url, baseUrl) { // use modern URL web API where we can if (modules.utils.isString(url) && modules.utils.isString(baseUrl) && url.indexOf('://') === -1) { // this try catch is required as IE has an URL object but no constuctor support @@ -3062,7 +3062,7 @@ var Microformats; // jshint ignore:line * clear all states * */ - clear: function() { + clear() { this.clearDate(); this.clearTime(); this.clearTimeZone(); @@ -3074,7 +3074,7 @@ var Microformats; // jshint ignore:line * clear date states * */ - clearDate: function() { + clearDate() { this.dY = -1; this.dM = -1; this.dD = -1; @@ -3086,7 +3086,7 @@ var Microformats; // jshint ignore:line * clear time states * */ - clearTime: function() { + clearTime() { this.tH = -1; this.tM = -1; this.tS = -1; @@ -3098,7 +3098,7 @@ var Microformats; // jshint ignore:line * clear timezone states * */ - clearTimeZone: function() { + clearTimeZone() { this.tzH = -1; this.tzM = -1; this.tzPN = '+'; @@ -3110,7 +3110,7 @@ var Microformats; // jshint ignore:line * resets the auto profile state * */ - setAutoProfileState: function() { + setAutoProfileState() { this.autoProfile = { sep: 'T', dsep: '-', @@ -3128,7 +3128,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parse: function( dateString, format ) { + parse( dateString, format ) { this.clear(); var parts = [], @@ -3218,7 +3218,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseDate: function( dateString, format ) { + parseDate( dateString, format ) { this.clearDate(); var parts = []; @@ -3263,7 +3263,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseTime: function( timeString, format ) { + parseTime( timeString, format ) { this.clearTime(); var parts = []; @@ -3297,7 +3297,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseTimeZone: function( timeString, format ) { + parseTimeZone( timeString, format ) { this.clearTimeZone(); var parts = []; @@ -3337,7 +3337,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - toString: function( format ) { + toString( format ) { var output = ''; if (format) { @@ -3374,7 +3374,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - toTimeString: function( format ) { + toTimeString( format ) { var out = ''; if (format) { @@ -3417,7 +3417,7 @@ var Microformats; // jshint ignore:line * set the current profile to W3C Note, RFC 3339, HTML5, or auto profile * */ - setFormatSep: function() { + setFormatSep() { switch ( this.format.toLowerCase() ) { case 'rfc3339': this.sep = 'T'; @@ -3456,7 +3456,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasFullDate: function() { + hasFullDate() { return (this.dY !== -1 && this.dM !== -1 && this.dD !== -1); }, @@ -3466,7 +3466,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasDate: function() { + hasDate() { return (this.dY !== -1); }, @@ -3476,7 +3476,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasTime: function() { + hasTime() { return (this.tH !== -1); }, @@ -3485,7 +3485,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasTimeZone: function() { + hasTimeZone() { return (this.tzH !== -1); } @@ -3503,7 +3503,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - hasAM: function( text ) { + hasAM( text ) { text = text.toLowerCase(); return (text.indexOf('am') > -1 || text.indexOf('a.m.') > -1); }, @@ -3515,7 +3515,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - hasPM: function( text ) { + hasPM( text ) { text = text.toLowerCase(); return (text.indexOf('pm') > -1 || text.indexOf('p.m.') > -1); }, @@ -3527,7 +3527,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - removeAMPM: function( text ) { + removeAMPM( text ) { return text.replace('pm', '').replace('p.m.', '').replace('am', '').replace('a.m.', ''); }, @@ -3538,7 +3538,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isDuration: function( text ) { + isDuration( text ) { if (modules.utils.isString( text )) { text = text.toLowerCase(); if (modules.utils.startWith(text, 'p') ) { @@ -3556,7 +3556,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isTime: function( text ) { + isTime( text ) { if (modules.utils.isString(text)) { text = text.toLowerCase(); text = modules.utils.trim( text ); @@ -3592,7 +3592,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - parseAmPmTime: function( text ) { + parseAmPmTime( text ) { var out = text, times = []; @@ -3643,7 +3643,7 @@ var Microformats; // jshint ignore:line * @param {String} format ( Modules.ISODate profile format ) * @return {Object} Modules.ISODate */ - dateTimeUnion: function(date, time, format) { + dateTimeUnion(date, time, format) { var isodate = new modules.ISODate(date, format), isotime = new modules.ISODate(); @@ -3670,7 +3670,7 @@ var Microformats; // jshint ignore:line * @param {String} format ( Modules.ISODate profile format ) * @return {Object} Modules.ISODate */ - concatFragments: function(arr, format) { + concatFragments(arr, format) { var out = new modules.ISODate(), i = 0, value = ''; @@ -3721,7 +3721,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Array} Modules.ISODate */ - splitTimeAndZone: function( text ) { + splitTimeAndZone( text ) { var out = [text], chars = ['-', '+', 'z', 'Z'], i = chars.length; @@ -3762,7 +3762,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - parse: function(doc, node, textFormat) { + parse(doc, node, textFormat) { var out; this.textFormat = (textFormat) ? textFormat : this.textFormat; if (this.textFormat === 'normalised') { @@ -3784,7 +3784,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - parseText: function( doc, text, textFormat ) { + parseText( doc, text, textFormat ) { var node = modules.domUtils.createNodeWithText( 'div', text ); return this.parse( doc, node, textFormat ); }, @@ -3797,7 +3797,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - formatText: function( doc, text, textFormat ) { + formatText( doc, text, textFormat ) { this.textFormat = (textFormat) ? textFormat : this.textFormat; if (text) { var out = '', @@ -3821,7 +3821,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - normalise: function( doc, text ) { + normalise( doc, text ) { text = text.replace( / /g, ' ') ; // exchanges html entity for space into space char text = modules.utils.collapseWhiteSpace( text ); // removes linefeeds, tabs and addtional spaces text = modules.domUtils.decodeEntities( doc, text ); // decode HTML entities @@ -3836,7 +3836,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - walkTreeForText: function( node ) { + walkTreeForText( node ) { var out = '', j = 0; @@ -3882,7 +3882,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - parse: function( node ) { + parse( node ) { var out = '', j = 0; @@ -3907,7 +3907,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - walkTreeForHtml: function( node ) { + walkTreeForHtml( node ) { var out = '', j = 0; diff --git a/toolkit/components/narrate/NarrateControls.jsm b/toolkit/components/narrate/NarrateControls.jsm index bfee9dd96ff5..3ad889d82cc2 100644 --- a/toolkit/components/narrate/NarrateControls.jsm +++ b/toolkit/components/narrate/NarrateControls.jsm @@ -137,7 +137,7 @@ function NarrateControls(mm, win, languagePromise) { } NarrateControls.prototype = { - handleEvent: function(evt) { + handleEvent(evt) { switch (evt.type) { case "change": if (evt.target.id == "narrate-rate-input") { @@ -163,7 +163,7 @@ NarrateControls.prototype = { /** * Returns true if synth voices are available. */ - _setupVoices: function() { + _setupVoices() { return this._languagePromise.then(language => { this.voiceSelect.clear(); let win = this._win; @@ -211,7 +211,7 @@ NarrateControls.prototype = { }); }, - _getVoicePref: function() { + _getVoicePref() { let voicePref = Services.prefs.getCharPref("narrate.voice"); try { return JSON.parse(voicePref); @@ -220,12 +220,12 @@ NarrateControls.prototype = { } }, - _onRateInput: function(evt) { + _onRateInput(evt) { AsyncPrefs.set("narrate.rate", parseInt(evt.target.value, 10)); this.narrator.setRate(this._convertRate(evt.target.value)); }, - _onVoiceChange: function() { + _onVoiceChange() { let voice = this.voice; this.narrator.setVoice(voice); this._languagePromise.then(language => { @@ -237,7 +237,7 @@ NarrateControls.prototype = { }); }, - _onButtonClick: function(evt) { + _onButtonClick(evt) { switch (evt.target.id) { case "narrate-skip-previous": this.narrator.skipPrevious(); @@ -262,7 +262,7 @@ NarrateControls.prototype = { } }, - _updateSpeechControls: function(speaking) { + _updateSpeechControls(speaking) { let dropdown = this._doc.getElementById("narrate-dropdown"); dropdown.classList.toggle("keep-open", speaking); dropdown.classList.toggle("speaking", speaking); @@ -281,7 +281,7 @@ NarrateControls.prototype = { } }, - _createVoiceLabel: function(voice) { + _createVoiceLabel(voice) { // This is a highly imperfect method of making human-readable labels // for system voices. Because each platform has a different naming scheme // for voices, we use a different method for each platform. @@ -304,7 +304,7 @@ NarrateControls.prototype = { } }, - _getLanguageName: function(lang) { + _getLanguageName(lang) { if (!this._langStrings) { this._langStrings = Services.strings.createBundle( "chrome://global/locale/languageNames.properties "); @@ -318,7 +318,7 @@ NarrateControls.prototype = { } }, - _convertRate: function(rate) { + _convertRate(rate) { // We need to convert a relative percentage value to a fraction rate value. // eg. -100 is half the speed, 100 is twice the speed in percentage, // 0.5 is half the speed and 2 is twice the speed in fractions. diff --git a/toolkit/components/narrate/Narrator.jsm b/toolkit/components/narrate/Narrator.jsm index 4af9c7eed604..03bec2500cf0 100644 --- a/toolkit/components/narrate/Narrator.jsm +++ b/toolkit/components/narrate/Narrator.jsm @@ -53,7 +53,7 @@ Narrator.prototype = { // For example, paragraphs. But nested anchors and other elements // are not interesting since their text already appears in their // parent's textContent. - acceptNode: function(node) { + acceptNode(node) { if (this._matches.has(node.parentNode)) { // Reject sub-trees of accepted nodes. return nf.FILTER_REJECT; @@ -106,7 +106,7 @@ Narrator.prototype = { this._win.speechSynthesis.pending; }, - _getVoice: function(voiceURI) { + _getVoice(voiceURI) { if (!this._voiceMap || !this._voiceMap.has(voiceURI)) { this._voiceMap = new Map( this._win.speechSynthesis.getVoices().map(v => [v.voiceURI, v])); @@ -115,7 +115,7 @@ Narrator.prototype = { return this._voiceMap.get(voiceURI); }, - _isParagraphInView: function(paragraph) { + _isParagraphInView(paragraph) { if (!paragraph) { return false; } @@ -124,13 +124,13 @@ Narrator.prototype = { return bb.top >= 0 && bb.top < this._win.innerHeight; }, - _sendTestEvent: function(eventType, detail) { + _sendTestEvent(eventType, detail) { let win = this._win; win.dispatchEvent(new win.CustomEvent(eventType, { detail: Cu.cloneInto(detail, win.document) })); }, - _speakInner: function() { + _speakInner() { this._win.speechSynthesis.cancel(); let tw = this._treeWalker; let paragraph = tw.currentNode; @@ -235,7 +235,7 @@ Narrator.prototype = { }); }, - start: function(speechOptions) { + start(speechOptions) { this._speechOptions = { rate: speechOptions.rate, voice: this._getVoice(speechOptions.voice) @@ -264,32 +264,32 @@ Narrator.prototype = { }); }, - stop: function() { + stop() { this._stopped = true; this._win.speechSynthesis.cancel(); }, - skipNext: function() { + skipNext() { this._win.speechSynthesis.cancel(); }, - skipPrevious: function() { + skipPrevious() { this._goBackParagraphs(this._timeIntoParagraph < PREV_THRESHOLD ? 2 : 1); }, - setRate: function(rate) { + setRate(rate) { this._speechOptions.rate = rate; /* repeat current paragraph */ this._goBackParagraphs(1); }, - setVoice: function(voice) { + setVoice(voice) { this._speechOptions.voice = this._getVoice(voice); /* repeat current paragraph */ this._goBackParagraphs(1); }, - _goBackParagraphs: function(count) { + _goBackParagraphs(count) { let tw = this._treeWalker; for (let i = 0; i < count; i++) { if (!tw.previousNode()) { @@ -316,7 +316,7 @@ Highlighter.prototype = { * @param {Number} startOffset the start offset * @param {Number} length the length in characters of the range */ - highlight: function(startOffset, length) { + highlight(startOffset, length) { let containerRect = this.container.getBoundingClientRect(); let range = this._getRange(startOffset, startOffset + length); let rangeRects = range.getClientRects(); @@ -362,7 +362,7 @@ Highlighter.prototype = { /** * Releases reference to container and removes all highlight nodes. */ - remove: function() { + remove() { for (let node of this._nodes) { node.remove(); } @@ -376,7 +376,7 @@ Highlighter.prototype = { * * @param {Number} count number of nodes needed */ - _getFreshHighlightNodes: function(count) { + _getFreshHighlightNodes(count) { let doc = this.container.ownerDocument; let nodes = Array.from(this._nodes); @@ -403,7 +403,7 @@ Highlighter.prototype = { * @param {Number} startOffset the start offset * @param {Number} endOffset the end offset */ - _getRange: function(startOffset, endOffset) { + _getRange(startOffset, endOffset) { let doc = this.container.ownerDocument; let i = 0; let treeWalker = doc.createTreeWalker( diff --git a/toolkit/components/narrate/VoiceSelect.jsm b/toolkit/components/narrate/VoiceSelect.jsm index b283a06b39f4..4d3ff82b9e24 100644 --- a/toolkit/components/narrate/VoiceSelect.jsm +++ b/toolkit/components/narrate/VoiceSelect.jsm @@ -37,7 +37,7 @@ function VoiceSelect(win, label) { } VoiceSelect.prototype = { - add: function(label, value) { + add(label, value) { let option = this._doc.createElement("button"); option.dataset.value = value; option.classList.add("option"); @@ -48,7 +48,7 @@ VoiceSelect.prototype = { return option; }, - addOptions: function(options) { + addOptions(options) { let selected = null; for (let option of options) { if (option.selected) { @@ -61,11 +61,11 @@ VoiceSelect.prototype = { this._select(selected || this.options[0], true); }, - clear: function() { + clear() { this.listbox.innerHTML = ""; }, - toggleList: function(force, focus = true) { + toggleList(force, focus = true) { if (this.element.classList.toggle("open", force)) { if (focus) { (this.selected || this.options[0]).focus(); @@ -84,7 +84,7 @@ VoiceSelect.prototype = { } }, - handleEvent: function(evt) { + handleEvent(evt) { let target = evt.target; switch (evt.type) { @@ -131,7 +131,7 @@ VoiceSelect.prototype = { } }, - _getPagedOption: function(option, up) { + _getPagedOption(option, up) { let height = elem => elem.getBoundingClientRect().height; let listboxHeight = height(this.listbox); @@ -148,7 +148,7 @@ VoiceSelect.prototype = { return next; }, - _keyPressedButton: function(evt) { + _keyPressedButton(evt) { if (evt.altKey && (evt.key === "ArrowUp" || evt.key === "ArrowUp")) { this.toggleList(true); return; @@ -178,7 +178,7 @@ VoiceSelect.prototype = { } }, - _keyPressedInBox: function(evt) { + _keyPressedInBox(evt) { let toFocus; let cur = this._doc.activeElement; @@ -212,7 +212,7 @@ VoiceSelect.prototype = { } }, - _select: function(option, suppressEvent = false) { + _select(option, suppressEvent = false) { let oldSelected = this.selected; if (oldSelected) { oldSelected.removeAttribute("aria-selected"); @@ -233,7 +233,7 @@ VoiceSelect.prototype = { } }, - _updateDropdownHeight: function(now) { + _updateDropdownHeight(now) { let updateInner = () => { let winHeight = this._win.innerHeight; let listbox = this.listbox; @@ -252,7 +252,7 @@ VoiceSelect.prototype = { } }, - _getOptionFromValue: function(value) { + _getOptionFromValue(value) { return Array.from(this.options).find(o => o.dataset.value === value); }, diff --git a/toolkit/components/narrate/test/NarrateTestUtils.jsm b/toolkit/components/narrate/test/NarrateTestUtils.jsm index 302e5c9928b8..227a7cf2b100 100644 --- a/toolkit/components/narrate/test/NarrateTestUtils.jsm +++ b/toolkit/components/narrate/test/NarrateTestUtils.jsm @@ -24,7 +24,7 @@ this.NarrateTestUtils = { BACK: "#narrate-skip-previous", FORWARD: "#narrate-skip-next", - isVisible: function(element) { + isVisible(element) { let style = element.ownerDocument.defaultView.getComputedStyle(element, ""); if (style.display == "none") { return false; @@ -42,7 +42,7 @@ this.NarrateTestUtils = { return true; }, - isStoppedState: function(window, ok) { + isStoppedState(window, ok) { let $ = window.document.querySelector.bind(window.document); ok($(this.BACK).disabled, "back button is disabled"); ok($(this.FORWARD).disabled, "forward button is disabled"); @@ -52,7 +52,7 @@ this.NarrateTestUtils = { ok($(this.START).title == "Start", "Button tooltip is correct"); }, - isStartedState: function(window, ok) { + isStartedState(window, ok) { let $ = window.document.querySelector.bind(window.document); ok(!$(this.BACK).disabled, "back button is enabled"); ok(!$(this.FORWARD).disabled, "forward button is enabled"); @@ -62,7 +62,7 @@ this.NarrateTestUtils = { ok($(this.STOP).title == "Stop", "Button tooltip is correct"); }, - selectVoice: function(window, voiceUri) { + selectVoice(window, voiceUri) { if (!this.isVisible(window.document.querySelector(this.VOICE_OPTIONS))) { window.document.querySelector(this.VOICE_SELECT).click(); } @@ -76,11 +76,11 @@ this.NarrateTestUtils = { return voiceOption.classList.contains("selected"); }, - getEventUtils: function(window) { + getEventUtils(window) { let eventUtils = { "_EU_Ci": Components.interfaces, "_EU_Cc": Components.classes, - window: window, + window, parent: window, navigator: window.navigator, KeyboardEvent: window.KeyboardEvent, @@ -91,7 +91,7 @@ this.NarrateTestUtils = { return eventUtils; }, - getReaderReadyPromise: function(window) { + getReaderReadyPromise(window) { return new Promise(resolve => { function observeReady(subject, topic) { if (subject == window) { @@ -108,13 +108,13 @@ this.NarrateTestUtils = { }); }, - waitForNarrateToggle: function(window) { + waitForNarrateToggle(window) { let toggle = window.document.querySelector(this.TOGGLE); return ContentTaskUtils.waitForCondition( () => !toggle.hidden, ""); }, - waitForPrefChange: function(pref) { + waitForPrefChange(pref) { return new Promise(resolve => { function observeChange() { Services.prefs.removeObserver(pref, observeChange); @@ -125,18 +125,18 @@ this.NarrateTestUtils = { }); }, - sendBoundaryEvent: function(window, name, charIndex, charLength) { + sendBoundaryEvent(window, name, charIndex, charLength) { let detail = { type: "boundary", args: { name, charIndex, charLength } }; window.dispatchEvent(new window.CustomEvent("testsynthevent", - { detail: detail })); + { detail })); }, - isWordHighlightGone: function(window, ok) { + isWordHighlightGone(window, ok) { let $ = window.document.querySelector.bind(window.document); ok(!$(".narrate-word-highlight"), "No more word highlights exist"); }, - getWordHighlights: function(window) { + getWordHighlights(window) { let $$ = window.document.querySelectorAll.bind(window.document); let nodes = Array.from($$(".narrate-word-highlight")); return nodes.map(node => { diff --git a/toolkit/components/passwordmgr/LoginHelper.jsm b/toolkit/components/passwordmgr/LoginHelper.jsm index f63832762138..be0fc32aac73 100644 --- a/toolkit/components/passwordmgr/LoginHelper.jsm +++ b/toolkit/components/passwordmgr/LoginHelper.jsm @@ -517,7 +517,7 @@ this.LoginHelper = { } else { window.openDialog("chrome://passwordmgr/content/passwordManager.xul", "Toolkit:PasswordManager", "", - {filterString : filterString}); + {filterString}); } }, diff --git a/toolkit/components/passwordmgr/LoginImport.jsm b/toolkit/components/passwordmgr/LoginImport.jsm index 8f4ce246b087..9d620dd43ade 100644 --- a/toolkit/components/passwordmgr/LoginImport.jsm +++ b/toolkit/components/passwordmgr/LoginImport.jsm @@ -137,19 +137,19 @@ this.LoginImport.prototype = { this.store.data.logins.push({ id: this.store.data.nextId++, - hostname: hostname, - httpRealm: httpRealm, - formSubmitURL: formSubmitURL, - usernameField: usernameField, - passwordField: passwordField, - encryptedUsername: encryptedUsername, - encryptedPassword: encryptedPassword, - guid: guid, - encType: encType, - timeCreated: timeCreated, - timeLastUsed: timeLastUsed, - timePasswordChanged: timePasswordChanged, - timesUsed: timesUsed, + hostname, + httpRealm, + formSubmitURL, + usernameField, + passwordField, + encryptedUsername, + encryptedPassword, + guid, + encType, + timeCreated, + timeLastUsed, + timePasswordChanged, + timesUsed, }); } catch (ex) { Cu.reportError("Error importing login: " + ex); diff --git a/toolkit/components/passwordmgr/LoginManagerContent.jsm b/toolkit/components/passwordmgr/LoginManagerContent.jsm index c6926f2a713c..998b6c991181 100644 --- a/toolkit/components/passwordmgr/LoginManagerContent.jsm +++ b/toolkit/components/passwordmgr/LoginManagerContent.jsm @@ -235,7 +235,7 @@ var LoginManagerContent = { let loginsFound = LoginHelper.vanillaObjectsToLogins(msg.data.logins); request.promise.resolve({ form: request.form, - loginsFound: loginsFound, + loginsFound, recipes: msg.data.recipes, }); break; @@ -276,10 +276,10 @@ var LoginManagerContent = { let messageManager = messageManagerFromWindow(win); // XXX Weak?? - let requestData = { form: form }; - let messageData = { formOrigin: formOrigin, - actionOrigin: actionOrigin, - options: options }; + let requestData = { form }; + let messageData = { formOrigin, + actionOrigin, + options }; return this._sendRequest(messageManager, requestData, "RemoteLogins:findLogins", @@ -306,14 +306,14 @@ var LoginManagerContent = { null; let requestData = {}; - let messageData = { formOrigin: formOrigin, - actionOrigin: actionOrigin, + let messageData = { formOrigin, + actionOrigin, searchString: aSearchString, - previousResult: previousResult, + previousResult, rect: aRect, isSecure: InsecurePasswordUtils.isFormSecure(form), isPasswordField: aElement.type == "password", - remote: remote }; + remote }; return this._sendRequest(messageManager, requestData, "RemoteLogins:autoCompleteLogins", @@ -608,7 +608,7 @@ var LoginManagerContent = { pwFields[pwFields.length] = { index : i, - element : element + element }; } @@ -881,8 +881,8 @@ var LoginManagerContent = { let openerTopWindow = win.opener ? win.opener.top : null; messageManager.sendAsyncMessage("RemoteLogins:onFormSubmit", - { hostname: hostname, - formSubmitURL: formSubmitURL, + { hostname, + formSubmitURL, usernameField: mockUsername, newPasswordField: mockPassword, oldPasswordField: mockOldPassword }, diff --git a/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm b/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm index c5671a56905d..74a9bd8ca1a4 100644 --- a/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm +++ b/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm @@ -164,10 +164,10 @@ var LoginManagerContextMenu = { */ _fillTargetField(login, inputElement, browser, documentURI) { LoginManagerParent.fillForm({ - browser: browser, + browser, loginFormOrigin: documentURI.prePath, - login: login, - inputElement: inputElement, + login, + inputElement, }).catch(Cu.reportError); }, diff --git a/toolkit/components/passwordmgr/LoginManagerParent.jsm b/toolkit/components/passwordmgr/LoginManagerParent.jsm index ec951344c971..52ce73f239eb 100644 --- a/toolkit/components/passwordmgr/LoginManagerParent.jsm +++ b/toolkit/components/passwordmgr/LoginManagerParent.jsm @@ -38,7 +38,7 @@ var LoginManagerParent = { */ _recipeManager: null, - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"] .getService(Ci.nsIMessageListenerManager); mm.addMessageListener("RemoteLogins:findLogins", this); @@ -57,7 +57,7 @@ var LoginManagerParent = { }); }, - receiveMessage: function(msg) { + receiveMessage(msg) { let data = msg.data; switch (msg.name) { case "RemoteLogins:findLogins": { @@ -156,7 +156,7 @@ var LoginManagerParent = { if (!showMasterPassword && !Services.logins.isLoggedIn) { try { target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId: requestId, + requestId, logins: [], recipes, }); @@ -175,14 +175,14 @@ var LoginManagerParent = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - observe: function(subject, topic, data) { + observe(subject, topic, data) { log("Got deferred sendLoginDataToChild notification:", topic); // Only run observer once. Services.obs.removeObserver(this, "passwordmgr-crypto-login"); Services.obs.removeObserver(this, "passwordmgr-crypto-loginCanceled"); if (topic == "passwordmgr-crypto-loginCanceled") { target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId: requestId, + requestId, logins: [], recipes, }); @@ -219,13 +219,13 @@ var LoginManagerParent = { // doesn't support structured cloning. var jsLogins = LoginHelper.loginsToVanillaObjects(logins); target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId: requestId, + requestId, logins: jsLogins, recipes, }); }), - doAutocompleteSearch: function({ formOrigin, actionOrigin, + doAutocompleteSearch({ formOrigin, actionOrigin, searchString, previousResult, rect, requestId, isSecure, isPasswordField, remote }, target) { @@ -283,12 +283,12 @@ var LoginManagerParent = { // doesn't support structured cloning. var jsLogins = LoginHelper.loginsToVanillaObjects(matchingLogins); target.messageManager.sendAsyncMessage("RemoteLogins:loginsAutoCompleted", { - requestId: requestId, + requestId, logins: jsLogins, }); }, - onFormSubmit: function(hostname, formSubmitURL, + onFormSubmit(hostname, formSubmitURL, usernameField, newPasswordField, oldPasswordField, openerTopWindow, target) { diff --git a/toolkit/components/passwordmgr/content/passwordManager.js b/toolkit/components/passwordmgr/content/passwordManager.js index 3dbb499cc3ab..941fe8bdf390 100644 --- a/toolkit/components/passwordmgr/content/passwordManager.js +++ b/toolkit/components/passwordmgr/content/passwordManager.js @@ -35,7 +35,7 @@ let removeAllButton; let signonsTree; let signonReloadDisplay = { - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic == "passwordmgr-storage-changed") { switch (data) { case "addLogin": diff --git a/toolkit/components/passwordmgr/crypto-SDR.js b/toolkit/components/passwordmgr/crypto-SDR.js index 82797bb0d844..d88e87d91140 100644 --- a/toolkit/components/passwordmgr/crypto-SDR.js +++ b/toolkit/components/passwordmgr/crypto-SDR.js @@ -37,14 +37,14 @@ LoginManagerCrypto_SDR.prototype = { return this.__utfConverter; }, - _utfConverterReset : function() { + _utfConverterReset() { this.__utfConverter = null; }, _uiBusy : false, - init : function() { + init() { // Check to see if the internal PKCS#11 token has been initialized. // If not, set a blank password. let tokenDB = Cc["@mozilla.org/security/pk11tokendb;1"]. @@ -66,7 +66,7 @@ LoginManagerCrypto_SDR.prototype = { * Returns the encrypted string, or throws an exception if there was a * problem. */ - encrypt : function(plainText) { + encrypt(plainText) { let cipherText = null; let wasLoggedIn = this.isLoggedIn; @@ -107,7 +107,7 @@ LoginManagerCrypto_SDR.prototype = { * Returns the decrypted string, or throws an exception if there was a * problem. */ - decrypt : function(cipherText) { + decrypt(cipherText) { let plainText = null; let wasLoggedIn = this.isLoggedIn; @@ -178,7 +178,7 @@ LoginManagerCrypto_SDR.prototype = { /* * _notifyObservers */ - _notifyObservers : function(topic) { + _notifyObservers(topic) { this.log("Prompted for a master password, notifying for " + topic); Services.obs.notifyObservers(null, topic, null); }, diff --git a/toolkit/components/passwordmgr/nsLoginInfo.js b/toolkit/components/passwordmgr/nsLoginInfo.js index 3baed81145ce..79ed276ce1e4 100644 --- a/toolkit/components/passwordmgr/nsLoginInfo.js +++ b/toolkit/components/passwordmgr/nsLoginInfo.js @@ -29,7 +29,7 @@ nsLoginInfo.prototype = { usernameField : null, passwordField : null, - init : function(aHostname, aFormSubmitURL, aHttpRealm, + init(aHostname, aFormSubmitURL, aHttpRealm, aUsername, aPassword, aUsernameField, aPasswordField) { this.hostname = aHostname; @@ -47,7 +47,7 @@ nsLoginInfo.prototype = { }); }, - equals : function(aLogin) { + equals(aLogin) { if (this.hostname != aLogin.hostname || this.formSubmitURL != aLogin.formSubmitURL || this.httpRealm != aLogin.httpRealm || @@ -60,7 +60,7 @@ nsLoginInfo.prototype = { return true; }, - clone : function() { + clone() { let clone = Cc["@mozilla.org/login-manager/loginInfo;1"]. createInstance(Ci.nsILoginInfo); clone.init(this.hostname, this.formSubmitURL, this.httpRealm, diff --git a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js index 54c6f53d8c7d..971ff0afbef4 100644 --- a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js +++ b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js @@ -46,7 +46,7 @@ LoginManagerPromptFactory.prototype = { _asyncPrompts : {}, _asyncPromptInProgress : false, - observe : function(subject, topic, data) { + observe(subject, topic, data) { this.log("Observed: " + topic); if (topic == "quit-application-granted") { this._cancelPendingPrompts(); @@ -60,13 +60,13 @@ LoginManagerPromptFactory.prototype = { } }, - getPrompt : function(aWindow, aIID) { + getPrompt(aWindow, aIID) { var prompt = new LoginManagerPrompter().QueryInterface(aIID); prompt.init(aWindow, this); return prompt; }, - _doAsyncPrompt : function() { + _doAsyncPrompt() { if (this._asyncPromptInProgress) { this.log("_doAsyncPrompt bypassed, already in progress"); return; @@ -115,7 +115,7 @@ LoginManagerPromptFactory.prototype = { var runnable = { cancel: false, - run : function() { + run() { var ok = false; if (!this.cancel) { try { @@ -185,7 +185,7 @@ LoginManagerPromptFactory.prototype = { }, - _cancelPendingPrompts : function() { + _cancelPendingPrompts() { this.log("Canceling all pending prompts..."); var asyncPrompts = this._asyncPrompts; this.__proto__._asyncPrompts = {}; @@ -321,7 +321,7 @@ LoginManagerPrompter.prototype = { * Wrapper around the prompt service prompt. Saving random fields here * doesn't really make sense and therefore isn't implemented. */ - prompt : function(aDialogTitle, aText, aPasswordRealm, + prompt(aDialogTitle, aText, aPasswordRealm, aSavePassword, aDefaultText, aResult) { if (aSavePassword != Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER) throw new Components.Exception("prompt only supports SAVE_PASSWORD_NEVER", @@ -342,7 +342,7 @@ LoginManagerPrompter.prototype = { * Looks up a username and password in the database. Will prompt the user * with a dialog, even if a username and password are found. */ - promptUsernameAndPassword : function(aDialogTitle, aText, aPasswordRealm, + promptUsernameAndPassword(aDialogTitle, aText, aPasswordRealm, aSavePassword, aUsername, aPassword) { this.log("===== promptUsernameAndPassword() called ====="); @@ -443,7 +443,7 @@ LoginManagerPrompter.prototype = { * with a dialog with a text field and ok/cancel buttons. If the user * allows it, then the password will be saved in the database. */ - promptPassword : function(aDialogTitle, aText, aPasswordRealm, + promptPassword(aDialogTitle, aText, aPasswordRealm, aSavePassword, aPassword) { this.log("===== promptPassword called() ====="); @@ -519,7 +519,7 @@ LoginManagerPrompter.prototype = { * arguments to let callers know the login can't be saved because we don't * know whether it's http or https. */ - _getRealmInfo : function(aRealmString) { + _getRealmInfo(aRealmString) { var httpRealm = /^.+ \(.+\)$/; if (httpRealm.test(aRealmString)) return [null, null, null]; @@ -547,7 +547,7 @@ LoginManagerPrompter.prototype = { * @param {int} aLevel * @param {nsIAuthInformation} aAuthInfo */ - promptAuth : function(aChannel, aLevel, aAuthInfo) { + promptAuth(aChannel, aLevel, aAuthInfo) { var selectedLogin = null; var checkbox = { value : false }; var checkboxLabel = null; @@ -678,7 +678,7 @@ LoginManagerPrompter.prototype = { return ok; }, - asyncPromptAuth : function(aChannel, aCallback, aContext, aLevel, aAuthInfo) { + asyncPromptAuth(aChannel, aCallback, aContext, aLevel, aAuthInfo) { var cancelable = null; try { @@ -731,7 +731,7 @@ LoginManagerPrompter.prototype = { /* ---------- nsILoginManagerPrompter prompts ---------- */ - init : function(aWindow = null, aFactory = null) { + init(aWindow = null, aFactory = null) { if (!aWindow) { // There may be no applicable window e.g. in a Sandbox or JSM. this._chromeWindow = null; @@ -759,7 +759,7 @@ LoginManagerPrompter.prototype = { this._opener = aOpener; }, - promptToSavePassword : function(aLogin) { + promptToSavePassword(aLogin) { this.log("promptToSavePassword"); var notifyObj = this._getPopupNote() || this._getNotifyBox(); if (notifyObj) @@ -771,7 +771,7 @@ LoginManagerPrompter.prototype = { /** * Displays a notification bar. */ - _showLoginNotification : function(aNotifyBox, aName, aText, aButtons) { + _showLoginNotification(aNotifyBox, aName, aText, aButtons) { var oldBar = aNotifyBox.getNotificationWithValue(aName); const priority = aNotifyBox.PRIORITY_INFO_MEDIUM; @@ -1014,7 +1014,7 @@ LoginManagerPrompter.prototype = { persistent: true, passwordNotificationType: type, hideClose: true, - eventCallback: function(topic) { + eventCallback(topic) { switch (topic) { case "showing": currentNotification = this; @@ -1072,7 +1072,7 @@ LoginManagerPrompter.prototype = { * @param aLogin * The login captured from the form. */ - _showSaveLoginNotification : function(aNotifyObj, aLogin) { + _showSaveLoginNotification(aNotifyObj, aLogin) { // Ugh. We can't use the strings from the popup window, because they // have the access key marked in the string (eg "Mo&zilla"), along // with some weird rules for handling access keys that do not occur @@ -1110,7 +1110,7 @@ LoginManagerPrompter.prototype = { label: rememberButtonText, accessKey: rememberButtonAccessKey, popup: null, - callback: function(aNotifyObj, aButton) { + callback(aNotifyObj, aButton) { pwmgr.addLogin(aLogin); } }, @@ -1120,7 +1120,7 @@ LoginManagerPrompter.prototype = { label: neverButtonText, accessKey: neverButtonAccessKey, popup: null, - callback: function(aNotifyObj, aButton) { + callback(aNotifyObj, aButton) { pwmgr.setLoginSavingEnabled(aLogin.hostname, false); } }, @@ -1130,7 +1130,7 @@ LoginManagerPrompter.prototype = { label: notNowButtonText, accessKey: notNowButtonAccessKey, popup: null, - callback: function() { /* NOP */ } + callback() { /* NOP */ } } ]; @@ -1141,7 +1141,7 @@ LoginManagerPrompter.prototype = { Services.obs.notifyObservers(aLogin, "passwordmgr-prompt-save", null); }, - _removeLoginNotifications : function() { + _removeLoginNotifications() { var popupNote = this._getPopupNote(); if (popupNote) popupNote = popupNote.getNotification("password"); @@ -1169,7 +1169,7 @@ LoginManagerPrompter.prototype = { * Called when we detect a new login in a form submission, * asks the user what to do. */ - _showSaveLoginDialog : function(aLogin) { + _showSaveLoginDialog(aLogin) { const buttonFlags = Ci.nsIPrompt.BUTTON_POS_1_DEFAULT + (Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_0) + (Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_1) + @@ -1292,7 +1292,7 @@ LoginManagerPrompter.prototype = { label: changeButtonText, accessKey: changeButtonAccessKey, popup: null, - callback: function(aNotifyObj, aButton) { + callback(aNotifyObj, aButton) { self._updateLogin(aOldLogin, aNewLogin); } }, @@ -1302,7 +1302,7 @@ LoginManagerPrompter.prototype = { label: dontChangeButtonText, accessKey: dontChangeButtonAccessKey, popup: null, - callback: function(aNotifyObj, aButton) { + callback(aNotifyObj, aButton) { // do nothing } } @@ -1361,7 +1361,7 @@ LoginManagerPrompter.prototype = { * * Note; XPCOM stupidity: |count| is just |logins.length|. */ - promptToChangePasswordWithUsernames : function(logins, count, aNewLogin) { + promptToChangePasswordWithUsernames(logins, count, aNewLogin) { this.log("promptToChangePasswordWithUsernames with count:", count); var usernames = logins.map(l => l.username); @@ -1419,7 +1419,7 @@ LoginManagerPrompter.prototype = { /** * Given a content DOM window, returns the chrome window and browser it's in. */ - _getChromeWindow: function(aWindow) { + _getChromeWindow(aWindow) { let windows = Services.wm.getEnumerator(null); while (windows.hasMoreElements()) { let win = windows.getNext(); @@ -1431,7 +1431,7 @@ LoginManagerPrompter.prototype = { return null; }, - _getNotifyWindow: function() { + _getNotifyWindow() { // Some sites pop up a temporary login window, which disappears // upon submission of credentials. We want to put the notification // bar in the opener window if this seems to be happening. @@ -1455,7 +1455,7 @@ LoginManagerPrompter.prototype = { * Returns the popup notification to this prompter, * or null if there isn't one available. */ - _getPopupNote : function() { + _getPopupNote() { let popupNote = null; try { @@ -1475,7 +1475,7 @@ LoginManagerPrompter.prototype = { * Returns the notification box to this prompter, or null if there isn't * a notification box available. */ - _getNotifyBox : function() { + _getNotifyBox() { let notifyBox = null; try { @@ -1496,7 +1496,7 @@ LoginManagerPrompter.prototype = { * is the same as some other existing login. So, pick a login with a * matching username, or return null. */ - _repickSelectedLogin : function(foundLogins, username) { + _repickSelectedLogin(foundLogins, username) { for (var i = 0; i < foundLogins.length; i++) if (foundLogins[i].username == username) return foundLogins[i]; @@ -1515,7 +1515,7 @@ LoginManagerPrompter.prototype = { * formatted if required. * */ - _getLocalizedString : function(key, formatArgs) { + _getLocalizedString(key, formatArgs) { if (formatArgs) return this._strBundle.formatStringFromName( key, formatArgs, formatArgs.length); @@ -1528,7 +1528,7 @@ LoginManagerPrompter.prototype = { * it's too long. This helps prevent an evil site from messing with the * "save password?" prompt too much. */ - _sanitizeUsername : function(username) { + _sanitizeUsername(username) { if (username.length > 30) { username = username.substring(0, 30); username += this._ellipsis; @@ -1543,7 +1543,7 @@ LoginManagerPrompter.prototype = { * Returns the hostname to use in a nsILoginInfo object (for example, * "http://example.com"). */ - _getFormattedHostname : function(aURI) { + _getFormattedHostname(aURI) { let uri; if (aURI instanceof Ci.nsIURI) { uri = aURI; @@ -1560,7 +1560,7 @@ LoginManagerPrompter.prototype = { * prompting purposes. Eg, "http://foo.com" --> "foo.com", or * "ftp://www.site.co.uk" --> "site.co.uk". */ - _getShortDisplayHost: function(aURIString) { + _getShortDisplayHost(aURIString) { var displayHost; var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"]. @@ -1586,7 +1586,7 @@ LoginManagerPrompter.prototype = { * Returns the hostname and realm for which authentication is being * requested, in the format expected to be used with nsILoginInfo. */ - _getAuthTarget : function(aChannel, aAuthInfo) { + _getAuthTarget(aChannel, aAuthInfo) { var hostname, realm; // If our proxy is demanding authentication, don't use the @@ -1634,7 +1634,7 @@ LoginManagerPrompter.prototype = { * If the authentication was for a Windows domain, we'll prepend the * return username with the domain. (eg, "domain\user") */ - _GetAuthInfo : function(aAuthInfo) { + _GetAuthInfo(aAuthInfo) { var username, password; var flags = aAuthInfo.flags; @@ -1654,7 +1654,7 @@ LoginManagerPrompter.prototype = { * domain out of the username if necessary and sets domain, username and * password on the auth information object. */ - _SetAuthInfo : function(aAuthInfo, username, password) { + _SetAuthInfo(aAuthInfo, username, password) { var flags = aAuthInfo.flags; if (flags & Ci.nsIAuthInformation.NEED_DOMAIN) { // Domain is separated from username by a backslash @@ -1671,12 +1671,12 @@ LoginManagerPrompter.prototype = { aAuthInfo.password = password; }, - _newAsyncPromptConsumer : function(aCallback, aContext) { + _newAsyncPromptConsumer(aCallback, aContext) { return { QueryInterface: XPCOMUtils.generateQI([Ci.nsICancelable]), callback: aCallback, context: aContext, - cancel: function() { + cancel() { this.callback.onAuthCancelled(this.context, false); this.callback = null; this.context = null; diff --git a/toolkit/components/passwordmgr/storage-json.js b/toolkit/components/passwordmgr/storage-json.js index 5bf75aab5071..bf9b13cc4e28 100644 --- a/toolkit/components/passwordmgr/storage-json.js +++ b/toolkit/components/passwordmgr/storage-json.js @@ -141,7 +141,7 @@ this.LoginManagerStorage_json.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: loginClone.guid, - encType: encType, + encType, timeCreated: loginClone.timeCreated, timeLastUsed: loginClone.timeLastUsed, timePasswordChanged: loginClone.timePasswordChanged, @@ -377,9 +377,9 @@ this.LoginManagerStorage_json.prototype = { findLogins(count, hostname, formSubmitURL, httpRealm) { let loginData = { - hostname: hostname, - formSubmitURL: formSubmitURL, - httpRealm: httpRealm + hostname, + formSubmitURL, + httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) @@ -397,9 +397,9 @@ this.LoginManagerStorage_json.prototype = { countLogins(hostname, formSubmitURL, httpRealm) { let loginData = { - hostname: hostname, - formSubmitURL: formSubmitURL, - httpRealm: httpRealm + hostname, + formSubmitURL, + httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) diff --git a/toolkit/components/passwordmgr/storage-mozStorage.js b/toolkit/components/passwordmgr/storage-mozStorage.js index f1f1273c70c5..54f640ae4f83 100644 --- a/toolkit/components/passwordmgr/storage-mozStorage.js +++ b/toolkit/components/passwordmgr/storage-mozStorage.js @@ -31,12 +31,12 @@ function Transaction(aDatabase) { } Transaction.prototype = { - commit : function() { + commit() { if (this._hasTransaction) this._db.commitTransaction(); }, - rollback : function() { + rollback() { if (this._hasTransaction) this._db.rollbackTransaction(); }, @@ -50,7 +50,7 @@ LoginManagerStorage_mozStorage.prototype = { classID : Components.ID("{8c2023b9-175c-477e-9761-44ae7b549756}"), QueryInterface : XPCOMUtils.generateQI([Ci.nsILoginManagerStorage, Ci.nsIInterfaceRequestor]), - getInterface : function(aIID) { + getInterface(aIID) { if (aIID.equals(Ci.nsIVariant)) { // Allows unwrapping the JavaScript object for regression tests. return this; @@ -155,7 +155,7 @@ LoginManagerStorage_mozStorage.prototype = { * Internal method used by regression tests only. It overrides the default * database location. */ - initWithFile : function(aDBFile) { + initWithFile(aDBFile) { if (aDBFile) this._signonsFile = aDBFile; @@ -163,7 +163,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - initialize : function() { + initialize() { this._dbStmts = {}; let isFirstRun; @@ -200,12 +200,12 @@ LoginManagerStorage_mozStorage.prototype = { * Internal method used by regression tests only. It is called before * replacing this storage module with a new instance. */ - terminate : function() { + terminate() { return Promise.resolve(); }, - addLogin : function(login) { + addLogin(login) { // Throws if there are bogus values. LoginHelper.checkLoginValues(login); @@ -254,7 +254,7 @@ LoginManagerStorage_mozStorage.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: loginClone.guid, - encType: encType, + encType, timeCreated: loginClone.timeCreated, timeLastUsed: loginClone.timeLastUsed, timePasswordChanged: loginClone.timePasswordChanged, @@ -280,7 +280,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - removeLogin : function(login) { + removeLogin(login) { let [idToDelete, storedLogin] = this._getIdForLogin(login); if (!idToDelete) throw new Error("No matching logins"); @@ -307,7 +307,7 @@ LoginManagerStorage_mozStorage.prototype = { LoginHelper.notifyStorageChanged("removeLogin", storedLogin); }, - modifyLogin : function(oldLogin, newLoginData) { + modifyLogin(oldLogin, newLoginData) { let [idToModify, oldStoredLogin] = this._getIdForLogin(oldLogin); if (!idToModify) throw new Error("No matching logins"); @@ -360,7 +360,7 @@ LoginManagerStorage_mozStorage.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: newLogin.guid, - encType: encType, + encType, timeCreated: newLogin.timeCreated, timeLastUsed: newLogin.timeLastUsed, timePasswordChanged: newLogin.timePasswordChanged, @@ -387,7 +387,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Returns an array of nsILoginInfo. */ - getAllLogins : function(count) { + getAllLogins(count) { let [logins, ids] = this._searchLogins({}); // decrypt entries for caller. @@ -406,7 +406,7 @@ LoginManagerStorage_mozStorage.prototype = { * * @return {nsILoginInfo[]} which are decrypted. */ - searchLogins : function(count, matchData) { + searchLogins(count, matchData) { let realMatchData = {}; let options = {}; // Convert nsIPropertyBag to normal JS object @@ -444,7 +444,7 @@ LoginManagerStorage_mozStorage.prototype = { * is an array of encrypted nsLoginInfo and ids is an array of associated * ids in the database. */ - _searchLogins : function(matchData, aOptions = { + _searchLogins(matchData, aOptions = { schemeUpgrades: false, }) { let conditions = [], params = {}; @@ -551,7 +551,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Moves a login to the deleted logins table */ - storeDeletedLogin : function(aLogin) { + storeDeletedLogin(aLogin) { let stmt = null; try { this.log("Storing " + aLogin.guid + " in deleted passwords\n"); @@ -572,7 +572,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Removes all logins from storage. */ - removeAllLogins : function() { + removeAllLogins() { this.log("Removing all logins"); let query; let stmt; @@ -600,11 +600,11 @@ LoginManagerStorage_mozStorage.prototype = { }, - findLogins : function(count, hostname, formSubmitURL, httpRealm) { + findLogins(count, hostname, formSubmitURL, httpRealm) { let loginData = { - hostname: hostname, - formSubmitURL: formSubmitURL, - httpRealm: httpRealm + hostname, + formSubmitURL, + httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) @@ -621,7 +621,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - countLogins : function(hostname, formSubmitURL, httpRealm) { + countLogins(hostname, formSubmitURL, httpRealm) { let _countLoginsHelper = (hostname, formSubmitURL, httpRealm) => { // Do checks for null and empty strings, adjust conditions and params @@ -670,7 +670,7 @@ LoginManagerStorage_mozStorage.prototype = { * found, both items will be null. The returned login contains the actual * stored login (useful for looking at the actual nsILoginMetaInfo values). */ - _getIdForLogin : function(login) { + _getIdForLogin(login) { let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) if (login[field] != '') @@ -705,7 +705,7 @@ LoginManagerStorage_mozStorage.prototype = { * statement being created. This fixes the cases where nulls are involved * and the empty string is supposed to be a wildcard match */ - _buildConditionsAndParams : function(hostname, formSubmitURL, httpRealm) { + _buildConditionsAndParams(hostname, formSubmitURL, httpRealm) { let conditions = [], params = {}; if (hostname == null) { @@ -736,9 +736,9 @@ LoginManagerStorage_mozStorage.prototype = { /** * Checks to see if the specified GUID already exists. */ - _isGuidUnique : function(guid) { + _isGuidUnique(guid) { let query = "SELECT COUNT(1) AS numLogins FROM moz_logins WHERE guid = :guid"; - let params = { guid: guid }; + let params = { guid }; let stmt, numLogins; try { @@ -761,7 +761,7 @@ LoginManagerStorage_mozStorage.prototype = { * Returns the encrypted username, password, and encrypton type for the specified * login. Can throw if the user cancels a master password entry. */ - _encryptLogin : function(login) { + _encryptLogin(login) { let encUsername = this._crypto.encrypt(login.username); let encPassword = this._crypto.encrypt(login.password); let encType = this._crypto.defaultEncType; @@ -781,7 +781,7 @@ LoginManagerStorage_mozStorage.prototype = { * to lose unencrypted entries (eg, because the user clicked Cancel * instead of entering their master password) */ - _decryptLogins : function(logins) { + _decryptLogins(logins) { let result = []; for (let login of logins) { @@ -809,7 +809,7 @@ LoginManagerStorage_mozStorage.prototype = { * Returns the wrapped statement for execution. Will use memoization * so that statements can be reused. */ - _dbCreateStatement : function(query, params) { + _dbCreateStatement(query, params) { let wrappedStmt = this._dbStmts[query]; // Memoize the statements if (!wrappedStmt) { @@ -829,7 +829,7 @@ LoginManagerStorage_mozStorage.prototype = { * Attempts to initialize the database. This creates the file if it doesn't * exist, performs any migrations, etc. Return if this is the first run. */ - _dbInit : function() { + _dbInit() { this.log("Initializing Database"); let isFirstRun = false; try { @@ -856,7 +856,7 @@ LoginManagerStorage_mozStorage.prototype = { return isFirstRun; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "profile-before-change": Services.obs.removeObserver(this, "profile-before-change"); @@ -865,27 +865,27 @@ LoginManagerStorage_mozStorage.prototype = { } }, - _dbCreate: function() { + _dbCreate() { this.log("Creating Database"); this._dbCreateSchema(); this._dbConnection.schemaVersion = DB_VERSION; }, - _dbCreateSchema : function() { + _dbCreateSchema() { this._dbCreateTables(); this._dbCreateIndices(); }, - _dbCreateTables : function() { + _dbCreateTables() { this.log("Creating Tables"); for (let name in this._dbSchema.tables) this._dbConnection.createTable(name, this._dbSchema.tables[name]); }, - _dbCreateIndices : function() { + _dbCreateIndices() { this.log("Creating Indices"); for (let name in this._dbSchema.indices) { let index = this._dbSchema.indices[name]; @@ -896,7 +896,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - _dbMigrate : function(oldVersion) { + _dbMigrate(oldVersion) { this.log("Attempting to migrate from version " + oldVersion); if (oldVersion > DB_VERSION) { @@ -943,7 +943,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 2 adds a GUID column. Existing logins are assigned a random GUID. */ - _dbMigrateToVersion2 : function() { + _dbMigrateToVersion2() { // Check to see if GUID column already exists, add if needed let query; if (!this._dbColumnExists("guid")) { @@ -975,7 +975,7 @@ LoginManagerStorage_mozStorage.prototype = { query = "UPDATE moz_logins SET guid = :guid WHERE id = :id"; for (let id of ids) { let params = { - id: id, + id, guid: this._uuidService.generateUUID().toString() }; @@ -997,7 +997,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 3 adds a encType column. */ - _dbMigrateToVersion3 : function() { + _dbMigrateToVersion3() { // Check to see if encType column already exists, add if needed let query; if (!this._dbColumnExists("encType")) { @@ -1057,7 +1057,7 @@ LoginManagerStorage_mozStorage.prototype = { * Version 4 adds timeCreated, timeLastUsed, timePasswordChanged, * and timesUsed columns */ - _dbMigrateToVersion4 : function() { + _dbMigrateToVersion4() { let query; // Add the new columns, if needed. for (let column of ["timeCreated", "timeLastUsed", "timePasswordChanged", "timesUsed"]) { @@ -1112,7 +1112,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 5 adds the moz_deleted_logins table */ - _dbMigrateToVersion5 : function() { + _dbMigrateToVersion5() { if (!this._dbConnection.tableExists("moz_deleted_logins")) { this._dbConnection.createTable("moz_deleted_logins", this._dbSchema.tables.moz_deleted_logins); } @@ -1122,7 +1122,7 @@ LoginManagerStorage_mozStorage.prototype = { * Version 6 migrates all the hosts from * moz_disabledHosts to the permission manager. */ - _dbMigrateToVersion6 : function() { + _dbMigrateToVersion6() { let disabledHosts = []; let query = "SELECT hostname FROM moz_disabledHosts"; let stmt; @@ -1158,7 +1158,7 @@ LoginManagerStorage_mozStorage.prototype = { * Sanity check to ensure that the columns this version of the code expects * are present in the DB we're using. */ - _dbAreExpectedColumnsPresent : function() { + _dbAreExpectedColumnsPresent() { let query = "SELECT " + "id, " + "hostname, " + @@ -1203,7 +1203,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Checks to see if the named column already exists. */ - _dbColumnExists : function(columnName) { + _dbColumnExists(columnName) { let query = "SELECT " + columnName + " FROM moz_logins"; try { let stmt = this._dbConnection.createStatement(query); @@ -1215,7 +1215,7 @@ LoginManagerStorage_mozStorage.prototype = { } }, - _dbClose : function() { + _dbClose() { this.log("Closing the DB connection."); // Finalize all statements to free memory, avoid errors later for (let query in this._dbStmts) { @@ -1238,7 +1238,7 @@ LoginManagerStorage_mozStorage.prototype = { * Called when database creation fails. Finalizes database statements, * closes the database connection, deletes the database file. */ - _dbCleanup : function(backup) { + _dbCleanup(backup) { this.log("Cleaning up DB file - close & remove & backup=" + backup); // Create backup file diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js index f2255b32738d..0b04042e3482 100644 --- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js @@ -19,7 +19,7 @@ add_task(function* test() { let modifiedLogin; let testNumber = 0; let testObserver = { - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic == "passwordmgr-dialog-updated") { switch (testNumber) { case 1: diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js index efe7c26c5d7c..4f841f042c34 100644 --- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js @@ -12,7 +12,7 @@ add_task(function* test() { isnot(tab, gBrowser.selectedTab, "New tab shouldn't be selected"); let listener = { - onOpenWindow: function(window) { + onOpenWindow(window) { var domwindow = window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindow); waitForFocus(() => { @@ -25,7 +25,7 @@ add_task(function* test() { }, domwindow); }, - onCloseWindow: function() { + onCloseWindow() { } }; diff --git a/toolkit/components/passwordmgr/test/prompt_common.js b/toolkit/components/passwordmgr/test/prompt_common.js index a72e04ba28eb..6749ea4db6a2 100644 --- a/toolkit/components/passwordmgr/test/prompt_common.js +++ b/toolkit/components/passwordmgr/test/prompt_common.js @@ -26,7 +26,7 @@ function startCallbackTimer() { var observer = SpecialPowers.wrapCallbackObject({ - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports, Ci.nsISupportsWeakReference]; @@ -35,7 +35,7 @@ var observer = SpecialPowers.wrapCallbackObject({ return this; }, - observe : function(subject, topic, data) { + observe(subject, topic, data) { var doc = getDialogDoc(); if (doc) handleDialog(doc, testNum); diff --git a/toolkit/components/passwordmgr/test/unit/test_notifications.js b/toolkit/components/passwordmgr/test/unit/test_notifications.js index d564c766aa08..0ff2253baa47 100644 --- a/toolkit/components/passwordmgr/test/unit/test_notifications.js +++ b/toolkit/components/passwordmgr/test/unit/test_notifications.js @@ -8,7 +8,7 @@ var expectedData; var TestObserver = { QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - observe : function(subject, topic, data) { + observe(subject, topic, data) { do_check_eq(topic, "passwordmgr-storage-changed"); do_check_eq(data, expectedNotification); diff --git a/toolkit/components/passwordmgr/test/unit/test_storage.js b/toolkit/components/passwordmgr/test/unit/test_storage.js index d65516d9b007..09ec96131164 100644 --- a/toolkit/components/passwordmgr/test/unit/test_storage.js +++ b/toolkit/components/passwordmgr/test/unit/test_storage.js @@ -31,7 +31,7 @@ add_task(function* test_storage_addLogin_nonascii() // Store the strings "user" and "pass" using similarly looking glyphs. let loginInfo = TestData.formLogin({ - hostname: hostname, + hostname, formSubmitURL: hostname, username: String.fromCharCode(533, 537, 7570, 345), password: String.fromCharCode(421, 259, 349, 537), diff --git a/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js b/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js index 36da8e8b72bb..7b869ab6ebb3 100644 --- a/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js +++ b/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js @@ -35,7 +35,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -63,7 +63,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -95,7 +95,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -123,7 +123,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -155,7 +155,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -183,7 +183,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -211,7 +211,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -239,7 +239,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -267,7 +267,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -295,7 +295,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -327,7 +327,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -355,7 +355,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -387,7 +387,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -415,7 +415,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [] }, { @@ -423,7 +423,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -451,7 +451,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [] }, ]; diff --git a/toolkit/components/perfmonitoring/AddonWatcher.jsm b/toolkit/components/perfmonitoring/AddonWatcher.jsm index 58decba85722..b081f97e98d2 100644 --- a/toolkit/components/perfmonitoring/AddonWatcher.jsm +++ b/toolkit/components/perfmonitoring/AddonWatcher.jsm @@ -44,7 +44,7 @@ this.AddonWatcher = { */ TOPIC_SLOW_ADDON_DETECTED: "addon-watcher-detected-slow-addon", - init: function() { + init() { this._initializedTimeStamp = Cu.now(); try { @@ -58,7 +58,7 @@ this.AddonWatcher = { this._idleThreshold = Preferences.get("browser.addon-watch.deactivate-after-idle-ms", 3000); this.paused = false; }, - uninit: function() { + uninit() { this.paused = true; }, _initializedTimeStamp: 0, @@ -87,7 +87,7 @@ this.AddonWatcher = { * {number} latestNotificationTimeStamp The timestamp of the latest user notification * that this add-on is slow. */ - _getAlerts: function(addonId) { + _getAlerts(addonId) { let alerts = this._alerts.get(addonId); if (!alerts) { alerts = { @@ -100,7 +100,7 @@ this.AddonWatcher = { return alerts; }, _alerts: new Map(), - _onSlowAddons: function(addons) { + _onSlowAddons(addons) { try { if (IdleService.idleTime >= this._idleThreshold) { // The application is idle. Maybe the computer is sleeping, or maybe @@ -202,10 +202,10 @@ this.AddonWatcher = { } }, - ignoreAddonForSession: function(addonid) { + ignoreAddonForSession(addonid) { this._ignoreList.add(addonid); }, - ignoreAddonPermanently: function(addonid) { + ignoreAddonPermanently(addonid) { this._ignoreList.add(addonid); try { let ignoreList = JSON.parse(Preferences.get("browser.addon-watch.ignore", "[]")) diff --git a/toolkit/components/perfmonitoring/PerformanceStats.jsm b/toolkit/components/perfmonitoring/PerformanceStats.jsm index 6b5fb117c49e..155009bb2916 100644 --- a/toolkit/components/perfmonitoring/PerformanceStats.jsm +++ b/toolkit/components/perfmonitoring/PerformanceStats.jsm @@ -79,7 +79,7 @@ Probe.prototype = { * If the probe was inactive, activate it. Note that activating a probe * can incur a memory or performance cost. */ - acquire: function() { + acquire() { if (this._counter == 0) { this._impl.isActive = true; Process.broadcast("acquire", [this._name]); @@ -92,7 +92,7 @@ Probe.prototype = { * * If this was the last client for this probe, deactivate it. */ - release: function() { + release() { this._counter--; if (this._counter == 0) { try { @@ -117,7 +117,7 @@ Probe.prototype = { * @return {object} An object containing the data extracted from this * probe. Actual format depends on the probe. */ - extract: function(xpcom) { + extract(xpcom) { if (!this._impl.isActive) { throw new Error(`Probe is inactive: ${this._name}`); } @@ -130,7 +130,7 @@ Probe.prototype = { * * @return {true} If `a` and `b` hold identical values. */ - isEqual: function(a, b) { + isEqual(a, b) { if (a == null && b == null) { return true; } @@ -149,7 +149,7 @@ Probe.prototype = { * @return {object} An object representing `a - b`. If `b` is * `null`, this is `a`. */ - subtract: function(a, b) { + subtract(a, b) { if (a == null) { throw new TypeError(); } @@ -159,7 +159,7 @@ Probe.prototype = { return this._impl.subtract(a, b); }, - importChildCompartments: function(parent, children) { + importChildCompartments(parent, children) { if (!Array.isArray(children)) { throw new TypeError(); } @@ -176,7 +176,7 @@ Probe.prototype = { return this._name; }, - compose: function(stats) { + compose(stats) { if (!Array.isArray(stats)) { throw new TypeError(); } @@ -221,17 +221,17 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringJank; }, - extract: function(xpcom) { + extract(xpcom) { let durations = xpcom.getDurations(); return { totalUserTime: xpcom.totalUserTime, totalSystemTime: xpcom.totalSystemTime, totalCPUTime: xpcom.totalUserTime + xpcom.totalSystemTime, - durations: durations, + durations, longestDuration: lastNonZero(durations) } }, - isEqual: function(a, b) { + isEqual(a, b) { // invariant: `a` and `b` are both non-null if (a.totalUserTime != b.totalUserTime) { return false; @@ -246,7 +246,7 @@ var Probes = { } return true; }, - subtract: function(a, b) { + subtract(a, b) { // invariant: `a` and `b` are both non-null let result = { totalUserTime: a.totalUserTime - b.totalUserTime, @@ -261,8 +261,8 @@ var Probes = { result.longestDuration = lastNonZero(result.durations); return result; }, - importChildCompartments: function() { /* nothing to do */ }, - compose: function(stats) { + importChildCompartments() { /* nothing to do */ }, + compose(stats) { let result = { totalUserTime: 0, totalSystemTime: 0, @@ -298,21 +298,21 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringCPOW; }, - extract: function(xpcom) { + extract(xpcom) { return { totalCPOWTime: xpcom.totalCPOWTime }; }, - isEqual: function(a, b) { + isEqual(a, b) { return a.totalCPOWTime == b.totalCPOWTime; }, - subtract: function(a, b) { + subtract(a, b) { return { totalCPOWTime: a.totalCPOWTime - b.totalCPOWTime }; }, - importChildCompartments: function() { /* nothing to do */ }, - compose: function(stats) { + importChildCompartments() { /* nothing to do */ }, + compose(stats) { let totalCPOWTime = 0; for (let stat of stats) { totalCPOWTime += stat.totalCPOWTime; @@ -335,21 +335,21 @@ var Probes = { ticks: new Probe("ticks", { set isActive(x) { /* this probe cannot be deactivated */ }, get isActive() { return true; }, - extract: function(xpcom) { + extract(xpcom) { return { ticks: xpcom.ticks }; }, - isEqual: function(a, b) { + isEqual(a, b) { return a.ticks == b.ticks; }, - subtract: function(a, b) { + subtract(a, b) { return { ticks: a.ticks - b.ticks }; }, - importChildCompartments: function() { /* nothing to do */ }, - compose: function(stats) { + importChildCompartments() { /* nothing to do */ }, + compose(stats) { let ticks = 0; for (let stat of stats) { ticks += stat.ticks; @@ -365,19 +365,19 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringPerCompartment; }, - extract: function(xpcom) { + extract(xpcom) { return null; }, - isEqual: function(a, b) { + isEqual(a, b) { return true; }, - subtract: function(a, b) { + subtract(a, b) { return true; }, - importChildCompartments: function(parent, children) { + importChildCompartments(parent, children) { parent.children = children; }, - compose: function(stats) { + compose(stats) { return null; }, }), @@ -447,7 +447,7 @@ PerformanceMonitor.prototype = { * @return {Promise} * @resolve {Snapshot} */ - _checkBeforeSnapshot: function(options) { + _checkBeforeSnapshot(options) { if (!this._finalizer) { throw new Error("dispose() has already been called, this PerformanceMonitor is not usable anymore"); } @@ -472,11 +472,11 @@ PerformanceMonitor.prototype = { } return probes; }, - promiseContentSnapshot: function(options = null) { + promiseContentSnapshot(options = null) { this._checkBeforeSnapshot(options); return (new ProcessSnapshot(performanceStatsService.getSnapshot())); }, - promiseSnapshot: function(options = null) { + promiseSnapshot(options = null) { let probes = this._checkBeforeSnapshot(options); return Task.spawn(function*() { let childProcesses = yield Process.broadcastAndCollect("collect", {probeNames: probes.map(p => p.name)}); @@ -496,7 +496,7 @@ PerformanceMonitor.prototype = { * Releasing probes as soon as they are unused is a good idea, as some probes * cost CPU and/or memory. */ - dispose: function() { + dispose() { if (!this._finalizer) { return; } @@ -573,7 +573,7 @@ this.PerformanceStats = { /** * Create a monitor for observing a set of performance probes. */ - getMonitor: function(probes) { + getMonitor(probes) { return PerformanceMonitor.make(probes); } }; @@ -640,7 +640,7 @@ PerformanceDataLeaf.prototype = { * * @return `true` if `this` and `to` have equal values in all fields. */ - equals: function(to) { + equals(to) { if (!(to instanceof PerformanceDataLeaf)) { throw new TypeError(); } @@ -661,7 +661,7 @@ PerformanceDataLeaf.prototype = { * * @return {PerformanceDiff} The performance usage between `to` and `this`. */ - subtract: function(to = null) { + subtract(to = null) { return (new PerformanceDiffLeaf(this, to)); } }; @@ -673,7 +673,7 @@ function PerformanceData(timestamp) { this._timestamp = timestamp; } PerformanceData.prototype = { - addChild: function(stat) { + addChild(stat) { if (!(stat instanceof PerformanceDataLeaf)) { throw new TypeError(); // FIXME } @@ -684,7 +684,7 @@ PerformanceData.prototype = { this._all.push(stat); stat.owner = this; }, - setParent: function(stat) { + setParent(stat) { if (!(stat instanceof PerformanceDataLeaf)) { throw new TypeError(); // FIXME } @@ -695,7 +695,7 @@ PerformanceData.prototype = { this._all.push(stat); stat.owner = this; }, - equals: function(to) { + equals(to) { if (this._parent && !to._parent) { return false; } @@ -719,7 +719,7 @@ PerformanceData.prototype = { } return true; }, - subtract: function(to = null) { + subtract(to = null) { return (new PerformanceDiff(this, to)); }, get addonId() { @@ -767,7 +767,7 @@ function PerformanceDiff(current, old = null) { } } PerformanceDiff.prototype = { - toString: function() { + toString() { return `[PerformanceDiff] ${this.key}`; }, get windowIds() { @@ -924,7 +924,7 @@ var Process = { * * NOOP if we are in a child process. */ - broadcast: function(topic, payload) { + broadcast(topic, payload) { if (!this.loader) { return; } diff --git a/toolkit/components/perfmonitoring/PerformanceWatcher.jsm b/toolkit/components/perfmonitoring/PerformanceWatcher.jsm index d0d034974967..994c057c59f6 100644 --- a/toolkit/components/perfmonitoring/PerformanceWatcher.jsm +++ b/toolkit/components/perfmonitoring/PerformanceWatcher.jsm @@ -95,20 +95,20 @@ ChildManager.prototype = { * Add a listener, which will be notified whenever a child process * reports a slow performance alert for this addon/window. */ - addListener: function(listener) { + addListener(listener) { this._listeners.add(listener); }, /** * Remove a listener. */ - removeListener: function(listener) { + removeListener(listener) { let deleted = this._listeners.delete(listener); if (!deleted) { throw new Error("Unknown listener"); } }, - listeners: function() { + listeners() { return this._listeners.values(); } }; @@ -216,7 +216,7 @@ function Observable(target) { } } Observable.prototype = { - addJankObserver: function(listener) { + addJankObserver(listener) { if (this._observers.has(listener)) { throw new TypeError(`Listener already registered for target ${this._key}`); } @@ -230,7 +230,7 @@ Observable.prototype = { this._process.addJankObserver(observer); }, - removeJankObserver: function(listener) { + removeJankObserver(listener) { let observer = this._observers.get(listener); if (!observer) { throw new TypeError(`No listener for target ${this._key}`); @@ -284,10 +284,10 @@ function Observer(listener) { this._listener = listener; } Observer.prototype = { - observe: function(...args) { + observe(...args) { this._listener(...args); }, - dispose: function() { + dispose() { this._monitor.dispose(); this.observe = function poison() { throw new Error("Internal error: I should have stopped receiving notifications"); @@ -350,14 +350,14 @@ this.PerformanceWatcher = { * If the listener listens to all add-ons/all webpages, it is triggered with * an array of {source, details}, as described above. */ - addPerformanceListener: function(target, listener) { + addPerformanceListener(target, listener) { if (typeof listener != "function") { throw new TypeError(); } let observable = Observable.get(target); observable.addJankObserver(listener); }, - removePerformanceListener: function(target, listener) { + removePerformanceListener(target, listener) { if (typeof listener != "function") { throw new TypeError(); } diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js b/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js index 8b674937282f..b7bc198e05b6 100644 --- a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js +++ b/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js @@ -64,25 +64,25 @@ function frameScript() { // A variant of `Assert` that doesn't spam the logs // in case of success. var SilentAssert = { - equal: function(a, b, msg) { + equal(a, b, msg) { if (a == b) { return; } Assert.equal(a, b, msg); }, - notEqual: function(a, b, msg) { + notEqual(a, b, msg) { if (a != b) { return; } Assert.notEqual(a, b, msg); }, - ok: function(a, msg) { + ok(a, msg) { if (a) { return; } Assert.ok(a, msg); }, - leq: function(a, b, msg) { + leq(a, b, msg) { this.ok(a <= b, `${msg}: ${a} <= ${b}`); } }; diff --git a/toolkit/components/perfmonitoring/tests/browser/head.js b/toolkit/components/perfmonitoring/tests/browser/head.js index 92258fd1b9d6..85e2ca5f2bb0 100644 --- a/toolkit/components/perfmonitoring/tests/browser/head.js +++ b/toolkit/components/perfmonitoring/tests/browser/head.js @@ -45,7 +45,7 @@ CPUBurner.prototype = { } return false; }), - dispose: function() { + dispose() { info(`CPUBurner: Closing tab for ${this.url}\n`); gBrowser.removeTab(this.tab); } @@ -142,7 +142,7 @@ function AlertListener(accept, {register, unregister}) { register(); } AlertListener.prototype = { - unregister: function() { + unregister() { this.reset(); if (this._unregistered) { info(`head.js: No need to unregister, we're already unregistered.\n`); @@ -153,7 +153,7 @@ AlertListener.prototype = { this._unregister(); info(`head.js: Unregistration complete.\n`); }, - reset: function() { + reset() { this.triggered = false; this.result = null; }, @@ -181,7 +181,7 @@ function AddonBurner(addonId = "fake add-on id: " + Math.random()) { } AddonBurner.prototype = Object.create(CPUBurner.prototype); Object.defineProperty(AddonBurner.prototype, "addonId", { - get: function() { + get() { return this._addonId; } }); diff --git a/toolkit/components/places/BookmarkHTMLUtils.jsm b/toolkit/components/places/BookmarkHTMLUtils.jsm index 5aff75e9d084..10db007368c6 100644 --- a/toolkit/components/places/BookmarkHTMLUtils.jsm +++ b/toolkit/components/places/BookmarkHTMLUtils.jsm @@ -1037,19 +1037,19 @@ BookmarkExporter.prototype = { _converterOut: null, - _write: function(aText) { + _write(aText) { this._converterOut.writeString(aText || ""); }, - _writeAttribute: function(aName, aValue) { + _writeAttribute(aName, aValue) { this._write(' ' + aName + '="' + aValue + '"'); }, - _writeLine: function(aText) { + _writeLine(aText) { this._write(aText + "\n"); }, - _writeHeader: function() { + _writeHeader() { this._writeLine(""); this._writeLine(" { this._rebuild(); }, - onError: function(errorCode) { + onError(errorCode) { if (errorCode != Ci.nsISearchInstallCallback.ERROR_DUPLICATE_ENGINE) { // Download error is shown by the search service return; diff --git a/toolkit/components/alerts/test/test_alerts.html b/toolkit/components/alerts/test/test_alerts.html index 2e55aa5ffa8a..b210af4b6d9a 100644 --- a/toolkit/components/alerts/test/test_alerts.html +++ b/toolkit/components/alerts/test/test_alerts.html @@ -21,7 +21,7 @@ var observer = { alertShow: false, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { is(aData, "foobarcookie", "Checking whether the alert cookie was passed correctly"); if (aTopic == "alertclickcallback") { todo(false, "Did someone click the notification while running mochitests? (Please don't.)"); diff --git a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html index 65c79f3bb78b..dc4acbd01cd1 100644 --- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html +++ b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html @@ -76,14 +76,14 @@ var startupComplete = new Promise(resolve => startupCompleteResolver = resolve); function proxyChannelListener() { } proxyChannelListener.prototype = { - onStartRequest: function(request, context) { + onStartRequest(request, context) { startupCompleteResolver(); }, - onStopRequest: function(request, context, status) { } + onStopRequest(request, context, status) { } }; var resolveCallback = SpecialPowers.wrapCallbackObject({ - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -91,7 +91,7 @@ var resolveCallback = SpecialPowers.wrapCallbackObject({ return this; }, - onProxyAvailable : function(req, uri, pi, status) { + onProxyAvailable(req, uri, pi, status) { initLogins(pi); // I'm cheating a bit here... We should probably do some magic foo to get diff --git a/toolkit/components/passwordmgr/test/test_master_password.html b/toolkit/components/passwordmgr/test/test_master_password.html index c8884811f7c6..1b2d5f48194d 100644 --- a/toolkit/components/passwordmgr/test/test_master_password.html +++ b/toolkit/components/passwordmgr/test/test_master_password.html @@ -128,7 +128,7 @@ function handleDialog(doc, testNumber) { } var outerWindowObserver = { - observe: function(id) { + observe(id) { SpecialPowers.removeObserver(outerWindowObserver, "outer-window-destroyed"); var func; if (testNum == 1) diff --git a/toolkit/components/passwordmgr/test/test_prompt_async.html b/toolkit/components/passwordmgr/test/test_prompt_async.html index 03bea611bc8f..4cb08e0959b6 100644 --- a/toolkit/components/passwordmgr/test/test_prompt_async.html +++ b/toolkit/components/passwordmgr/test/test_prompt_async.html @@ -39,7 +39,7 @@ windowsOpen : 0, windowsRegistered : 0, - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -47,7 +47,7 @@ return this; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic === "domwindowopened") { this.windowsOpen++; this.windowsRegistered++; @@ -59,14 +59,14 @@ } }, - shutdown: function() { + shutdown() { var observerService = SpecialPowers.Cc["@mozilla.org/observer-service;1"] .getService(Ci.nsIObserverService); observerService.removeObserver(this, "domwindowopened"); observerService.removeObserver(this, "domwindowclosed"); }, - reset: function() { + reset() { this.windowsOpen = 0; this.windowsRegistered = 0; } @@ -130,7 +130,7 @@ } var resolveCallback = SpecialPowers.wrapCallbackObject({ - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -138,7 +138,7 @@ return this; }, - onProxyAvailable : function(req, uri, pi, status) { + onProxyAvailable(req, uri, pi, status) { initLogins(pi); doTest(testNum); } diff --git a/toolkit/components/printing/content/printPreviewBindings.xml b/toolkit/components/printing/content/printPreviewBindings.xml index 6b279d5cca42..6054c21733a8 100644 --- a/toolkit/components/printing/content/printPreviewBindings.xml +++ b/toolkit/components/printing/content/printPreviewBindings.xml @@ -219,8 +219,8 @@ } this.mMessageManager.sendAsyncMessage("Printing:Preview:Navigate", { - navType: navType, - pageNum: pageNum, + navType, + pageNum, }); ]]> @@ -242,8 +242,8 @@ var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService); var promptStr = this.mScaleLabel.value; var renameTitle = this.mCustomTitle; - var result = {value:value}; - var confirmed = promptService.prompt(window, renameTitle, promptStr, result, null, {value:value}); + var result = {value}; + var confirmed = promptService.prompt(window, renameTitle, promptStr, result, null, {value}); if (!confirmed || (!result.value) || (result.value == "") || result.value == value) { return -1; } diff --git a/toolkit/components/satchel/test/test_form_autocomplete.html b/toolkit/components/satchel/test/test_form_autocomplete.html index 57750af28e5c..447841df00ac 100644 --- a/toolkit/components/satchel/test/test_form_autocomplete.html +++ b/toolkit/components/satchel/test/test_form_autocomplete.html @@ -1032,7 +1032,7 @@ function runTest() { function addEntry(name, value) { - updateFormHistory({ op : "add", fieldname : name, value: value }, runTest); + updateFormHistory({ op : "add", fieldname : name, value }, runTest); } // Runs the next test when scroll event occurs diff --git a/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html b/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html index 540eeacf4b29..8ccd1ef65d87 100644 --- a/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html +++ b/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html @@ -24,7 +24,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=998893 { op : "bump", fieldname: "field1", value: "Default text option" }, { op : "bump", fieldname: "field1", value: "New value option" }, ], { - handleCompletion: function() { + handleCompletion() { sendAsyncMessage("Test:Resume"); }, }); diff --git a/toolkit/content/widgets/autocomplete.xml b/toolkit/content/widgets/autocomplete.xml index ac20f255a93f..92df64a34be0 100644 --- a/toolkit/content/widgets/autocomplete.xml +++ b/toolkit/content/widgets/autocomplete.xml @@ -618,16 +618,16 @@ _autocomplete: this, _kGlobalClipboard: Components.interfaces.nsIClipboard.kGlobalClipboard, supportsCommand: aCommand => aCommand == "cmd_paste", - doCommand: function(aCommand) { + doCommand(aCommand) { this._autocomplete._valueIsPasted = true; this._autocomplete.editor.paste(this._kGlobalClipboard); this._autocomplete._valueIsPasted = false; }, - isCommandEnabled: function(aCommand) { + isCommandEnabled(aCommand) { return this._autocomplete.editor.isSelectionEditable && this._autocomplete.editor.canPaste(this._kGlobalClipboard); }, - onEvent: function() {} + onEvent() {} }) ]]> @@ -2353,7 +2353,7 @@ extends="chrome://global/content/bindings/popup.xml#popup"> let [, type, params] = aUrl.match(/^moz-action:([^,]+),(.*)$/); let action = { - type: type, + type, }; try { diff --git a/toolkit/content/widgets/editor.xml b/toolkit/content/widgets/editor.xml index 637586dc2c74..0fd0eb24c26a 100644 --- a/toolkit/content/widgets/editor.xml +++ b/toolkit/content/widgets/editor.xml @@ -26,7 +26,7 @@ Date: Thu, 29 Dec 2016 13:24:51 -0800 Subject: [PATCH 089/229] Backed out changeset 57a62a57c996 (bug 1326174) for test_utils.py failures a=backout --- testing/marionette/assert.js | 28 +--- testing/marionette/driver.js | 135 ++++++++---------- .../tests/unit/test_cookies.py | 12 -- .../tests/unit/test_navigation.py | 8 +- .../tests/unit/test_shadow_dom.py | 8 +- 5 files changed, 64 insertions(+), 127 deletions(-) diff --git a/testing/marionette/assert.js b/testing/marionette/assert.js index b9bf6ae0eb76..9705105466fb 100644 --- a/testing/marionette/assert.js +++ b/testing/marionette/assert.js @@ -8,7 +8,6 @@ const {classes: Cc, interfaces: Ci, utils: Cu} = Components; Cu.import("resource://gre/modules/AppConstants.jsm"); Cu.import("resource://gre/modules/Preferences.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); Cu.import("chrome://marionette/content/error.js"); @@ -31,7 +30,7 @@ this.assert = {}; * If current browser is not Firefox. */ assert.firefox = function (msg = "") { - msg = msg || "Only supported in Firefox"; + msg = msg || "Expected Firefox"; assert.that(isFirefox, msg, UnsupportedOperationError)(); }; @@ -45,7 +44,7 @@ assert.firefox = function (msg = "") { * If current browser is not Fennec. */ assert.fennec = function (msg = "") { - msg = msg || "Only supported in Fennec"; + msg = msg || "Expected Fennec"; assert.that(isFennec, msg, UnsupportedOperationError)(); }; @@ -59,29 +58,10 @@ assert.fennec = function (msg = "") { * If the current browser is not B2G. */ assert.b2g = function (msg = "") { - msg = msg || "Only supported in B2G"; + msg = msg || "Expected B2G" assert.that(isB2G, msg, UnsupportedOperationError)(); }; -/** - * Asserts that the current |context| is content. - * - * @param {string} context - * Context to test. - * @param {string=} msg - * Custom error message. - * - * @return {string} - * |context| is returned unaltered. - * - * @throws {UnsupportedOperationError} - * If |context| is not content. - */ -assert.content = function (context, msg = "") { - msg = msg || "Only supported in content context"; - assert.that(c => c.toString() == "content", msg, UnsupportedOperationError)(context); -} - /** * Asserts that the current browser is a mobile browser, that is either * B2G or Fennec. @@ -93,7 +73,7 @@ assert.content = function (context, msg = "") { * If the current browser is not B2G or Fennec. */ assert.mobile = function (msg = "") { - msg = msg || "Only supported in Fennec or B2G"; + msg = msg || "Expected Fennec or B2G"; assert.that(() => isFennec() || isB2G(), msg, UnsupportedOperationError)(); }; diff --git a/testing/marionette/driver.js b/testing/marionette/driver.js index b6341f642f0b..4db4ccb8e90f 100644 --- a/testing/marionette/driver.js +++ b/testing/marionette/driver.js @@ -1015,26 +1015,32 @@ GeckoDriver.prototype.executeJSScript = function* (cmd, resp) { * URL to navigate to. */ GeckoDriver.prototype.get = function*(cmd, resp) { - assert.content(this.context); - let url = cmd.parameters.url; - let get = this.listener.get({url: url, pageTimeout: this.pageTimeout}); - // TODO(ato): Bug 1242595 - let id = this.listener.activeMessageId; + switch (this.context) { + case Context.CONTENT: + let get = this.listener.get({url: url, pageTimeout: this.pageTimeout}); + // TODO(ato): Bug 1242595 + let id = this.listener.activeMessageId; - // If a remoteness update interrupts our page load, this will never return - // We need to re-issue this request to correctly poll for readyState and - // send errors. - this.curBrowser.pendingCommands.push(() => { - cmd.parameters.command_id = id; - cmd.parameters.pageTimeout = this.pageTimeout; - this.mm.broadcastAsyncMessage( - "Marionette:pollForReadyState" + this.curBrowser.curFrameId, - cmd.parameters); - }); + // If a remoteness update interrupts our page load, this will never return + // We need to re-issue this request to correctly poll for readyState and + // send errors. + this.curBrowser.pendingCommands.push(() => { + cmd.parameters.command_id = id; + cmd.parameters.pageTimeout = this.pageTimeout; + this.mm.broadcastAsyncMessage( + "Marionette:pollForReadyState" + this.curBrowser.curFrameId, + cmd.parameters); + }); - yield get; + yield get; + break; + + case Context.CHROME: + throw new UnsupportedOperationError("Cannot navigate in chrome context"); + break; + } }; /** @@ -1095,22 +1101,16 @@ GeckoDriver.prototype.getPageSource = function* (cmd, resp) { /** Go back in history. */ GeckoDriver.prototype.goBack = function*(cmd, resp) { - assert.content(this.context); - yield this.listener.goBack(); }; /** Go forward in history. */ GeckoDriver.prototype.goForward = function*(cmd, resp) { - assert.content(this.context); - yield this.listener.goForward(); }; /** Refresh the page. */ GeckoDriver.prototype.refresh = function*(cmd, resp) { - assert.content(this.context); - yield this.listener.refresh(); }; @@ -1270,7 +1270,9 @@ GeckoDriver.prototype.getWindowPosition = function (cmd, resp) { * Object with |x| and |y| coordinates. */ GeckoDriver.prototype.setWindowPosition = function (cmd, resp) { - assert.firefox() + if (this.appName != "Firefox") { + throw new UnsupportedOperationError("Unable to set the window position on mobile"); + } let {x, y} = cmd.parameters; assert.positiveInteger(x); @@ -1616,8 +1618,7 @@ GeckoDriver.prototype.singleTap = function*(cmd, resp) { switch (this.context) { case Context.CHROME: - throw new UnsupportedOperationError( - "Command 'singleTap' is not yet available in chrome context"); + throw new WebDriverError("Command 'singleTap' is not available in chrome context"); case Context.CONTENT: this.addFrameCloseListener("tap"); @@ -1639,8 +1640,7 @@ GeckoDriver.prototype.performActions = function(cmd, resp) { switch (this.context) { case Context.CHROME: throw new UnsupportedOperationError( - "Command 'performActions' is not yet available in chrome context"); - + "Command 'performActions' is not available in chrome context"); case Context.CONTENT: return this.listener.performActions({"actions": cmd.parameters.actions}); } @@ -1650,14 +1650,7 @@ GeckoDriver.prototype.performActions = function(cmd, resp) { * Release all the keys and pointer buttons that are currently depressed. */ GeckoDriver.prototype.releaseActions = function(cmd, resp) { - switch (this.context) { - case Context.CHROME: - throw new UnsupportedOperationError( - "Command 'releaseActions' is not yet available in chrome context"); - - case Context.CONTENT: - return this.listener.releaseActions(); - } + return this.listener.releaseActions(); }; /** @@ -1675,9 +1668,12 @@ GeckoDriver.prototype.actionChain = function*(cmd, resp) { switch (this.context) { case Context.CHROME: - // be conservative until this has a use case and is established - // to work as expected in Fennec - assert.firefox() + if (this.appName != "Firefox") { + // be conservative until this has a use case and is established + // to work as expected on b2g/fennec + throw new WebDriverError( + "Command 'actionChain' is not available in chrome context"); + } let win = this.getCurrentWindow(); resp.body.value = yield this.legacyactions.dispatchActions( @@ -1702,8 +1698,7 @@ GeckoDriver.prototype.actionChain = function*(cmd, resp) { GeckoDriver.prototype.multiAction = function*(cmd, resp) { switch (this.context) { case Context.CHROME: - throw new UnsupportedOperationError( - "Command 'multiAction' is not yet available in chrome context"); + throw new WebDriverError("Command 'multiAction' is not available in chrome context"); case Context.CONTENT: this.addFrameCloseListener("multi action chain"); @@ -1800,15 +1795,7 @@ GeckoDriver.prototype.findElements = function*(cmd, resp) { /** Return the active element on the page. */ GeckoDriver.prototype.getActiveElement = function*(cmd, resp) { - switch (this.context) { - case Context.CHROME: - throw new UnsupportedOperationError( - "Command 'getActiveElement' is not yet available in chrome context"); - - case Context.CONTENT: - resp.body.value = yield this.listener.getActiveElement(); - break; - } + resp.body.value = yield this.listener.getActiveElement(); }; /** @@ -2125,8 +2112,6 @@ GeckoDriver.prototype.clearElement = function*(cmd, resp) { * @param {string} id element id. */ GeckoDriver.prototype.switchToShadowRoot = function*(cmd, resp) { - assert.content(this.context) - let id; if (cmd.parameters) { id = cmd.parameters.id; } yield this.listener.switchToShadowRoot(id); @@ -2134,8 +2119,6 @@ GeckoDriver.prototype.switchToShadowRoot = function*(cmd, resp) { /** Add a cookie to the document. */ GeckoDriver.prototype.addCookie = function*(cmd, resp) { - assert.content(this.context) - let cb = msg => { this.mm.removeMessageListener("Marionette:addCookie", cb); let cookie = msg.json; @@ -2151,7 +2134,6 @@ GeckoDriver.prototype.addCookie = function*(cmd, resp) { {}); // originAttributes return true; }; - this.mm.addMessageListener("Marionette:addCookie", cb); yield this.listener.addCookie(cmd.parameters.cookie); }; @@ -2163,15 +2145,11 @@ GeckoDriver.prototype.addCookie = function*(cmd, resp) { * the result. */ GeckoDriver.prototype.getCookies = function*(cmd, resp) { - assert.content(this.context) - resp.body = yield this.listener.getCookies(); }; /** Delete all cookies that are visible to a document. */ GeckoDriver.prototype.deleteAllCookies = function*(cmd, resp) { - assert.content(this.context) - let cb = msg => { let cookie = msg.json; cookieManager.remove( @@ -2182,7 +2160,6 @@ GeckoDriver.prototype.deleteAllCookies = function*(cmd, resp) { cookie.originAttributes); return true; }; - this.mm.addMessageListener("Marionette:deleteCookie", cb); yield this.listener.deleteAllCookies(); this.mm.removeMessageListener("Marionette:deleteCookie", cb); @@ -2190,8 +2167,6 @@ GeckoDriver.prototype.deleteAllCookies = function*(cmd, resp) { /** Delete a cookie by name. */ GeckoDriver.prototype.deleteCookie = function*(cmd, resp) { - assert.content(this.context) - let cb = msg => { this.mm.removeMessageListener("Marionette:deleteCookie", cb); let cookie = msg.json; @@ -2203,7 +2178,6 @@ GeckoDriver.prototype.deleteCookie = function*(cmd, resp) { cookie.originAttributes); return true; }; - this.mm.addMessageListener("Marionette:deleteCookie", cb); yield this.listener.deleteCookie(cmd.parameters.name); }; @@ -2373,15 +2347,7 @@ GeckoDriver.prototype.deleteSession = function (cmd, resp) { /** Returns the current status of the Application Cache. */ GeckoDriver.prototype.getAppCacheStatus = function* (cmd, resp) { - switch (this.context) { - case Context.CHROME: - throw new UnsupportedOperationError( - "Command 'getAppCacheStatus' is not yet available in chrome context"); - - case Context.CONTENT: - resp.body.value = yield this.listener.getAppCacheStatus(); - break; - } + resp.body.value = yield this.listener.getAppCacheStatus(); }; /** @@ -2499,8 +2465,9 @@ GeckoDriver.prototype.takeScreenshot = function (cmd, resp) { * landscape-secondary. */ GeckoDriver.prototype.getScreenOrientation = function (cmd, resp) { - assert.fennec(); - + if (this.appName == "Firefox") { + throw new UnsupportedOperationError(); + } resp.body.value = this.getCurrentWindow().screen.mozOrientation; }; @@ -2527,7 +2494,7 @@ GeckoDriver.prototype.setScreenOrientation = function (cmd, resp) { let or = String(cmd.parameters.orientation); assert.string(or); let mozOr = or.toLowerCase(); - if (!ors.includes(mozOr)) { + if (!ors.include(mozOr)) { throw new InvalidArgumentError(`Unknown screen orientation: ${or}`); } @@ -2558,7 +2525,9 @@ GeckoDriver.prototype.getWindowSize = function (cmd, resp) { * bars, title bars, etc. */ GeckoDriver.prototype.setWindowSize = function (cmd, resp) { - assert.firefox() + if (this.appName != "Firefox") { + throw new UnsupportedOperationError(); + } let {width, height} = cmd.parameters; let win = this.getCurrentWindow(); @@ -2573,7 +2542,9 @@ GeckoDriver.prototype.setWindowSize = function (cmd, resp) { * Not Supported on B2G or Fennec. */ GeckoDriver.prototype.maximizeWindow = function (cmd, resp) { - assert.firefox() + if (this.appName != "Firefox") { + throw new UnsupportedOperationError(); + } let win = this.getCurrentWindow(); win.maximize() @@ -2670,7 +2641,9 @@ GeckoDriver.prototype.acceptConnections = function (cmd, resp) { * session. */ GeckoDriver.prototype.quitApplication = function (cmd, resp) { - assert.firefox() + if (this.appName != "Firefox") { + throw new WebDriverError("In app initiated quit only supported in Firefox"); + } let flags = Ci.nsIAppStartup.eAttemptQuit; for (let k of cmd.parameters.flags || []) { @@ -2685,7 +2658,9 @@ GeckoDriver.prototype.quitApplication = function (cmd, resp) { }; GeckoDriver.prototype.installAddon = function (cmd, resp) { - assert.firefox() + if (this.appName != "Firefox") { + throw new UnsupportedOperationError(); + } let path = cmd.parameters.path; let temp = cmd.parameters.temporary || false; @@ -2698,7 +2673,9 @@ GeckoDriver.prototype.installAddon = function (cmd, resp) { }; GeckoDriver.prototype.uninstallAddon = function (cmd, resp) { - assert.firefox() + if (this.appName != "Firefox") { + throw new UnsupportedOperationError(); + } let id = cmd.parameters.id; if (typeof id == "undefined" || typeof id != "string") { diff --git a/testing/marionette/harness/marionette_harness/tests/unit/test_cookies.py b/testing/marionette/harness/marionette_harness/tests/unit/test_cookies.py index f7841c73e099..e2b7a6fc2c4e 100644 --- a/testing/marionette/harness/marionette_harness/tests/unit/test_cookies.py +++ b/testing/marionette/harness/marionette_harness/tests/unit/test_cookies.py @@ -6,7 +6,6 @@ import calendar import random import time -from marionette_driver.errors import UnsupportedOperationException from marionette_harness import MarionetteTestCase @@ -37,17 +36,6 @@ class CookieTest(MarionetteTestCase): cookies = self.marionette.get_cookies() self.assertEquals(0, len(cookies)) - def test_chrome_error(self): - with self.marionette.using_context("chrome"): - self.assertRaises(UnsupportedOperationException, - self.marionette.add_cookie, self.COOKIE_A) - self.assertRaises(UnsupportedOperationException, - self.marionette.delete_cookie, self.COOKIE_A) - self.assertRaises(UnsupportedOperationException, - self.marionette.delete_all_cookies) - self.assertRaises(UnsupportedOperationException, - self.marionette.get_cookies) - def test_delete_all_cookie(self): self.marionette.add_cookie(self.COOKIE_A) cookie_returned = str(self.marionette.execute_script("return document.cookie")) diff --git a/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py b/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py index 9e3b26a1c5d4..75276c4a99f8 100644 --- a/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py +++ b/testing/marionette/harness/marionette_harness/tests/unit/test_navigation.py @@ -51,11 +51,9 @@ class TestNavigate(WindowManagerMixin, MarionetteTestCase): def test_navigate_chrome_error(self): with self.marionette.using_context("chrome"): - self.assertRaises(errors.UnsupportedOperationException, - self.marionette.navigate, "about:blank") - self.assertRaises(errors.UnsupportedOperationException, self.marionette.go_back) - self.assertRaises(errors.UnsupportedOperationException, self.marionette.go_forward) - self.assertRaises(errors.UnsupportedOperationException, self.marionette.refresh) + self.assertRaisesRegexp( + errors.UnsupportedOperationException, "Cannot navigate in chrome context", + self.marionette.navigate, "about:blank") def test_get_current_url_returns_top_level_browsing_context_url(self): self.marionette.navigate(self.iframe_doc) diff --git a/testing/marionette/harness/marionette_harness/tests/unit/test_shadow_dom.py b/testing/marionette/harness/marionette_harness/tests/unit/test_shadow_dom.py index 9750d8cdd728..be530101e510 100644 --- a/testing/marionette/harness/marionette_harness/tests/unit/test_shadow_dom.py +++ b/testing/marionette/harness/marionette_harness/tests/unit/test_shadow_dom.py @@ -5,8 +5,7 @@ from marionette_driver.by import By from marionette_driver.errors import ( NoSuchElementException, - StaleElementException, - UnsupportedOperationException, + StaleElementException ) from marionette_harness import MarionetteTestCase @@ -23,11 +22,6 @@ class TestShadowDom(MarionetteTestCase): self.marionette.switch_to_shadow_root(self.host) self.button = self.marionette.find_element(By.ID, "button") - def test_chrome_error(self): - with self.marionette.using_context("chrome"): - self.assertRaises(UnsupportedOperationException, - self.marionette.switch_to_shadow_root) - def test_shadow_dom(self): # Button in shadow root should be actionable self.button.click() From 0dfb7c2b5c5cf4a64983ed47e6937a903712a083 Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Thu, 29 Dec 2016 14:05:44 -0800 Subject: [PATCH 090/229] Backed out 3 changesets (bug 1325464) for xpcshell failures a=backout Backed out changeset 562ddc32cc21 (bug 1325464) Backed out changeset cd10db6087dd (bug 1325464) Backed out changeset 4079437c4648 (bug 1325464) --- .../base/content/aboutDialog-appUpdater.js | 28 +- .../content/aboutaccounts/aboutaccounts.js | 32 +- .../content/abouthealthreport/abouthealth.js | 34 +- browser/base/content/abouthome/aboutHome.js | 6 +- browser/base/content/browser-addons.js | 54 +-- browser/base/content/browser-ctrlTab.js | 14 +- browser/base/content/browser-customization.js | 10 +- .../browser-data-submission-info-bar.js | 10 +- browser/base/content/browser-devedition.js | 18 +- .../browser-fullScreenAndPointerLock.js | 72 ++- browser/base/content/browser-fullZoom.js | 10 +- browser/base/content/browser-fxaccounts.js | 30 +- .../base/content/browser-gestureSupport.js | 14 +- browser/base/content/browser-media.js | 16 +- browser/base/content/browser-places.js | 42 +- browser/base/content/browser-plugins.js | 44 +- .../base/content/browser-refreshblocker.js | 4 +- browser/base/content/browser-safebrowsing.js | 4 +- browser/base/content/browser-sidebar.js | 4 +- browser/base/content/browser-syncui.js | 16 +- .../content/browser-tabsintitlebar-stub.js | 6 +- .../base/content/browser-tabsintitlebar.js | 18 +- browser/base/content/browser.js | 356 +++++++------- browser/base/content/content.js | 98 ++-- browser/base/content/contentSearchUI.js | 86 ++-- browser/base/content/pageinfo/pageInfo.js | 78 +-- browser/base/content/pageinfo/permissions.js | 2 +- browser/base/content/pageinfo/security.js | 32 +- browser/base/content/sanitize.js | 8 +- browser/base/content/social-content.js | 2 +- browser/base/content/sync/aboutSyncTabs.js | 38 +- browser/base/content/sync/genericChange.js | 6 +- browser/base/content/sync/setup.js | 78 +-- browser/base/content/sync/utils.js | 22 +- browser/base/content/tab-content.js | 90 ++-- browser/base/content/tabbrowser.xml | 108 ++--- .../test/general/browser_aboutAccounts.js | 46 +- .../test/general/browser_aboutHealthReport.js | 2 +- .../content/test/general/browser_aboutHome.js | 6 +- .../test/general/browser_alltabslistener.js | 18 +- .../content/test/general/browser_blockHPKP.js | 2 +- .../content/test/general/browser_bug321000.js | 2 +- .../content/test/general/browser_bug356571.js | 6 +- .../content/test/general/browser_bug424101.js | 2 +- .../content/test/general/browser_bug553455.js | 10 +- .../content/test/general/browser_bug561636.js | 2 +- .../content/test/general/browser_bug592338.js | 2 +- .../content/test/general/browser_bug676619.js | 8 +- .../content/test/general/browser_bug734076.js | 18 +- .../test/general/browser_contentAltClick.js | 4 +- .../test/general/browser_contentAreaClick.js | 46 +- .../test/general/browser_contentSearchUI.js | 56 +-- .../test/general/browser_contextmenu.js | 8 +- .../test/general/browser_devedition.js | 2 +- .../general/browser_documentnavigation.js | 2 +- .../browser_domFullscreen_fullscreenMode.js | 2 +- .../general/browser_e10s_about_process.js | 10 +- .../general/browser_fullscreen-window-open.js | 32 +- .../content/test/general/browser_fxa_oauth.js | 12 +- .../test/general/browser_fxa_web_channel.js | 26 +- .../test/general/browser_fxaccounts.js | 6 +- .../test/general/browser_getshortcutoruri.js | 2 +- .../content/test/general/browser_homeDrop.js | 4 +- .../test/general/browser_keywordSearch.js | 2 +- .../test/general/browser_plainTextLinks.js | 2 +- .../test/general/browser_restore_isAppTab.js | 2 +- .../general/browser_sanitize-timespans.js | 14 +- .../test/general/browser_sanitizeDialog.js | 44 +- ...browser_save_link_when_window_navigates.js | 4 +- .../browser_save_private_link_perwindowpb.js | 6 +- .../content/test/general/browser_tabfocus.js | 6 +- .../test/general/browser_tabopen_reflows.js | 4 +- .../test/general/browser_trackingUI_4.js | 2 +- .../test/general/browser_trackingUI_6.js | 2 +- .../browser_viewSourceInTabOnViewSource.js | 2 +- .../test/general/browser_web_channel.js | 34 +- .../test/general/browser_windowactivation.js | 6 +- .../general/browser_windowopen_reflows.js | 4 +- .../content/test/general/contentSearchUI.js | 30 +- browser/base/content/test/general/head.js | 32 +- .../content/test/general/offlineByDefault.js | 4 +- .../test/general/parsingTestHelpers.jsm | 2 +- .../test/newtab/browser_newtab_bug722273.js | 6 +- .../test/newtab/browser_newtab_bug725996.js | 2 +- .../test/newtab/browser_newtab_bug991210.js | 4 +- .../test/newtab/browser_newtab_drag_drop.js | 2 +- .../test/newtab/browser_newtab_search.js | 4 +- browser/base/content/test/newtab/head.js | 4 +- .../content/test/plugins/blocklist_proxy.js | 20 +- .../content/test/plugins/browser_bug797677.js | 2 +- ...browser_pluginCrashReportNonDeterminism.js | 4 +- .../browser_popupNotification.js | 70 +-- .../browser_popupNotification_2.js | 50 +- .../browser_popupNotification_3.js | 48 +- .../browser_popupNotification_4.js | 42 +- .../browser_popupNotification_5.js | 48 +- .../browser_popupNotification_checkbox.js | 38 +- .../browser_popupNotification_no_anchors.js | 20 +- .../social/browser_aboutHome_activation.js | 2 +- .../content/test/social/browser_addons.js | 38 +- .../content/test/social/browser_blocklist.js | 18 +- .../base/content/test/social/browser_share.js | 12 +- .../test/social/browser_social_activation.js | 10 +- .../social/social_crash_content_helper.js | 4 +- browser/base/content/test/urlbar/Panel.jsm | 4 +- .../urlbar/browser_autocomplete_no_title.js | 2 +- ...rowser_autocomplete_tag_star_visibility.js | 2 +- .../content/test/urlbar/browser_bug556061.js | 16 +- .../content/test/urlbar/browser_bug623155.js | 4 +- .../test/urlbar/browser_search_favicon.js | 2 +- .../urlbar/browser_tabMatchesInAwesomebar.js | 10 +- .../test/urlbar/browser_urlbarAddonIframe.js | 14 +- .../test/urlbar/browser_urlbarCopying.js | 2 +- .../urlbar/browser_urlbarSearchTelemetry.js | 2 +- browser/base/content/test/urlbar/head.js | 6 +- .../content/test/urlbar/urlbarAddonIframe.js | 2 +- browser/base/content/urlbarBindings.xml | 12 +- browser/base/content/utilityOverlay.js | 2 +- browser/base/content/web-panels.js | 12 +- browser/base/content/webrtcIndicator.js | 6 +- .../test/browser/browser_forgetaboutsite.js | 8 +- .../test/browser/browser_serviceworkers.js | 6 +- .../customizableui/CustomizableUI.jsm | 278 +++++------ .../customizableui/CustomizableWidgets.jsm | 82 ++-- .../customizableui/CustomizeMode.jsm | 160 +++---- .../customizableui/DragPositionManager.jsm | 34 +- .../customizableui/PanelWideWidgetTracker.jsm | 22 +- .../customizableui/ScrollbarSampler.jsm | 6 +- .../customizableui/content/panelUI.js | 46 +- .../customizableui/content/toolbar.xml | 4 +- .../browser_1003588_no_specials_in_panel.js | 2 +- .../test/browser_877006_missing_view.js | 2 +- ..._942581_unregisterArea_keeps_placements.js | 2 +- .../browser_947914_button_newPrivateWindow.js | 2 +- .../test/browser_947914_button_newWindow.js | 2 +- .../test/browser_973641_button_addon.js | 2 +- .../test/browser_976792_insertNodeInWindow.js | 24 +- .../browser_980155_add_overflow_toolbar.js | 2 +- ...r_981418-widget-onbeforecreated-handler.js | 4 +- .../test/browser_987492_window_api.js | 4 +- ...5164_registerArea_during_customize_mode.js | 8 +- .../migration/360seProfileMigrator.js | 2 +- .../migration/ChromeProfileMigrator.js | 8 +- browser/components/migration/ESEDBReader.jsm | 2 +- .../migration/EdgeProfileMigrator.js | 8 +- .../migration/FirefoxProfileMigrator.js | 6 +- .../components/migration/IEProfileMigrator.js | 16 +- .../components/migration/MSMigrationUtils.jsm | 2 +- .../components/migration/MigrationUtils.jsm | 1 + .../migration/SafariProfileMigrator.js | 8 +- .../components/migration/content/migration.js | 36 +- .../tests/unit/test_automigration.js | 20 +- browser/components/newtab/NewTabURL.jsm | 6 +- .../components/newtab/NewTabWebChannel.jsm | 2 +- browser/components/newtab/PlacesProvider.jsm | 2 +- .../tests/browser/newtabwebchannel_basic.html | 2 +- browser/components/nsBrowserGlue.js | 74 +-- .../test/browser/browser_cache.js | 8 +- browser/components/places/PlacesUIUtils.jsm | 14 +- .../places/content/bookmarkProperties.js | 2 +- .../places/content/browserPlacesViews.js | 18 +- .../components/places/content/controller.js | 14 +- .../places/content/editBookmarkOverlay.js | 2 +- .../places/content/moveBookmarks.js | 2 +- browser/components/places/content/places.js | 6 +- browser/components/places/content/treeView.js | 22 +- .../places/tests/browser/browser_423515.js | 20 +- .../browser/browser_bookmarklet_windowOpen.js | 6 +- .../browser/browser_bookmarksProperties.js | 34 +- .../browser_drag_bookmarks_on_toolbar.js | 4 +- .../browser/browser_library_batch_delete.js | 6 +- .../browser/browser_library_downloads.js | 6 +- .../tests/browser/browser_library_infoBox.js | 2 +- .../browser_library_left_pane_fixnames.js | 2 +- .../browser/browser_library_middleclick.js | 22 +- .../browser_library_views_liveupdate.js | 12 +- .../browser/browser_sidebarpanels_click.js | 18 +- .../tests/browser/browser_views_liveupdate.js | 12 +- .../components/places/tests/browser/head.js | 6 +- .../places/tests/unit/test_421483.js | 2 +- .../tests/unit/test_PUIU_makeTransaction.js | 2 +- .../tests/unit/test_clearHistory_shutdown.js | 6 +- .../preferences/SiteDataManager.jsm | 10 +- browser/components/preferences/blocklists.js | 44 +- browser/components/preferences/connection.js | 26 +- browser/components/preferences/cookies.js | 122 ++--- browser/components/preferences/fonts.js | 10 +- .../preferences/in-content/advanced.js | 72 +-- .../preferences/in-content/applications.js | 102 ++-- .../preferences/in-content/content.js | 24 +- .../components/preferences/in-content/main.js | 40 +- .../preferences/in-content/preferences.js | 2 +- .../preferences/in-content/privacy.js | 48 +- .../preferences/in-content/search.js | 116 ++--- .../preferences/in-content/security.js | 20 +- .../preferences/in-content/subdialogs.js | 36 +- .../components/preferences/in-content/sync.js | 62 +-- .../tests/browser_advanced_siteData.js | 6 +- .../tests/browser_advanced_update.js | 8 +- .../tests/browser_basic_rebuild_fonts_test.js | 8 +- ...g1020245_openPreferences_to_paneContent.js | 2 +- .../tests/browser_cookies_exceptions.js | 36 +- .../preferences/in-content/tests/head.js | 2 +- browser/components/preferences/languages.js | 26 +- browser/components/preferences/permissions.js | 74 +-- browser/components/preferences/sanitize.js | 4 +- browser/components/preferences/translation.js | 56 +-- browser/components/search/content/search.xml | 12 +- .../components/search/test/browser_426329.js | 8 +- .../search/test/browser_aboutSearchReset.js | 8 +- .../search/test/browser_abouthome_behavior.js | 8 +- .../search/test/browser_addEngine.js | 8 +- .../search/test/browser_amazon_behavior.js | 10 +- .../search/test/browser_bing_behavior.js | 10 +- .../search/test/browser_google_behavior.js | 10 +- .../test/browser_hiddenOneOffs_cleanup.js | 6 +- .../browser_searchbar_keyboard_navigation.js | 6 +- .../test/browser_searchbar_openpopup.js | 6 +- ...earchbar_smallpanel_keyboard_navigation.js | 6 +- .../components/search/test/browser_webapi.js | 2 +- .../search/test/browser_yahoo_behavior.js | 10 +- browser/components/search/test/head.js | 6 +- .../selfsupport/SelfSupportService.js | 16 +- .../shell/content/setDesktopBackground.js | 8 +- .../syncedtabs/SyncedTabsDeckComponent.js | 2 +- .../syncedtabs/SyncedTabsDeckStore.js | 2 +- .../syncedtabs/test/xpcshell/head.js | 6 +- .../tests/browser/browser_bug538331.js | 10 +- .../tests/unit/test_distribution.js | 2 +- .../components/translation/BingTranslator.jsm | 28 +- .../translation/LanguageDetector.jsm | 2 +- .../components/translation/Translation.jsm | 44 +- .../translation/TranslationContentHandler.jsm | 14 +- .../translation/TranslationDocument.jsm | 22 +- .../translation/YandexTranslator.jsm | 16 +- .../test/browser_translation_infobar.js | 8 +- .../test/browser_translation_telemetry.js | 8 +- browser/components/uitour/UITour-lib.js | 52 +- browser/components/uitour/UITour.jsm | 92 ++-- browser/components/uitour/content-UITour.js | 12 +- .../test/browser_UITour_defaultBrowser.js | 10 +- .../uitour/test/browser_UITour_heartbeat.js | 2 +- .../uitour/test/browser_UITour_modalDialog.js | 4 +- .../components/uitour/test/browser_no_tabs.js | 2 +- browser/experiments/Experiments.jsm | 118 ++--- browser/experiments/ExperimentsService.js | 6 +- .../test/xpcshell/test_activate.js | 2 +- browser/extensions/pocket/bootstrap.js | 38 +- .../extensions/pocket/content/AboutPocket.jsm | 10 +- browser/extensions/pocket/content/main.js | 56 +-- .../pocket/content/panels/js/messages.js | 10 +- .../pocket/content/panels/js/saved.js | 26 +- .../pocket/content/panels/js/signup.js | 10 +- browser/extensions/pocket/content/pktApi.jsm | 34 +- browser/extensions/pocket/test/head.js | 2 +- browser/extensions/presentation/bootstrap.js | 12 +- .../content/PresentationDevicePrompt.jsm | 6 +- browser/modules/AboutHome.jsm | 6 +- browser/modules/AboutNewTab.jsm | 6 +- browser/modules/BrowserUITelemetry.jsm | 72 +-- browser/modules/CastingApps.jsm | 32 +- browser/modules/ContentClick.jsm | 6 +- browser/modules/ContentCrashHandlers.jsm | 12 +- browser/modules/ContentLinkHandler.jsm | 8 +- browser/modules/ContentSearch.jsm | 56 +-- browser/modules/ContentWebRTC.jsm | 24 +- browser/modules/DirectoryLinksProvider.jsm | 24 +- browser/modules/E10SUtils.jsm | 12 +- browser/modules/Feeds.jsm | 2 +- browser/modules/FormSubmitObserver.jsm | 20 +- browser/modules/FormValidationHandler.jsm | 18 +- browser/modules/HiddenFrame.jsm | 8 +- browser/modules/NetworkPrioritizer.jsm | 2 +- browser/modules/PermissionUI.jsm | 4 +- browser/modules/PluginContent.jsm | 104 ++-- browser/modules/ProcessHangMonitor.jsm | 48 +- browser/modules/ReaderParent.jsm | 12 +- browser/modules/RemotePrompt.jsm | 8 +- browser/modules/SelfSupportBackend.jsm | 28 +- browser/modules/SitePermissions.jsm | 32 +- browser/modules/Social.jsm | 16 +- browser/modules/SocialService.jsm | 70 +-- browser/modules/TransientPrefs.jsm | 2 +- browser/modules/URLBarZoom.jsm | 2 +- browser/modules/Windows8WindowFrameColor.jsm | 2 +- browser/modules/WindowsJumpLists.jsm | 6 +- browser/modules/WindowsPreviewPerTab.jsm | 72 +-- browser/modules/offlineAppCache.jsm | 2 +- browser/modules/test/browser_ContentSearch.js | 8 +- browser/modules/test/browser_PermissionUI.js | 8 +- .../test/browser_ProcessHangNotifications.js | 12 +- browser/modules/test/contentSearch.js | 4 +- browser/modules/test/unit/social/head.js | 4 +- .../xpcshell/test_DirectoryLinksProvider.js | 14 +- browser/modules/webrtcUI.jsm | 44 +- .../mozscreenshots/extension/TestRunner.jsm | 2 +- .../extension/configurations/Buttons.jsm | 2 +- storage/test/unit/head_storage.js | 12 +- toolkit/.eslintrc.js | 3 - .../content/aboutCheckerboard.js | 2 +- .../aboutmemory/content/aboutMemory.js | 20 +- .../content/aboutPerformance.js | 48 +- .../components/addoncompat/CompatWarning.jsm | 4 +- toolkit/components/addoncompat/Prefetcher.jsm | 18 +- .../addoncompat/RemoteAddonsChild.jsm | 100 ++-- .../addoncompat/RemoteAddonsParent.jsm | 92 ++-- toolkit/components/addoncompat/ShimWaiver.jsm | 2 +- .../components/addoncompat/defaultShims.js | 6 +- .../addoncompat/multiprocessShims.js | 8 +- .../addoncompat/tests/addon/bootstrap.js | 22 +- .../tests/browser/browser_addonShims.js | 8 +- .../components/alerts/test/test_alerts.html | 2 +- .../asyncshutdown/AsyncShutdown.jsm | 48 +- .../asyncshutdown/nsAsyncShutdown.js | 28 +- .../asyncshutdown/tests/xpcshell/head.js | 20 +- .../test_AsyncShutdown_leave_uncaught.js | 2 +- .../tests/unit/head_autocomplete.js | 28 +- .../autocomplete/tests/unit/test_330578.js | 2 +- .../autocomplete/tests/unit/test_378079.js | 38 +- .../autocomplete/tests/unit/test_393191.js | 38 +- .../autocomplete/tests/unit/test_440866.js | 38 +- .../tests/unit/test_autocomplete_multiple.js | 38 +- .../tests/unit/test_previousResult.js | 38 +- .../tests/unit/test_stopSearch.js | 20 +- .../components/captivedetect/captivedetect.js | 8 +- .../contentprefs/ContentPrefService2.jsm | 2 +- .../contentprefs/ContentPrefServiceChild.jsm | 52 +- .../contentprefs/ContentPrefServiceParent.jsm | 30 +- .../contentprefs/nsContentPrefService.js | 12 +- .../contentprefs/tests/unit/test_bug679784.js | 4 +- .../tests/unit/test_getPrefAsync.js | 2 +- .../contentprefs/tests/unit_cps2/head.js | 22 +- .../tests/unit_cps2/test_setGet.js | 6 +- toolkit/components/crashes/CrashManager.jsm | 76 +-- .../components/crashes/CrashManagerTest.jsm | 8 +- toolkit/components/crashes/CrashService.js | 4 +- .../components/crashmonitor/CrashMonitor.jsm | 6 +- .../components/crashmonitor/nsCrashMonitor.js | 2 +- .../chrome/xpcshellTestHarnessAdaptor.js | 4 +- toolkit/components/ctypes/tests/unit/head.js | 2 +- .../ctypes/tests/unit/test_finalizer.js | 38 +- .../ctypes/tests/unit/test_jsctypes.js | 34 +- .../test/unit/test_app_rep_windows.js | 4 +- .../test/xpcshell/test_ext_storage_sync.js | 1 + .../components/exthelper/extApplication.js | 2 +- toolkit/components/feeds/test/test_xml.js | 2 +- .../filepicker/content/filepicker.js | 4 +- toolkit/components/filepicker/nsFilePicker.js | 16 +- .../filepicker/test/unit/test_filecomplete.js | 2 +- .../FormAutofillContentService.js | 12 +- .../formautofill/FormAutofillStartup.js | 4 +- .../content/RequestAutocompleteUI.jsm | 2 +- .../content/requestAutocomplete.js | 8 +- .../formautofill/test/chrome/loader.js | 2 +- .../formautofill/test/head_common.js | 10 +- .../formautofill/test/loader_common.js | 4 +- toolkit/components/gfx/SanityTest.js | 12 +- .../components/gfx/content/gfxFrameScript.js | 8 +- .../jsdownloads/src/DownloadCore.jsm | 78 +-- .../jsdownloads/src/DownloadImport.jsm | 8 +- .../jsdownloads/src/DownloadLegacy.js | 16 +- .../jsdownloads/src/DownloadList.jsm | 26 +- .../jsdownloads/src/DownloadUIHelper.jsm | 4 +- .../components/jsdownloads/src/Downloads.jsm | 6 +- .../test/unit/common_test_Download.js | 16 +- .../components/jsdownloads/test/unit/head.js | 30 +- .../test/unit/test_DownloadImport.js | 6 +- .../test/unit/test_DownloadList.js | 22 +- toolkit/components/lz4/lz4.js | 4 +- .../test/unit/test_mediasniffer.js | 8 +- .../test/unit/test_mediasniffer_ext.js | 6 +- .../microformats/microformat-shiv.js | 248 +++++----- .../components/narrate/NarrateControls.jsm | 20 +- toolkit/components/narrate/Narrator.jsm | 32 +- toolkit/components/narrate/VoiceSelect.jsm | 22 +- .../narrate/test/NarrateTestUtils.jsm | 26 +- .../components/passwordmgr/LoginHelper.jsm | 2 +- .../components/passwordmgr/LoginImport.jsm | 26 +- .../passwordmgr/LoginManagerContent.jsm | 24 +- .../passwordmgr/LoginManagerContextMenu.jsm | 6 +- .../passwordmgr/LoginManagerParent.jsm | 18 +- .../passwordmgr/content/passwordManager.js | 2 +- toolkit/components/passwordmgr/crypto-SDR.js | 10 +- toolkit/components/passwordmgr/nsLoginInfo.js | 6 +- .../passwordmgr/nsLoginManagerPrompter.js | 76 +-- .../components/passwordmgr/storage-json.js | 14 +- .../passwordmgr/storage-mozStorage.js | 90 ++-- .../browser/browser_passwordmgr_observers.js | 2 +- .../browser/browser_passwordmgr_switchtab.js | 4 +- .../test_prompt_promptAuth_proxy.html | 8 +- .../passwordmgr/test/prompt_common.js | 4 +- .../test/test_master_password.html | 2 +- .../passwordmgr/test/test_prompt_async.html | 12 +- .../test/unit/test_notifications.js | 2 +- .../passwordmgr/test/unit/test_storage.js | 2 +- .../unit/test_user_autocomplete_result.js | 32 +- .../perfmonitoring/AddonWatcher.jsm | 12 +- .../perfmonitoring/PerformanceStats.jsm | 82 ++-- .../perfmonitoring/PerformanceWatcher.jsm | 18 +- .../tests/browser/browser_compartments.js | 8 +- .../perfmonitoring/tests/browser/head.js | 8 +- .../components/places/BookmarkHTMLUtils.jsm | 16 +- .../components/places/BookmarkJSONUtils.jsm | 8 +- toolkit/components/places/Bookmarks.jsm | 8 +- toolkit/components/places/ClusterLib.js | 2 +- toolkit/components/places/ColorAnalyzer.js | 2 +- .../components/places/ColorAnalyzer_worker.js | 10 +- toolkit/components/places/History.jsm | 16 +- toolkit/components/places/PlacesBackups.jsm | 4 +- toolkit/components/places/PlacesDBUtils.jsm | 28 +- .../PlacesSearchAutocompleteProvider.jsm | 12 +- .../components/places/PlacesTransactions.jsm | 48 +- toolkit/components/places/PlacesUtils.jsm | 46 +- toolkit/components/places/UnifiedComplete.js | 52 +- .../components/places/nsLivemarkService.js | 2 +- .../components/places/nsPlacesExpiration.js | 16 +- toolkit/components/places/nsTaggingService.js | 6 +- .../test_1017502-bookmarks_foreign_count.js | 2 +- .../places/tests/bookmarks/test_393498.js | 4 +- .../bookmarks/test_405938_restore_queries.js | 2 +- .../test_424958-json-quoted-folders.js | 6 +- .../places/tests/bookmarks/test_448584.js | 6 +- .../places/tests/bookmarks/test_458683.js | 6 +- .../places/tests/bookmarks/test_675416.js | 2 +- .../places/tests/bookmarks/test_711914.js | 2 +- .../tests/bookmarks/test_async_observers.js | 18 +- .../places/tests/bookmarks/test_bookmarks.js | 14 +- .../tests/bookmarks/test_bookmarks_insert.js | 6 +- .../bookmarks/test_bookmarks_notifications.js | 2 +- .../places/tests/bookmarks/test_keywords.js | 2 +- .../bookmarks/test_nsINavBookmarkObserver.js | 8 +- .../places/tests/browser/browser_bug399606.js | 16 +- .../places/tests/browser/browser_bug646422.js | 16 +- .../tests/browser/browser_double_redirect.js | 2 +- .../places/tests/browser/browser_notfound.js | 16 +- .../places/tests/browser/browser_redirect.js | 16 +- .../places/tests/browser/browser_settitle.js | 16 +- .../tests/browser/browser_visited_notfound.js | 2 +- ...er_visituri_privatebrowsing_perwindowpb.js | 2 +- .../components/places/tests/browser/head.js | 24 +- .../tests/expiration/test_analyze_runs.js | 2 +- .../expiration/test_annos_expire_session.js | 6 +- .../tests/expiration/test_notifications.js | 2 +- .../test_notifications_onDeleteURI.js | 12 +- .../test_notifications_onDeleteVisits.js | 12 +- .../tests/expiration/test_outdated_analyze.js | 6 +- .../tests/expiration/test_pref_maxpages.js | 12 +- .../test_moz-anno_favicon_mime_type.js | 6 +- .../components/places/tests/head_common.js | 62 +-- .../places/tests/history/test_insert.js | 2 +- .../places/tests/history/test_remove.js | 50 +- .../history/test_removeVisitsByFilter.js | 26 +- .../migration/test_current_from_downgraded.js | 2 +- .../tests/migration/test_current_from_v19.js | 2 +- .../places/tests/queries/test_async.js | 34 +- .../test_history_queries_titles_liveUpdate.js | 24 +- .../tests/queries/test_querySerialization.js | 8 +- .../places/tests/queries/test_sorting.js | 56 +-- .../unifiedcomplete/head_autocomplete.js | 10 +- .../tests/unifiedcomplete/test_416211.js | 6 +- .../test_avoid_stripping_to_empty_tokens.js | 2 +- .../tests/unifiedcomplete/test_enabled.js | 6 +- .../test_remote_tab_matches.js | 2 +- .../test_search_engine_host.js | 2 +- .../places/tests/unit/nsDummyObserver.js | 26 +- .../places/tests/unit/test_000_frecency.js | 14 +- .../places/tests/unit/test_405497.js | 2 +- .../places/tests/unit/test_408221.js | 14 +- .../places/tests/unit/test_413784.js | 14 +- .../unit/test_418643_removeFolderChildren.js | 4 +- .../places/tests/unit/test_452777.js | 2 +- .../places/tests/unit/test_454977.js | 2 +- .../places/tests/unit/test_463863.js | 2 +- .../unit/test_PlacesUtils_lazyobservers.js | 14 +- .../places/tests/unit/test_adaptive.js | 14 +- .../tests/unit/test_adaptive_bug527311.js | 12 +- .../places/tests/unit/test_analyze.js | 6 +- .../places/tests/unit/test_annotations.js | 8 +- .../unit/test_asyncExecuteLegacyQueries.js | 14 +- .../tests/unit/test_async_history_api.js | 4 +- .../tests/unit/test_async_transactions.js | 26 +- .../places/tests/unit/test_bookmarks_html.js | 2 +- .../places/tests/unit/test_bookmarks_json.js | 2 +- .../test_bookmarks_restore_notification.js | 2 +- .../places/tests/unit/test_browserhistory.js | 8 +- .../places/tests/unit/test_childlessTags.js | 4 +- .../tests/unit/test_download_history.js | 20 +- .../places/tests/unit/test_frecency.js | 14 +- .../unit/test_history_autocomplete_tags.js | 14 +- .../places/tests/unit/test_history_clear.js | 16 +- .../tests/unit/test_history_observer.js | 20 +- .../places/tests/unit/test_isURIVisited.js | 8 +- .../places/tests/unit/test_isvisited.js | 8 +- .../places/tests/unit/test_keywords.js | 2 +- .../places/tests/unit/test_markpageas.js | 2 +- .../tests/unit/test_nsINavHistoryViewer.js | 34 +- .../tests/unit/test_onItemChanged_tags.js | 14 +- .../places/tests/unit/test_placesTxn.js | 16 +- .../tests/unit/test_preventive_maintenance.js | 108 ++--- .../tests/unit/test_sql_guid_functions.js | 4 +- .../unit/test_tag_autocomplete_search.js | 14 +- .../printing/content/printPreviewBindings.xml | 8 +- .../printing/content/printPreviewProgress.js | 12 +- .../printing/content/printProgress.js | 12 +- .../components/printing/content/printUtils.js | 32 +- .../printing/content/printdialog.js | 6 +- .../printing/content/printjoboptions.js | 6 +- ...vateBrowsingTrackingProtectionWhitelist.js | 2 +- .../ContentProcessSingleton.js | 4 +- .../processsingleton/MainProcessSingleton.js | 6 +- .../promiseworker/PromiseWorker.jsm | 24 +- .../tests/xpcshell/data/worker.js | 4 +- .../promiseworker/worker/PromiseWorker.js | 16 +- .../components/prompts/src/CommonDialog.jsm | 22 +- .../prompts/src/SharedPromptUtils.jsm | 18 +- toolkit/components/prompts/src/nsPrompter.js | 136 +++--- .../components/prompts/test/chromeScript.js | 2 +- .../components/prompts/test/prompt_common.js | 2 +- toolkit/components/reader/AboutReader.jsm | 78 +-- toolkit/components/reader/ReaderMode.jsm | 28 +- toolkit/components/reader/ReaderWorker.js | 2 +- .../remotebrowserutils/RemoteWebNavigation.js | 20 +- .../components/satchel/AutoCompletePopup.jsm | 22 +- toolkit/components/satchel/FormHistory.jsm | 40 +- .../components/satchel/FormHistoryStartup.js | 6 +- .../components/satchel/formSubmitListener.js | 16 +- .../components/satchel/nsFormAutoComplete.js | 30 +- .../satchel/nsFormAutoCompleteResult.jsm | 16 +- toolkit/components/satchel/nsFormHistory.js | 62 +-- .../satchel/nsInputListAutoComplete.js | 4 +- .../components/satchel/test/parent_utils.js | 4 +- .../components/satchel/test/satchel_common.js | 6 +- .../satchel/test/test_form_autocomplete.html | 2 +- .../satchel/test/unit/head_satchel.js | 16 +- .../satchel/test/unit/test_async_expire.js | 4 +- .../satchel/test/unit/test_autocomplete.js | 20 +- .../satchel/test/unit/test_db_corrupt.js | 8 +- .../satchel/test/unit/test_history_api.js | 34 +- .../satchel/test/unit/test_notify.js | 6 +- .../satchel/test/unit/test_previous_result.js | 4 +- .../components/search/SearchStaticData.jsm | 2 +- .../search/SearchSuggestionController.jsm | 16 +- toolkit/components/search/nsSearchService.js | 26 +- .../components/search/nsSearchSuggestions.js | 12 +- toolkit/components/search/nsSidebar.js | 8 +- .../search/tests/xpcshell/head_search.js | 6 +- .../tests/xpcshell/test_addEngine_callback.js | 16 +- .../xpcshell/test_location_malformed_json.js | 2 +- .../tests/xpcshell/test_location_sync.js | 2 +- .../tests/xpcshell/test_searchSuggest.js | 6 +- .../securityreporter/SecurityReporter.js | 6 +- toolkit/components/sqlite/sqlite_internal.js | 4 +- .../startup/tests/unit/head_startup.js | 2 +- .../components/telemetry/TelemetryArchive.jsm | 14 +- .../telemetry/TelemetryController.jsm | 64 +-- .../telemetry/TelemetryEnvironment.jsm | 106 ++--- toolkit/components/telemetry/TelemetryLog.jsm | 4 +- .../telemetry/TelemetryReportingPolicy.jsm | 34 +- .../components/telemetry/TelemetrySend.jsm | 78 +-- .../components/telemetry/TelemetrySession.jsm | 102 ++-- .../telemetry/TelemetryStopwatch.jsm | 34 +- .../components/telemetry/TelemetryStorage.jsm | 108 ++--- .../components/telemetry/TelemetryUtils.jsm | 16 +- .../telemetry/ThirdPartyCookieProbe.jsm | 12 +- toolkit/components/telemetry/UITelemetry.jsm | 22 +- .../tests/unit/TelemetryArchiveTesting.jsm | 6 +- .../components/telemetry/tests/unit/head.js | 18 +- .../tests/unit/test_TelemetryEnvironment.js | 12 +- .../thumbnails/BackgroundPageThumbs.jsm | 26 +- .../components/thumbnails/PageThumbUtils.jsm | 14 +- toolkit/components/thumbnails/PageThumbs.jsm | 22 +- .../content/backgroundPageThumbsContent.js | 16 +- toolkit/components/thumbnails/test/head.js | 4 +- .../test/thumbnails_crash_content_helper.js | 4 +- .../timermanager/nsUpdateTimerManager.js | 10 +- .../components/viewconfig/content/config.js | 56 +-- .../viewsource/content/viewSource-content.js | 4 +- .../viewsource/content/viewSource.js | 2 +- .../viewsource/content/viewSourceUtils.js | 36 +- .../test/browser/browser_contextmenu.js | 2 +- .../viewsource/test/browser/head.js | 2 +- toolkit/components/workerloader/require.js | 8 +- .../workerloader/tests/utils_worker.js | 4 +- toolkit/components/xulstore/XULStore.js | 28 +- toolkit/content/aboutProfiles.js | 2 +- toolkit/content/aboutServiceWorkers.js | 4 +- toolkit/content/aboutSupport.js | 16 +- toolkit/content/aboutTelemetry.js | 90 ++-- toolkit/content/aboutwebrtc/aboutWebrtc.js | 70 +-- toolkit/content/browser-child.js | 42 +- toolkit/content/browser-content.js | 98 ++-- toolkit/content/contentAreaUtils.js | 30 +- toolkit/content/findUtils.js | 4 +- toolkit/content/finddialog.js | 2 +- .../tests/browser/browser_bug1170531.js | 2 +- .../browser_bug295977_autoscroll_overflow.js | 4 +- .../browser/browser_content_url_annotation.js | 2 +- .../tests/browser/browser_isSynthetic.js | 4 +- .../tests/browser/common/mockTransfer.js | 16 +- .../file_autocomplete_with_composition.js | 74 +-- toolkit/content/tests/chrome/popup_trigger.js | 242 +++++----- .../chrome/content/TileManager.js | 2 +- .../chrome/content/WidgetStack.js | 74 +-- .../chrome/content/overlay.js | 4 +- .../test_autocomplete_change_after_focus.html | 2 +- toolkit/content/tests/widgets/tree_shared.js | 34 +- toolkit/content/treeUtils.js | 6 +- toolkit/content/widgets/autocomplete.xml | 8 +- toolkit/content/widgets/editor.xml | 10 +- toolkit/content/widgets/findbar.xml | 4 +- toolkit/content/widgets/preferences.xml | 2 +- toolkit/content/widgets/richlistbox.xml | 4 +- toolkit/content/widgets/toolbar.xml | 4 +- toolkit/crashreporter/CrashReports.jsm | 2 +- toolkit/crashreporter/content/crashes.js | 4 +- .../test/browser/browser_bug471404.js | 6 +- .../test/browser/browser_clearReports.js | 2 +- toolkit/crashreporter/test/browser/head.js | 4 +- .../unit/test_crash_with_memory_report.js | 4 +- toolkit/forgetaboutsite/ForgetAboutSite.jsm | 2 +- .../test/unit/test_removeDataFromDomain.js | 4 +- toolkit/identity/Identity.jsm | 2 +- toolkit/identity/IdentityProvider.jsm | 2 +- toolkit/identity/MinimalIdentity.jsm | 2 +- toolkit/identity/RelyingParty.jsm | 8 +- toolkit/identity/jwcrypto.jsm | 8 +- toolkit/identity/tests/unit/head_identity.js | 8 +- .../tests/unit/test_authentication.js | 6 +- .../tests/unit/test_firefox_accounts.js | 6 +- toolkit/identity/tests/unit/test_jwcrypto.js | 12 +- toolkit/identity/tests/unit/test_log_utils.js | 2 +- .../identity/tests/unit/test_provisioning.js | 20 +- toolkit/modules/Battery.jsm | 4 +- toolkit/modules/BinarySearch.jsm | 6 +- toolkit/modules/BrowserUtils.jsm | 30 +- toolkit/modules/CertUtils.jsm | 6 +- toolkit/modules/CharsetMenu.jsm | 22 +- toolkit/modules/ClientID.jsm | 14 +- toolkit/modules/Console.jsm | 6 +- toolkit/modules/DateTimePickerHelper.jsm | 18 +- toolkit/modules/DeferredTask.jsm | 10 +- toolkit/modules/Deprecated.jsm | 2 +- toolkit/modules/Finder.jsm | 48 +- toolkit/modules/FinderHighlighter.jsm | 8 +- toolkit/modules/FinderIterator.jsm | 4 +- toolkit/modules/GMPInstallManager.jsm | 28 +- toolkit/modules/GMPUtils.jsm | 20 +- toolkit/modules/Geometry.jsm | 20 +- toolkit/modules/InlineSpellChecker.jsm | 34 +- toolkit/modules/InlineSpellCheckerContent.jsm | 2 +- toolkit/modules/Integration.jsm | 2 +- toolkit/modules/LightweightThemeConsumer.jsm | 14 +- toolkit/modules/Log.jsm | 74 +-- toolkit/modules/NewTabUtils.jsm | 44 +- toolkit/modules/ObjectUtils.jsm | 6 +- toolkit/modules/PageMenu.jsm | 24 +- toolkit/modules/PageMetadata.jsm | 2 +- toolkit/modules/PermissionsUtils.jsm | 2 +- toolkit/modules/PopupNotifications.jsm | 12 +- toolkit/modules/Preferences.jsm | 2 +- toolkit/modules/PrivateBrowsingUtils.jsm | 2 +- toolkit/modules/ProfileAge.jsm | 14 +- toolkit/modules/Promise-backend.js | 34 +- toolkit/modules/PromiseUtils.jsm | 2 +- toolkit/modules/PropertyListUtils.jsm | 8 +- toolkit/modules/RemoteController.jsm | 16 +- toolkit/modules/RemoteFinder.jsm | 46 +- toolkit/modules/RemotePageManager.jsm | 58 +-- toolkit/modules/RemoteSecurityUI.jsm | 2 +- toolkit/modules/RemoteWebProgress.jsm | 18 +- toolkit/modules/ResetProfile.jsm | 4 +- toolkit/modules/SelectContentHelper.jsm | 22 +- toolkit/modules/SelectParentHelper.jsm | 14 +- toolkit/modules/SessionRecorder.jsm | 30 +- toolkit/modules/ShortcutUtils.jsm | 4 +- toolkit/modules/SpatialNavigation.jsm | 6 +- toolkit/modules/Sqlite.jsm | 68 +-- toolkit/modules/Task.jsm | 2 +- toolkit/modules/WebChannel.jsm | 22 +- toolkit/modules/WindowDraggingUtils.jsm | 8 +- toolkit/modules/WindowsRegistry.jsm | 4 +- toolkit/modules/secondscreen/RokuApp.jsm | 6 +- .../secondscreen/SimpleServiceDiscovery.jsm | 26 +- toolkit/modules/sessionstore/FormData.jsm | 16 +- .../modules/sessionstore/ScrollPosition.jsm | 6 +- toolkit/modules/sessionstore/Utils.jsm | 8 +- .../tests/browser/browser_Deprecated.js | 12 +- .../modules/tests/browser/browser_Finder.js | 4 +- .../browser/browser_FinderHighlighter.js | 2 +- .../browser/browser_Finder_hidden_textarea.js | 2 +- .../modules/tests/browser/browser_Geometry.js | 8 +- .../browser/browser_InlineSpellChecker.js | 2 +- .../tests/xpcshell/test_GMPInstallManager.js | 20 +- toolkit/modules/tests/xpcshell/test_Http.js | 28 +- toolkit/modules/tests/xpcshell/test_Log.js | 2 +- .../tests/xpcshell/test_NewTabUtils.js | 10 +- .../tests/xpcshell/test_ObjectUtils.js | 2 +- .../tests/xpcshell/test_Preferences.js | 4 +- .../modules/tests/xpcshell/test_Promise.js | 2 +- .../modules/tests/xpcshell/test_client_id.js | 4 +- .../tests/xpcshell/test_session_recorder.js | 2 +- toolkit/modules/tests/xpcshell/test_sqlite.js | 30 +- .../tests/xpcshell/test_sqlite_shutdown.js | 4 +- .../tests/xpcshell/test_web_channel.js | 4 +- .../tests/xpcshell/test_web_channel_broker.js | 2 +- toolkit/mozapps/downloads/DownloadLastDir.jsm | 16 +- toolkit/mozapps/extensions/AddonManager.jsm | 246 +++++----- .../extensions/ChromeManifestParser.jsm | 10 +- toolkit/mozapps/extensions/DeferredSave.jsm | 12 +- .../extensions/LightweightThemeManager.jsm | 50 +- toolkit/mozapps/extensions/addonManager.js | 28 +- .../mozapps/extensions/amContentHandler.js | 6 +- .../mozapps/extensions/amInstallTrigger.js | 24 +- .../extensions/amWebInstallListener.js | 28 +- .../mozapps/extensions/content/extensions.js | 444 +++++++++--------- .../mozapps/extensions/content/newaddon.js | 2 +- .../mozapps/extensions/content/setting.xml | 4 +- toolkit/mozapps/extensions/content/update.js | 70 +-- .../extensions/content/xpinstallConfirm.js | 2 +- .../extensions/internal/AddonLogging.jsm | 12 +- .../extensions/internal/AddonRepository.jsm | 104 ++-- .../AddonRepository_SQLiteMigrator.jsm | 40 +- .../extensions/internal/AddonTestUtils.jsm | 12 +- .../internal/AddonUpdateChecker.jsm | 28 +- .../extensions/internal/GMPProvider.jsm | 38 +- .../LightweightThemeImageOptimizer.jsm | 16 +- .../extensions/internal/PluginProvider.jsm | 26 +- .../internal/ProductAddonChecker.jsm | 29 +- .../extensions/internal/XPIProvider.jsm | 254 +++++----- .../extensions/internal/XPIProviderUtils.js | 74 +-- .../mozapps/extensions/nsBlocklistService.js | 76 +-- .../extensions/nsBlocklistServiceContent.js | 22 +- .../extensions/test/AddonManagerTesting.jsm | 14 +- .../browser_addonrepository_performance.js | 2 +- .../test/browser/browser_bug557956.js | 2 +- .../test/browser/browser_bug562797.js | 10 +- .../test/browser/browser_bug562992.js | 2 +- .../test/browser/browser_bug567127.js | 10 +- .../test/browser/browser_bug572561.js | 8 +- .../test/browser/browser_bug577990.js | 2 +- .../test/browser/browser_bug586574.js | 4 +- .../test/browser/browser_bug587970.js | 4 +- .../test/browser/browser_bug591663.js | 12 +- .../test/browser/browser_bug593535.js | 4 +- .../test/browser/browser_bug596336.js | 2 +- .../test/browser/browser_bug608316.js | 2 +- .../test/browser/browser_cancelCompatCheck.js | 4 +- .../test/browser/browser_discovery.js | 10 +- .../test/browser/browser_dragdrop.js | 10 +- .../extensions/test/browser/browser_eula.js | 2 +- .../test/browser/browser_gmpProvider.js | 2 +- .../test/browser/browser_inlinesettings.js | 12 +- .../browser/browser_inlinesettings_custom.js | 2 +- .../browser/browser_inlinesettings_info.js | 12 +- .../test/browser/browser_install.js | 12 +- .../test/browser/browser_installssl.js | 4 +- .../test/browser/browser_manualupdates.js | 4 +- .../test/browser/browser_searching.js | 10 +- .../test/browser/browser_updatessl.js | 6 +- .../test/browser/browser_webapi_install.js | 2 +- .../mozapps/extensions/test/browser/head.js | 50 +- .../extensions/test/xpcshell/head_addons.js | 40 +- .../test/xpcshell/test_AddonRepository.js | 36 +- .../test_AddonRepository_compatmode.js | 12 +- .../test/xpcshell/test_DeferredSave.js | 8 +- .../test/xpcshell/test_XPIcancel.js | 6 +- .../test/xpcshell/test_backgroundupdate.js | 4 +- .../test/xpcshell/test_badschema.js | 4 +- .../test_blocklist_metadata_filters.js | 4 +- .../test/xpcshell/test_blocklist_prefs.js | 4 +- .../test/xpcshell/test_blocklist_regexp.js | 4 +- .../test/xpcshell/test_blocklistchange.js | 12 +- .../test/xpcshell/test_bug1180901_2.js | 4 +- .../test/xpcshell/test_bug299716_2.js | 2 +- .../test/xpcshell/test_bug335238.js | 14 +- .../test/xpcshell/test_bug384052.js | 10 +- .../test/xpcshell/test_bug393285.js | 4 +- .../test/xpcshell/test_bug406118.js | 4 +- .../test/xpcshell/test_bug424262.js | 4 +- .../test/xpcshell/test_bug430120.js | 6 +- .../test/xpcshell/test_bug449027.js | 8 +- .../test/xpcshell/test_bug455906.js | 8 +- .../test/xpcshell/test_bug465190.js | 4 +- .../test/xpcshell/test_bug514327_3.js | 8 +- .../test/xpcshell/test_bug542391.js | 6 +- .../test/xpcshell/test_bug554133.js | 4 +- .../test/xpcshell/test_bug594058.js | 6 +- .../test/xpcshell/test_bug655254.js | 4 +- .../test/xpcshell/test_bug757663.js | 12 +- .../test/xpcshell/test_cache_certdb.js | 2 +- .../test/xpcshell/test_cacheflush.js | 6 +- .../extensions/test/xpcshell/test_corrupt.js | 4 +- .../xpcshell/test_corrupt_strictcompat.js | 4 +- .../extensions/test/xpcshell/test_dss.js | 2 +- .../test/xpcshell/test_duplicateplugins.js | 4 +- .../extensions/test/xpcshell/test_hotfix.js | 8 +- .../extensions/test/xpcshell/test_install.js | 40 +- .../xpcshell/test_install_strictcompat.js | 40 +- .../test/xpcshell/test_json_updatecheck.js | 4 +- .../extensions/test/xpcshell/test_locked.js | 4 +- .../test/xpcshell/test_locked_strictcompat.js | 4 +- .../test/xpcshell/test_mapURIToAddonID.js | 10 +- .../test/xpcshell/test_metadata_update.js | 4 +- .../extensions/test/xpcshell/test_migrate4.js | 4 +- .../test/xpcshell/test_pluginchange.js | 4 +- .../test/xpcshell/test_pref_properties.js | 8 +- .../test/xpcshell/test_signed_migrate.js | 4 +- .../test/xpcshell/test_softblocked.js | 4 +- .../extensions/test/xpcshell/test_startup.js | 2 +- .../test/xpcshell/test_system_update.js | 8 +- .../extensions/test/xpcshell/test_theme.js | 4 +- .../extensions/test/xpcshell/test_types.js | 4 +- .../extensions/test/xpcshell/test_update.js | 118 ++--- .../test/xpcshell/test_updateCancel.js | 4 +- .../test/xpcshell/test_update_compatmode.js | 30 +- .../test/xpcshell/test_update_ignorecompat.js | 10 +- .../test/xpcshell/test_update_strictcompat.js | 102 ++-- .../test/xpcshell/test_updatecheck.js | 2 +- .../test/xpcshell/test_webextension.js | 4 +- .../xpcshell/test_webextension_install.js | 8 +- .../xpinstall/browser_amosigned_trigger.js | 2 +- .../browser_amosigned_trigger_iframe.js | 2 +- .../test/xpinstall/browser_badhash.js | 2 +- .../test/xpinstall/browser_badhashtype.js | 2 +- .../test/xpinstall/browser_bug638292.js | 2 +- .../xpinstall/browser_concurrent_installs.js | 6 +- .../extensions/test/xpinstall/browser_hash.js | 2 +- .../test/xpinstall/browser_hash2.js | 2 +- .../test/xpinstall/browser_httphash.js | 2 +- .../test/xpinstall/browser_httphash2.js | 2 +- .../test/xpinstall/browser_httphash3.js | 2 +- .../test/xpinstall/browser_httphash4.js | 2 +- .../test/xpinstall/browser_httphash5.js | 2 +- .../test/xpinstall/browser_httphash6.js | 2 +- .../test/xpinstall/browser_relative.js | 2 +- .../test/xpinstall/browser_switchtab.js | 2 +- .../xpinstall/browser_unsigned_trigger.js | 2 +- .../browser_unsigned_trigger_iframe.js | 2 +- .../browser_unsigned_trigger_xorigin.js | 2 +- .../mozapps/extensions/test/xpinstall/head.js | 44 +- .../test/xpinstall/triggerredirect.html | 2 +- toolkit/mozapps/preferences/fontbuilder.js | 2 +- toolkit/mozapps/preferences/removemp.js | 6 +- toolkit/mozapps/update/content/history.js | 4 +- toolkit/mozapps/update/content/updates.js | 94 ++-- toolkit/mozapps/update/nsUpdateService.js | 8 +- toolkit/mozapps/update/nsUpdateServiceStub.js | 2 +- toolkit/mozapps/update/tests/chrome/utils.js | 2 +- toolkit/mozapps/update/tests/data/shared.js | 2 +- .../update/tests/data/xpcshellUtilsAUS.js | 6 +- .../downloadInterruptedRecovery.js | 10 +- .../tests/unit_aus_update/uiAutoPref.js | 4 +- .../tests/unit_aus_update/uiSilentPref.js | 4 +- .../uiUnsupportedAlreadyNotified.js | 4 +- 854 files changed, 8157 insertions(+), 8141 deletions(-) diff --git a/browser/base/content/aboutDialog-appUpdater.js b/browser/base/content/aboutDialog-appUpdater.js index 06fe9e18ce3b..f78d2366f689 100644 --- a/browser/base/content/aboutDialog-appUpdater.js +++ b/browser/base/content/aboutDialog-appUpdater.js @@ -168,7 +168,7 @@ appUpdater.prototype = * @param aChildID * The id of the deck's child to select, e.g. "apply". */ - selectPanel(aChildID) { + selectPanel: function(aChildID) { let panel = document.getElementById(aChildID); let button = panel.querySelector("button"); @@ -191,7 +191,7 @@ appUpdater.prototype = /** * Check for updates */ - checkForUpdates() { + checkForUpdates: function() { // Clear prefs that could prevent a user from discovering available updates. if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_CANCELATIONS_OSX)) { Services.prefs.clearUserPref(PREF_APP_UPDATE_CANCELATIONS_OSX); @@ -209,7 +209,7 @@ appUpdater.prototype = * Handles oncommand for the "Restart to Update" button * which is presented after the download has been downloaded. */ - buttonRestartAfterDownload() { + buttonRestartAfterDownload: function() { if (!this.isPending && !this.isApplied) { return; } @@ -249,7 +249,7 @@ appUpdater.prototype = /** * See nsIUpdateService.idl */ - onCheckComplete(aRequest, aUpdates, aUpdateCount) { + onCheckComplete: function(aRequest, aUpdates, aUpdateCount) { gAppUpdater.isChecking = false; gAppUpdater.update = gAppUpdater.aus. selectUpdate(aUpdates, aUpdates.length); @@ -281,7 +281,7 @@ appUpdater.prototype = /** * See nsIUpdateService.idl */ - onError(aRequest, aUpdate) { + onError: function(aRequest, aUpdate) { // Errors in the update check are treated as no updates found. If the // update check fails repeatedly without a success the user will be // notified with the normal app update user interface so this is safe. @@ -292,7 +292,7 @@ appUpdater.prototype = /** * See nsISupports.idl */ - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (!aIID.equals(Components.interfaces.nsIUpdateCheckListener) && !aIID.equals(Components.interfaces.nsISupports)) throw Components.results.NS_ERROR_NO_INTERFACE; @@ -303,7 +303,7 @@ appUpdater.prototype = /** * Starts the download of an update mar. */ - startDownload() { + startDownload: function() { if (!this.update) this.update = this.um.activeUpdate; this.update.QueryInterface(Components.interfaces.nsIWritablePropertyBag); @@ -322,7 +322,7 @@ appUpdater.prototype = /** * Switches to the UI responsible for tracking the download. */ - setupDownloadingUI() { + setupDownloadingUI: function() { this.downloadStatus = document.getElementById("downloadStatus"); this.downloadStatus.value = DownloadUtils.getTransferTotal(0, this.update.selectedPatch.size); @@ -330,7 +330,7 @@ appUpdater.prototype = this.aus.addDownloadListener(this); }, - removeDownloadListener() { + removeDownloadListener: function() { if (this.aus) { this.aus.removeDownloadListener(this); } @@ -339,13 +339,13 @@ appUpdater.prototype = /** * See nsIRequestObserver.idl */ - onStartRequest(aRequest, aContext) { + onStartRequest: function(aRequest, aContext) { }, /** * See nsIRequestObserver.idl */ - onStopRequest(aRequest, aContext, aStatusCode) { + onStopRequest: function(aRequest, aContext, aStatusCode) { switch (aStatusCode) { case Components.results.NS_ERROR_UNEXPECTED: if (this.update.selectedPatch.state == "download-failed" && @@ -404,13 +404,13 @@ appUpdater.prototype = /** * See nsIProgressEventSink.idl */ - onStatus(aRequest, aContext, aStatus, aStatusArg) { + onStatus: function(aRequest, aContext, aStatus, aStatusArg) { }, /** * See nsIProgressEventSink.idl */ - onProgress(aRequest, aContext, aProgress, aProgressMax) { + onProgress: function(aRequest, aContext, aProgress, aProgressMax) { this.downloadStatus.value = DownloadUtils.getTransferTotal(aProgress, aProgressMax); }, @@ -418,7 +418,7 @@ appUpdater.prototype = /** * See nsISupports.idl */ - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (!aIID.equals(Components.interfaces.nsIProgressEventSink) && !aIID.equals(Components.interfaces.nsIRequestObserver) && !aIID.equals(Components.interfaces.nsISupports)) diff --git a/browser/base/content/aboutaccounts/aboutaccounts.js b/browser/base/content/aboutaccounts/aboutaccounts.js index f1660ca4149a..bb9d00b1627d 100644 --- a/browser/base/content/aboutaccounts/aboutaccounts.js +++ b/browser/base/content/aboutaccounts/aboutaccounts.js @@ -101,7 +101,7 @@ function updateDisplayedEmail(user) { var wrapper = { iframe: null, - init(url, urlParams) { + init: function(url, urlParams) { // If a master-password is enabled, we want to encourage the user to // unlock it. Things still work if not, but the user will probably need // to re-auth next startup (in which case we will get here again and @@ -130,7 +130,7 @@ var wrapper = { webNav.loadURI(url, Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY, null, null, null); }, - retry() { + retry: function() { let webNav = this.iframe.frameLoader.docShell.QueryInterface(Ci.nsIWebNavigation); webNav.loadURI(this.url, Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY, null, null, null); }, @@ -140,7 +140,7 @@ var wrapper = { Ci.nsISupportsWeakReference, Ci.nsISupports]), - onStateChange(aWebProgress, aRequest, aState, aStatus) { + onStateChange: function(aWebProgress, aRequest, aState, aStatus) { let failure = false; // Captive portals sometimes redirect users @@ -164,19 +164,19 @@ var wrapper = { } }, - onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { if (aRequest && aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) { aRequest.cancel(Components.results.NS_BINDING_ABORTED); setErrorPage("networkError"); } }, - onProgressChange() {}, - onStatusChange() {}, - onSecurityChange() {}, + onProgressChange: function() {}, + onStatusChange: function() {}, + onSecurityChange: function() {}, }, - handleEvent(evt) { + handleEvent: function(evt) { switch (evt.type) { case "load": this.iframe.contentWindow.addEventListener("FirefoxAccountsCommand", this); @@ -194,7 +194,7 @@ var wrapper = { * * @param accountData the user's account data and credentials */ - onLogin(accountData) { + onLogin: function(accountData) { log("Received: 'login'. Data:" + JSON.stringify(accountData)); if (accountData.customizeSync) { @@ -251,16 +251,16 @@ var wrapper = { ); }, - onCanLinkAccount(accountData) { + onCanLinkAccount: function(accountData) { // We need to confirm a relink - see shouldAllowRelink for more let ok = shouldAllowRelink(accountData.email); - this.injectData("message", { status: "can_link_account", data: { ok } }); + this.injectData("message", { status: "can_link_account", data: { ok: ok } }); }, /** * onSignOut handler erases the current user's session from the fxaccounts service */ - onSignOut() { + onSignOut: function() { log("Received: 'sign_out'."); fxAccounts.signOut().then( @@ -269,7 +269,7 @@ var wrapper = { ); }, - handleRemoteCommand(evt) { + handleRemoteCommand: function(evt) { log('command: ' + evt.detail.command); let data = evt.detail.data; @@ -289,11 +289,11 @@ var wrapper = { } }, - injectData(type, content) { + injectData: function(type, content) { return fxAccounts.promiseAccountsSignUpURI().then(authUrl => { let data = { - type, - content + type: type, + content: content }; this.iframe.contentWindow.postMessage(data, authUrl); }) diff --git a/browser/base/content/abouthealthreport/abouthealth.js b/browser/base/content/abouthealthreport/abouthealth.js index ae59e238eb0a..a21248f62d48 100644 --- a/browser/base/content/abouthealthreport/abouthealth.js +++ b/browser/base/content/abouthealthreport/abouthealth.js @@ -15,28 +15,28 @@ const PREF_UNIFIED = "toolkit.telemetry.unified"; const PREF_REPORTING_URL = "datareporting.healthreport.about.reportUrl"; var healthReportWrapper = { - init() { + init: function() { let iframe = document.getElementById("remote-report"); iframe.addEventListener("load", healthReportWrapper.initRemotePage, false); iframe.src = this._getReportURI().spec; prefs.observe("uploadEnabled", this.updatePrefState, healthReportWrapper); }, - uninit() { + uninit: function() { prefs.ignore("uploadEnabled", this.updatePrefState, healthReportWrapper); }, - _getReportURI() { + _getReportURI: function() { let url = Services.urlFormatter.formatURLPref(PREF_REPORTING_URL); return Services.io.newURI(url, null, null); }, - setDataSubmission(enabled) { + setDataSubmission: function(enabled) { MozSelfSupport.healthReportDataSubmissionEnabled = enabled; this.updatePrefState(); }, - updatePrefState() { + updatePrefState: function() { try { let prefsObj = { enabled: MozSelfSupport.healthReportDataSubmissionEnabled, @@ -48,7 +48,7 @@ var healthReportWrapper = { } }, - sendTelemetryPingList() { + sendTelemetryPingList: function() { console.log("AboutHealthReport: Collecting Telemetry ping list."); MozSelfSupport.getTelemetryPingList().then((list) => { console.log("AboutHealthReport: Sending Telemetry ping list."); @@ -58,7 +58,7 @@ var healthReportWrapper = { }); }, - sendTelemetryPingData(pingId) { + sendTelemetryPingData: function(pingId) { console.log("AboutHealthReport: Collecting Telemetry ping data."); MozSelfSupport.getTelemetryPing(pingId).then((ping) => { console.log("AboutHealthReport: Sending Telemetry ping data."); @@ -75,7 +75,7 @@ var healthReportWrapper = { }); }, - sendCurrentEnvironment() { + sendCurrentEnvironment: function() { console.log("AboutHealthReport: Sending Telemetry environment data."); MozSelfSupport.getCurrentTelemetryEnvironment().then((environment) => { this.injectData("telemetry-current-environment-data", environment); @@ -84,7 +84,7 @@ var healthReportWrapper = { }); }, - sendCurrentPingData() { + sendCurrentPingData: function() { console.log("AboutHealthReport: Sending current Telemetry ping data."); MozSelfSupport.getCurrentTelemetrySubsessionPing().then((ping) => { this.injectData("telemetry-current-ping-data", ping); @@ -93,7 +93,7 @@ var healthReportWrapper = { }); }, - injectData(type, content) { + injectData: function(type, content) { let report = this._getReportURI(); // file URIs can't be used for targetOrigin, so we use "*" for this special case @@ -101,15 +101,15 @@ var healthReportWrapper = { let reportUrl = report.scheme == "file" ? "*" : report.spec; let data = { - type, - content + type: type, + content: content } let iframe = document.getElementById("remote-report"); iframe.contentWindow.postMessage(data, reportUrl); }, - handleRemoteCommand(evt) { + handleRemoteCommand: function(evt) { // Do an origin check to harden against the frame content being loaded from unexpected locations. let allowedPrincipal = Services.scriptSecurityManager.getCodebasePrincipal(this._getReportURI()); let targetPrincipal = evt.target.nodePrincipal; @@ -147,7 +147,7 @@ var healthReportWrapper = { } }, - initRemotePage() { + initRemotePage: function() { let iframe = document.getElementById("remote-report").contentDocument; iframe.addEventListener("RemoteHealthReportCommand", function onCommand(e) { healthReportWrapper.handleRemoteCommand(e); }, @@ -160,18 +160,18 @@ var healthReportWrapper = { ERROR_PAYLOAD_FAILED: 2, ERROR_PREFS_FAILED: 3, - reportFailure(error) { + reportFailure: function(error) { let details = { errorType: error, } healthReportWrapper.injectData("error", details); }, - handleInitFailure() { + handleInitFailure: function() { healthReportWrapper.reportFailure(healthReportWrapper.ERROR_INIT_FAILED); }, - handlePayloadFailure() { + handlePayloadFailure: function() { healthReportWrapper.reportFailure(healthReportWrapper.ERROR_PAYLOAD_FAILED); }, } diff --git a/browser/base/content/abouthome/aboutHome.js b/browser/base/content/abouthome/aboutHome.js index 54dd71b96493..498d9bd2ed31 100644 --- a/browser/base/content/abouthome/aboutHome.js +++ b/browser/base/content/abouthome/aboutHome.js @@ -186,18 +186,18 @@ function ensureSnippetsMapThen(aCallback) // The cache has been filled up, create the snippets map. gSnippetsMap = Object.freeze({ get: (aKey) => cache.get(aKey), - set(aKey, aValue) { + set: function(aKey, aValue) { db.transaction(SNIPPETS_OBJECTSTORE_NAME, "readwrite") .objectStore(SNIPPETS_OBJECTSTORE_NAME).put(aValue, aKey); return cache.set(aKey, aValue); }, has: (aKey) => cache.has(aKey), - delete(aKey) { + delete: function(aKey) { db.transaction(SNIPPETS_OBJECTSTORE_NAME, "readwrite") .objectStore(SNIPPETS_OBJECTSTORE_NAME).delete(aKey); return cache.delete(aKey); }, - clear() { + clear: function() { db.transaction(SNIPPETS_OBJECTSTORE_NAME, "readwrite") .objectStore(SNIPPETS_OBJECTSTORE_NAME).clear(); return cache.clear(); diff --git a/browser/base/content/browser-addons.js b/browser/base/content/browser-addons.js index 8957c36c69e0..1b52cde94901 100644 --- a/browser/base/content/browser-addons.js +++ b/browser/base/content/browser-addons.js @@ -30,7 +30,7 @@ function removeNotificationOnEnd(notification, installs) { } const gXPInstallObserver = { - _findChildShell(aDocShell, aSoughtShell) + _findChildShell: function(aDocShell, aSoughtShell) { if (aDocShell == aSoughtShell) return aDocShell; @@ -45,7 +45,7 @@ const gXPInstallObserver = { return null; }, - _getBrowser(aDocShell) + _getBrowser: function(aDocShell) { for (let browser of gBrowser.browsers) { if (this._findChildShell(browser.docShell, aDocShell)) @@ -56,7 +56,7 @@ const gXPInstallObserver = { pendingInstalls: new WeakMap(), - showInstallConfirmation(browser, installInfo, height = undefined) { + showInstallConfirmation: function(browser, installInfo, height = undefined) { // If the confirmation notification is already open cache the installInfo // and the new confirmation will be shown later if (PopupNotifications.getNotification("addon-install-confirmation", browser)) { @@ -217,7 +217,7 @@ const gXPInstallObserver = { .add(Ci.nsISecurityUITelemetry.WARNING_CONFIRM_ADDON_INSTALL); }, - observe(aSubject, aTopic, aData) + observe: function(aSubject, aTopic, aData) { var brandBundle = document.getElementById("bundle_brand"); var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo); @@ -282,7 +282,7 @@ const gXPInstallObserver = { action = { label: gNavigatorBundle.getString("xpinstallPromptAllowButton"), accessKey: gNavigatorBundle.getString("xpinstallPromptAllowButton.accesskey"), - callback() { + callback: function() { secHistogram.add(Ci.nsISecurityUITelemetry.WARNING_ADDON_ASKING_PREVENTED_CLICK_THROUGH); installInfo.install(); } @@ -433,7 +433,7 @@ const gXPInstallObserver = { action = { label: gNavigatorBundle.getString("addonInstallRestartButton"), accessKey: gNavigatorBundle.getString("addonInstallRestartButton.accesskey"), - callback() { + callback: function() { BrowserUtils.restartApplication(); } }; @@ -472,14 +472,14 @@ const gXPInstallObserver = { }; var LightWeightThemeWebInstaller = { - init() { + init: function() { let mm = window.messageManager; mm.addMessageListener("LightWeightThemeWebInstaller:Install", this); mm.addMessageListener("LightWeightThemeWebInstaller:Preview", this); mm.addMessageListener("LightWeightThemeWebInstaller:ResetPreview", this); }, - receiveMessage(message) { + receiveMessage: function(message) { // ignore requests from background tabs if (message.target != gBrowser.selectedBrowser) { return; @@ -503,7 +503,7 @@ var LightWeightThemeWebInstaller = { } }, - handleEvent(event) { + handleEvent: function(event) { switch (event.type) { case "TabSelect": { this._resetPreview(); @@ -519,7 +519,7 @@ var LightWeightThemeWebInstaller = { return this._manager = temp.LightweightThemeManager; }, - _installRequest(dataString, baseURI) { + _installRequest: function(dataString, baseURI) { let data = this._manager.parseTheme(dataString, baseURI); if (!data) { @@ -560,7 +560,7 @@ var LightWeightThemeWebInstaller = { let buttons = [{ label: allowButtonText, accessKey: allowButtonAccesskey, - callback() { + callback: function() { LightWeightThemeWebInstaller._install(data, notify); } }]; @@ -575,11 +575,11 @@ var LightWeightThemeWebInstaller = { notificationBar.persistence = 1; }, - _install(newLWTheme, notify) { + _install: function(newLWTheme, notify) { let previousLWTheme = this._manager.currentTheme; let listener = { - onEnabling(aAddon, aRequiresRestart) { + onEnabling: function(aAddon, aRequiresRestart) { if (!aRequiresRestart) { return; } @@ -590,7 +590,7 @@ var LightWeightThemeWebInstaller = { let action = { label: gNavigatorBundle.getString("lwthemeNeedsRestart.button"), accessKey: gNavigatorBundle.getString("lwthemeNeedsRestart.accesskey"), - callback() { + callback: function() { BrowserUtils.restartApplication(); } }; @@ -604,7 +604,7 @@ var LightWeightThemeWebInstaller = { action, null, options); }, - onEnabled(aAddon) { + onEnabled: function(aAddon) { if (notify) { LightWeightThemeWebInstaller._postInstallNotification(newLWTheme, previousLWTheme); } @@ -616,7 +616,7 @@ var LightWeightThemeWebInstaller = { AddonManager.removeAddonListener(listener); }, - _postInstallNotification(newTheme, previousTheme) { + _postInstallNotification: function(newTheme, previousTheme) { function text(id) { return gNavigatorBundle.getString("lwthemePostInstallNotification." + id); } @@ -624,14 +624,14 @@ var LightWeightThemeWebInstaller = { let buttons = [{ label: text("undoButton"), accessKey: text("undoButton.accesskey"), - callback() { + callback: function() { LightWeightThemeWebInstaller._manager.forgetUsedTheme(newTheme.id); LightWeightThemeWebInstaller._manager.currentTheme = previousTheme; } }, { label: text("manageButton"), accessKey: text("manageButton.accesskey"), - callback() { + callback: function() { BrowserOpenAddonsMgr("addons://list/theme"); } }]; @@ -648,7 +648,7 @@ var LightWeightThemeWebInstaller = { notificationBar.timeout = Date.now() + 20000; // 20 seconds }, - _removePreviousNotifications() { + _removePreviousNotifications: function() { let box = gBrowser.getNotificationBox(); ["lwtheme-install-request", @@ -659,7 +659,7 @@ var LightWeightThemeWebInstaller = { }); }, - _preview(dataString, baseURI) { + _preview: function(dataString, baseURI) { if (!this._isAllowed(baseURI)) return; @@ -672,14 +672,14 @@ var LightWeightThemeWebInstaller = { this._manager.previewTheme(data); }, - _resetPreview(baseURI) { + _resetPreview: function(baseURI) { if (baseURI && !this._isAllowed(baseURI)) return; gBrowser.tabContainer.removeEventListener("TabSelect", this, false); this._manager.resetPreview(); }, - _isAllowed(srcURIString) { + _isAllowed: function(srcURIString) { let uri; try { uri = makeURI(srcURIString); @@ -704,7 +704,7 @@ var LightWeightThemeWebInstaller = { var LightweightThemeListener = { _modifiedStyles: [], - init() { + init: function() { XPCOMUtils.defineLazyGetter(this, "styleSheet", function() { for (let i = document.styleSheets.length - 1; i >= 0; i--) { let sheet = document.styleSheets[i]; @@ -720,7 +720,7 @@ var LightweightThemeListener = { this.updateStyleSheet(document.documentElement.style.backgroundImage); }, - uninit() { + uninit: function() { Services.obs.removeObserver(this, "lightweight-theme-styling-update"); Services.obs.removeObserver(this, "lightweight-theme-optimized"); }, @@ -731,13 +731,13 @@ var LightweightThemeListener = { * * @param headerImage - a string containing a CSS image for the lightweight theme header. */ - updateStyleSheet(headerImage) { + updateStyleSheet: function(headerImage) { if (!this.styleSheet) return; this.substituteRules(this.styleSheet.cssRules, headerImage); }, - substituteRules(ruleList, headerImage, existingStyleRulesModified = 0) { + substituteRules: function(ruleList, headerImage, existingStyleRulesModified = 0) { let styleRulesModified = 0; for (let i = 0; i < ruleList.length; i++) { let rule = ruleList[i]; @@ -761,7 +761,7 @@ var LightweightThemeListener = { }, // nsIObserver - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if ((aTopic != "lightweight-theme-styling-update" && aTopic != "lightweight-theme-optimized") || !this.styleSheet) return; diff --git a/browser/base/content/browser-ctrlTab.js b/browser/base/content/browser-ctrlTab.js index 88cff082b1e2..7cafd8541948 100644 --- a/browser/base/content/browser-ctrlTab.js +++ b/browser/base/content/browser-ctrlTab.js @@ -96,7 +96,7 @@ var tabPreviews = { }; var tabPreviewPanelHelper = { - opening(host) { + opening: function(host) { host.panel.hidden = false; var handler = this._generateHandler(host); @@ -105,7 +105,7 @@ var tabPreviewPanelHelper = { host._prevFocus = document.commandDispatcher.focusedElement; }, - _generateHandler(host) { + _generateHandler: function(host) { var self = this; return function(event) { if (event.target == host.panel) { @@ -114,11 +114,11 @@ var tabPreviewPanelHelper = { } }; }, - _popupshown(host) { + _popupshown: function(host) { if ("setupGUI" in host) host.setupGUI(); }, - _popuphiding(host) { + _popuphiding: function(host) { if ("suspendGUI" in host) host.suspendGUI(); @@ -219,7 +219,7 @@ var ctrlTab = { else this.uninit(); }, - observe(aSubject, aTopic, aPrefName) { + observe: function(aSubject, aTopic, aPrefName) { this.readPref(); }, @@ -507,7 +507,7 @@ var ctrlTab = { } }, - filterForThumbnailExpiration(aCallback) { + filterForThumbnailExpiration: function(aCallback) { // Save a few more thumbnails than we actually display, so that when tabs // are closed, the previews we add instead still get thumbnails. const extraThumbnails = 3; @@ -521,7 +521,7 @@ var ctrlTab = { aCallback(urls); }, - _initRecentlyUsedTabs() { + _initRecentlyUsedTabs: function() { this._recentlyUsedTabs = Array.filter(gBrowser.tabs, tab => !tab.closing) .sort((tab1, tab2) => tab2.lastAccessed - tab1.lastAccessed); diff --git a/browser/base/content/browser-customization.js b/browser/base/content/browser-customization.js index 672d25ec6caa..d5d51b8931a3 100644 --- a/browser/base/content/browser-customization.js +++ b/browser/base/content/browser-customization.js @@ -9,7 +9,7 @@ * events. */ var CustomizationHandler = { - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "customizationstarting": this._customizationStarting(); @@ -23,11 +23,11 @@ var CustomizationHandler = { } }, - isCustomizing() { + isCustomizing: function() { return document.documentElement.hasAttribute("customizing"); }, - _customizationStarting() { + _customizationStarting: function() { // Disable the toolbar context menu items let menubar = document.getElementById("main-menubar"); for (let childNode of menubar.childNodes) @@ -51,11 +51,11 @@ var CustomizationHandler = { } }, - _customizationChange() { + _customizationChange: function() { PlacesToolbarHelper.customizeChange(); }, - _customizationEnding(aDetails) { + _customizationEnding: function(aDetails) { // Update global UI elements that may have been added or removed if (aDetails.changed) { gURLBar = document.getElementById("urlbar"); diff --git a/browser/base/content/browser-data-submission-info-bar.js b/browser/base/content/browser-data-submission-info-bar.js index 456f91b48ee0..0d2c7aabfc10 100644 --- a/browser/base/content/browser-data-submission-info-bar.js +++ b/browser/base/content/browser-data-submission-info-bar.js @@ -27,7 +27,7 @@ var gDataNotificationInfoBar = { return this._log = Log.repository.getLoggerWithMessagePrefix(LOGGER_NAME, LOGGER_PREFIX); }, - init() { + init: function() { window.addEventListener("unload", () => { for (let o of this._OBSERVERS) { Services.obs.removeObserver(this, o); @@ -39,11 +39,11 @@ var gDataNotificationInfoBar = { } }, - _getDataReportingNotification(name = this._DATA_REPORTING_NOTIFICATION) { + _getDataReportingNotification: function(name = this._DATA_REPORTING_NOTIFICATION) { return this._notificationBox.getNotificationWithValue(name); }, - _displayDataPolicyInfoBar(request) { + _displayDataPolicyInfoBar: function(request) { if (this._getDataReportingNotification()) { return; } @@ -88,7 +88,7 @@ var gDataNotificationInfoBar = { request.onUserNotifyComplete(); }, - _clearPolicyNotification() { + _clearPolicyNotification: function() { let notification = this._getDataReportingNotification(); if (notification) { this._log.debug("Closing notification."); @@ -96,7 +96,7 @@ var gDataNotificationInfoBar = { } }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case "datareporting:notify-data-policy:request": let request = subject.wrappedJSObject.object; diff --git a/browser/base/content/browser-devedition.js b/browser/base/content/browser-devedition.js index aa4da1d5ba0e..8c1fe88a5b0e 100644 --- a/browser/base/content/browser-devedition.js +++ b/browser/base/content/browser-devedition.js @@ -21,7 +21,7 @@ var DevEdition = { return theme && theme.id == "firefox-devedition@mozilla.org"; }, - init() { + init: function() { this.initialized = true; Services.prefs.addObserver(this._devtoolsThemePrefName, this, false); Services.obs.addObserver(this, "lightweight-theme-styling-update", false); @@ -33,7 +33,7 @@ var DevEdition = { } }, - createStyleSheet() { + createStyleSheet: function() { let styleSheetAttr = `href="${this.styleSheetLocation}" type="text/css"`; this.styleSheet = document.createProcessingInstruction( "xml-stylesheet", styleSheetAttr); @@ -42,7 +42,7 @@ var DevEdition = { this.styleSheet.sheet.disabled = true; }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { if (topic == "lightweight-theme-styling-update") { let newTheme = JSON.parse(data); if (newTheme && newTheme.id == "firefox-devedition@mozilla.org") { @@ -59,7 +59,7 @@ var DevEdition = { } }, - _inferBrightness() { + _inferBrightness: function() { ToolbarIconColor.inferFromText(); // Get an inverted full screen button if the dark theme is applied. if (this.isStyleSheetEnabled && @@ -78,7 +78,7 @@ var DevEdition = { } }, - _updateDevtoolsThemeAttribute() { + _updateDevtoolsThemeAttribute: function() { // Set an attribute on root element to make it possible // to change colors based on the selected devtools theme. let devtoolsTheme = Services.prefs.getCharPref(this._devtoolsThemePrefName); @@ -90,14 +90,14 @@ var DevEdition = { this._inferBrightness(); }, - handleEvent(e) { + handleEvent: function(e) { if (e.type === "load") { this.styleSheet.removeEventListener("load", this); this.refreshBrowserDisplay(); } }, - refreshBrowserDisplay() { + refreshBrowserDisplay: function() { // Don't touch things on the browser if gBrowserInit.onLoad hasn't // yet fired. if (this.initialized) { @@ -106,7 +106,7 @@ var DevEdition = { } }, - _toggleStyleSheet(deveditionThemeEnabled) { + _toggleStyleSheet: function(deveditionThemeEnabled) { let wasEnabled = this.isStyleSheetEnabled; if (deveditionThemeEnabled && !wasEnabled) { // The stylesheet may not have been created yet if it wasn't @@ -122,7 +122,7 @@ var DevEdition = { } }, - uninit() { + uninit: function() { Services.prefs.removeObserver(this._devtoolsThemePrefName, this); Services.obs.removeObserver(this, "lightweight-theme-styling-update", false); Services.obs.removeObserver(this, "lightweight-theme-window-updated", false); diff --git a/browser/base/content/browser-fullScreenAndPointerLock.js b/browser/base/content/browser-fullScreenAndPointerLock.js index 4e8539056735..678500e7ab32 100644 --- a/browser/base/content/browser-fullScreenAndPointerLock.js +++ b/browser/base/content/browser-fullScreenAndPointerLock.js @@ -8,19 +8,19 @@ var PointerlockFsWarning = { _element: null, _origin: null, - init() { + init: function() { this.Timeout.prototype = { - start() { + start: function() { this.cancel(); this._id = setTimeout(() => this._handle(), this._delay); }, - cancel() { + cancel: function() { if (this._id) { clearTimeout(this._id); this._id = 0; } }, - _handle() { + _handle: function() { this._id = 0; this._func(); }, @@ -30,13 +30,6 @@ var PointerlockFsWarning = { }; }, - /* eslint-disable object-shorthand */ - /* The object-shorthand rule must be disabled for this constructor - * because the ES6 method syntax causes "this.Timeout is not a - * constructor" exception. Further, using the {ignoreConstructors: true} - * option causes "TypeError: Cannot read property 'charAt' of undefined" - * in eslint. - */ /** * Timeout object for managing timeout request. If it is started when * the previous call hasn't finished, it would automatically cancelled @@ -47,16 +40,15 @@ var PointerlockFsWarning = { this._func = func; this._delay = delay; }, - /* eslint-enable object-shorthand */ - showPointerLock(aOrigin) { + showPointerLock: function(aOrigin) { if (!document.fullscreen) { let timeout = gPrefService.getIntPref("pointer-lock-api.warning.timeout"); this.show(aOrigin, "pointerlock-warning", timeout, 0); } }, - showFullScreen(aOrigin) { + showFullScreen: function(aOrigin) { let timeout = gPrefService.getIntPref("full-screen-api.warning.timeout"); let delay = gPrefService.getIntPref("full-screen-api.warning.delay"); this.show(aOrigin, "fullscreen-warning", timeout, delay); @@ -64,7 +56,7 @@ var PointerlockFsWarning = { // Shows a warning that the site has entered fullscreen or // pointer lock for a short duration. - show(aOrigin, elementId, timeout, delay) { + show: function(aOrigin, elementId, timeout, delay) { if (!this._element) { this._element = document.getElementById(elementId); @@ -119,7 +111,7 @@ var PointerlockFsWarning = { this._timeoutHide.start(); }, - close() { + close: function() { if (!this._element) { return; } @@ -188,7 +180,7 @@ var PointerlockFsWarning = { } }, - handleEvent(event) { + handleEvent: function(event) { switch (event.type) { case "mousemove": { let state = this._state; @@ -234,12 +226,12 @@ var PointerlockFsWarning = { var PointerLock = { - init() { + init: function() { window.messageManager.addMessageListener("PointerLock:Entered", this); window.messageManager.addMessageListener("PointerLock:Exited", this); }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { switch (aMessage.name) { case "PointerLock:Entered": { PointerlockFsWarning.showPointerLock(aMessage.data.originNoSuffix); @@ -261,7 +253,7 @@ var FullScreen = { "DOMFullscreen:Painted", ], - init() { + init: function() { // called when we go into full screen, even if initiated by a web page script window.addEventListener("fullscreen", this, true); window.addEventListener("MozDOMFullscreen:Entered", this, @@ -278,14 +270,14 @@ var FullScreen = { this.toggle(); }, - uninit() { + uninit: function() { for (let type of this._MESSAGES) { window.messageManager.removeMessageListener(type, this); } this.cleanup(); }, - toggle() { + toggle: function() { var enterFS = window.fullScreen; // Toggle the View:FullScreen command, which controls elements like the @@ -350,11 +342,11 @@ var FullScreen = { } }, - exitDomFullScreen() { + exitDomFullScreen : function() { document.exitFullscreen(); }, - handleEvent(event) { + handleEvent: function(event) { switch (event.type) { case "fullscreen": this.toggle(); @@ -385,7 +377,7 @@ var FullScreen = { } }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { let browser = aMessage.target; switch (aMessage.name) { case "DOMFullscreen:Request": { @@ -411,7 +403,7 @@ var FullScreen = { } }, - enterDomFullscreen(aBrowser) { + enterDomFullscreen : function(aBrowser) { if (!document.fullscreenElement) { return; @@ -464,7 +456,7 @@ var FullScreen = { window.addEventListener("activate", this); }, - cleanup() { + cleanup: function() { if (!window.fullScreen) { MousePosTracker.removeListener(this); document.removeEventListener("keypress", this._keyToggleCallback, false); @@ -473,7 +465,7 @@ var FullScreen = { } }, - cleanupDomFullscreen() { + cleanupDomFullscreen: function() { window.messageManager .broadcastAsyncMessage("DOMFullscreen:CleanUp"); @@ -486,7 +478,7 @@ var FullScreen = { document.documentElement.removeAttribute("inDOMFullscreen"); }, - _isRemoteBrowser(aBrowser) { + _isRemoteBrowser: function(aBrowser) { return gMultiProcessBrowser && aBrowser.getAttribute("remote") == "true"; }, @@ -495,21 +487,21 @@ var FullScreen = { .getInterface(Ci.nsIDOMWindowUtils); }, - getMouseTargetRect() + getMouseTargetRect: function() { return this._mouseTargetRect; }, // Event callbacks - _expandCallback() + _expandCallback: function() { FullScreen.showNavToolbox(); }, - onMouseEnter() + onMouseEnter: function() { FullScreen.hideNavToolbox(); }, - _keyToggleCallback(aEvent) + _keyToggleCallback: function(aEvent) { // if we can use the keyboard (eg Ctrl+L or Ctrl+E) to open the toolbars, we // should provide a way to collapse them too. @@ -524,7 +516,7 @@ var FullScreen = { // Checks whether we are allowed to collapse the chrome _isPopupOpen: false, _isChromeCollapsed: false, - _safeToCollapse() { + _safeToCollapse: function() { if (!gPrefService.getBoolPref("browser.fullscreen.autohide")) return false; @@ -546,7 +538,7 @@ var FullScreen = { return true; }, - _setPopupOpen(aEvent) + _setPopupOpen: function(aEvent) { // Popups should only veto chrome collapsing if they were opened when the chrome was not collapsed. // Otherwise, they would not affect chrome and the user would expect the chrome to go away. @@ -564,18 +556,18 @@ var FullScreen = { }, // Autohide helpers for the context menu item - getAutohide(aItem) + getAutohide: function(aItem) { aItem.setAttribute("checked", gPrefService.getBoolPref("browser.fullscreen.autohide")); }, - setAutohide() + setAutohide: function() { gPrefService.setBoolPref("browser.fullscreen.autohide", !gPrefService.getBoolPref("browser.fullscreen.autohide")); // Try again to hide toolbar when we change the pref. FullScreen.hideNavToolbox(true); }, - showNavToolbox(trackMouse = true) { + showNavToolbox: function(trackMouse = true) { this._fullScrToggler.hidden = true; gNavToolbox.removeAttribute("fullscreenShouldAnimate"); gNavToolbox.style.marginTop = ""; @@ -599,7 +591,7 @@ var FullScreen = { this._isChromeCollapsed = false; }, - hideNavToolbox(aAnimate = false) { + hideNavToolbox: function(aAnimate = false) { if (this._isChromeCollapsed || !this._safeToCollapse()) return; @@ -623,7 +615,7 @@ var FullScreen = { MousePosTracker.removeListener(this); }, - _updateToolbars(aEnterFS) { + _updateToolbars: function(aEnterFS) { for (let el of document.querySelectorAll("toolbar[fullscreentoolbar=true]")) { if (aEnterFS) { // Give the main nav bar and the tab bar the fullscreen context menu, diff --git a/browser/base/content/browser-fullZoom.js b/browser/base/content/browser-fullZoom.js index 6f3f0271b08e..2e963cfa6f9d 100644 --- a/browser/base/content/browser-fullZoom.js +++ b/browser/base/content/browser-fullZoom.js @@ -89,7 +89,7 @@ var FullZoom = { // nsIObserver - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { switch (aTopic) { case "nsPref:changed": switch (aData) { @@ -154,7 +154,7 @@ var FullZoom = { let hasPref = false; let token = this._getBrowserToken(browser); this._cps2.getByDomainAndName(browser.currentURI.spec, this.name, ctxt, { - handleResult() { hasPref = true; }, + handleResult: function() { hasPref = true; }, handleCompletion: function() { if (!hasPref && token.isCurrent) this._applyPrefToZoom(undefined, browser); @@ -223,7 +223,7 @@ var FullZoom = { let value = undefined; let token = this._getBrowserToken(browser); this._cps2.getByDomainAndName(aURI.spec, this.name, ctxt, { - handleResult(resultPref) { value = resultPref.value; }, + handleResult: function(resultPref) { value = resultPref.value; }, handleCompletion: function() { if (!token.isCurrent) { this._notifyOnLocationChange(browser); @@ -269,7 +269,7 @@ var FullZoom = { * Sets the zoom level for the given browser to the given floating * point value, where 1 is the default zoom level. */ - setZoom(value, browser = gBrowser.selectedBrowser) { + setZoom: function(value, browser = gBrowser.selectedBrowser) { ZoomManager.setZoomForBrowser(browser, value); this._ignorePendingZoomAccesses(browser); this._applyZoomToPref(browser); @@ -487,7 +487,7 @@ var FullZoom = { } let value = undefined; this._cps2.getGlobal(this.name, this._loadContextFromBrowser(browser), { - handleResult(pref) { value = pref.value; }, + handleResult: function(pref) { value = pref.value; }, handleCompletion: (reason) => { this._globalValue = this._ensureValid(value); resolve(this._globalValue); diff --git a/browser/base/content/browser-fxaccounts.js b/browser/base/content/browser-fxaccounts.js index 951f35b9cbd0..d841dc142e7c 100644 --- a/browser/base/content/browser-fxaccounts.js +++ b/browser/base/content/browser-fxaccounts.js @@ -88,7 +88,7 @@ var gFxAccounts = { .sort((a, b) => a.name.localeCompare(b.name)); }, - init() { + init: function() { // Bail out if we're already initialized and for pop-up windows. if (this._initialized || !window.toolbar.visible) { return; @@ -107,7 +107,7 @@ var gFxAccounts = { this.updateUI(); }, - uninit() { + uninit: function() { if (!this._initialized) { return; } @@ -119,7 +119,7 @@ var gFxAccounts = { this._initialized = false; }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case "fxa-migration:state-changed": this.onMigrationStateChanged(data, subject); @@ -133,7 +133,7 @@ var gFxAccounts = { } }, - onMigrationStateChanged() { + onMigrationStateChanged: function() { // Since we nuked most of the migration code, this notification will fire // once after legacy Sync has been disconnected (and should never fire // again) @@ -175,12 +175,12 @@ var gFxAccounts = { this.updateAppMenuItem(); }, - handleEvent(event) { + handleEvent: function(event) { this._inCustomizationMode = event.type == "customizationstarting"; this.updateAppMenuItem(); }, - updateUI() { + updateUI: function() { // It's possible someone signed in to FxA after seeing our notification // about "Legacy Sync migration" (which now is actually "Legacy Sync // auto-disconnect") so kill that notification if it still exists. @@ -194,7 +194,7 @@ var gFxAccounts = { }, // Note that updateAppMenuItem() returns a Promise that's only used by tests. - updateAppMenuItem() { + updateAppMenuItem: function() { let profileInfoEnabled = false; try { profileInfoEnabled = Services.prefs.getBoolPref("identity.fxaccounts.profile_image.enabled"); @@ -320,7 +320,7 @@ var gFxAccounts = { }); }, - onMenuPanelCommand() { + onMenuPanelCommand: function() { switch (this.panelUIFooter.getAttribute("fxastatus")) { case "signedin": @@ -341,11 +341,11 @@ var gFxAccounts = { PanelUI.hide(); }, - openPreferences() { + openPreferences: function() { openPreferences("paneSync", { urlParams: { entrypoint: "menupanel" } }); }, - openAccountsPage(action, urlParams = {}) { + openAccountsPage: function(action, urlParams = {}) { let params = new URLSearchParams(); if (action) { params.set("action", action); @@ -361,15 +361,15 @@ var gFxAccounts = { }); }, - openSignInAgainPage(entryPoint) { + openSignInAgainPage: function(entryPoint) { this.openAccountsPage("reauth", { entrypoint: entryPoint }); }, - sendTabToDevice(url, clientId, title) { + sendTabToDevice: function(url, clientId, title) { Weave.Service.clientsEngine.sendURIToClientForDisplay(url, clientId, title); }, - populateSendTabToDevicesMenu(devicesPopup, url, title) { + populateSendTabToDevicesMenu: function(devicesPopup, url, title) { // remove existing menu items while (devicesPopup.hasChildNodes()) { devicesPopup.removeChild(devicesPopup.firstChild); @@ -410,7 +410,7 @@ var gFxAccounts = { devicesPopup.appendChild(fragment); }, - updateTabContextMenu(aPopupMenu) { + updateTabContextMenu: function(aPopupMenu) { if (!this.sendTabToDeviceEnabled) { return; } @@ -420,7 +420,7 @@ var gFxAccounts = { .forEach(id => { document.getElementById(id).hidden = !remoteClientPresent }); }, - initPageContextMenu(contextMenu) { + initPageContextMenu: function(contextMenu) { if (!this.sendTabToDeviceEnabled) { return; } diff --git a/browser/base/content/browser-gestureSupport.js b/browser/base/content/browser-gestureSupport.js index c281ebf54e19..7c60a05675b0 100644 --- a/browser/base/content/browser-gestureSupport.js +++ b/browser/base/content/browser-gestureSupport.js @@ -351,7 +351,7 @@ var gGestureSupport = { * @param aEvent * The continual motion update event to handle */ - _doUpdate(aEvent) {}, + _doUpdate: function(aEvent) {}, /** * Handle gesture end events. This function will be set by _setupSwipe. @@ -359,7 +359,7 @@ var gGestureSupport = { * @param aEvent * The gesture end event to handle */ - _doEnd(aEvent) {}, + _doEnd: function(aEvent) {}, /** * Convert the swipe gesture into a browser action based on the direction. @@ -444,7 +444,7 @@ var gGestureSupport = { * @param aEvent * The MozRotateGestureUpdate event triggering this call */ - rotate(aEvent) { + rotate: function(aEvent) { if (!(content.document instanceof ImageDocument)) return; @@ -463,7 +463,7 @@ var gGestureSupport = { /** * Perform a rotation end for ImageDocuments */ - rotateEnd() { + rotateEnd: function() { if (!(content.document instanceof ImageDocument)) return; @@ -531,7 +531,7 @@ var gGestureSupport = { * When the location/tab changes, need to reload the current rotation for the * image */ - restoreRotationState() { + restoreRotationState: function() { // Bug 863514 - Make gesture support work in electrolysis if (gMultiProcessBrowser) return; @@ -560,7 +560,7 @@ var gGestureSupport = { /** * Removes the transition rule by removing the completeRotation class */ - _clearCompleteRotation() { + _clearCompleteRotation: function() { let contentElement = content.document && content.document instanceof ImageDocument && content.document.body && @@ -731,7 +731,7 @@ var gHistorySwipeAnimation = { } }, - _getCurrentHistoryIndex() { + _getCurrentHistoryIndex: function() { return SessionStore.getSessionHistory(gBrowser.selectedTab).index; }, diff --git a/browser/base/content/browser-media.js b/browser/base/content/browser-media.js index 9e0498b9259c..7d10635df286 100644 --- a/browser/base/content/browser-media.js +++ b/browser/base/content/browser-media.js @@ -12,7 +12,7 @@ var gEMEHandler = { } return emeUIEnabled; }, - ensureEMEEnabled(browser, keySystem) { + ensureEMEEnabled: function(browser, keySystem) { Services.prefs.setBoolPref("media.eme.enabled", true); if (keySystem) { if (keySystem.startsWith("com.adobe") && @@ -27,7 +27,7 @@ var gEMEHandler = { } browser.reload(); }, - isKeySystemVisible(keySystem) { + isKeySystemVisible: function(keySystem) { if (!keySystem) { return false; } @@ -41,13 +41,13 @@ var gEMEHandler = { } return true; }, - getLearnMoreLink(msgId) { + getLearnMoreLink: function(msgId) { let text = gNavigatorBundle.getString("emeNotifications." + msgId + ".learnMoreLabel"); let baseURL = Services.urlFormatter.formatURLPref("app.support.baseURL"); return ""; }, - receiveMessage({target: browser, data: data}) { + receiveMessage: function({target: browser, data: data}) { let parsedData; try { parsedData = JSON.parse(data); @@ -102,7 +102,7 @@ var gEMEHandler = { this.showNotificationBar(browser, notificationId, keySystem, params, buttonCallback); }, - showNotificationBar(browser, notificationId, keySystem, labelParams, callback) { + showNotificationBar: function(browser, notificationId, keySystem, labelParams, callback) { let box = gBrowser.getNotificationBox(browser); if (box.getNotificationWithValue(notificationId)) { return; @@ -122,7 +122,7 @@ var gEMEHandler = { buttons.push({ label: gNavigatorBundle.getString(btnLabelId), accessKey: gNavigatorBundle.getString(btnAccessKeyId), - callback + callback: callback }); } @@ -139,7 +139,7 @@ var gEMEHandler = { box.appendNotification(fragment, notificationId, iconURL, box.PRIORITY_WARNING_MEDIUM, buttons); }, - showPopupNotificationForSuccess(browser, keySystem) { + showPopupNotificationForSuccess: function(browser, keySystem) { // We're playing EME content! Remove any "we can't play because..." messages. var box = gBrowser.getNotificationBox(browser); ["drmContentDisabled", @@ -174,7 +174,7 @@ var gEMEHandler = { let mainAction = { label: gNavigatorBundle.getString(btnLabelId), accessKey: gNavigatorBundle.getString(btnAccessKeyId), - callback() { openPreferences("paneContent"); }, + callback: function() { openPreferences("paneContent"); }, dismiss: true }; let options = { diff --git a/browser/base/content/browser-places.js b/browser/base/content/browser-places.js index 960065dd0192..08e326b7e0fe 100644 --- a/browser/base/content/browser-places.js +++ b/browser/base/content/browser-places.js @@ -9,7 +9,7 @@ var StarUI = { _isNewBookmark: false, _autoCloseTimer: 0, - _element(aID) { + _element: function(aID) { return document.getElementById(aID); }, @@ -633,10 +633,10 @@ var PlacesCommandHook = { PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "livemark" - , feedURI + , feedURI: feedURI , siteURI: gBrowser.currentURI - , title - , description + , title: title + , description: description , defaultInsertionPoint: toolbarIP , hiddenRows: [ "feedLocation" , "siteLocation" @@ -1143,7 +1143,7 @@ var PlacesToolbarHelper = { return !area || CustomizableUI.TYPE_MENU_PANEL == areaType; }, - onPlaceholderCommand() { + onPlaceholderCommand: function() { let widgetGroup = CustomizableUI.getWidget("personal-bookmarks"); let widget = widgetGroup.forWindow(window); if (widget.overflowed || @@ -1152,7 +1152,7 @@ var PlacesToolbarHelper = { } }, - _getParentToolbar(element) { + _getParentToolbar: function(element) { while (element) { if (element.localName == "toolbar") { return element; @@ -1162,7 +1162,7 @@ var PlacesToolbarHelper = { return null; }, - onWidgetUnderflow(aNode, aContainer) { + onWidgetUnderflow: function(aNode, aContainer) { // The view gets broken by being removed and reinserted by the overflowable // toolbar, so we have to force an uninit and reinit. let win = aNode.ownerGlobal; @@ -1171,7 +1171,7 @@ var PlacesToolbarHelper = { } }, - onWidgetAdded(aWidgetId, aArea, aPosition) { + onWidgetAdded: function(aWidgetId, aArea, aPosition) { if (aWidgetId == "personal-bookmarks" && !this._isCustomizing) { // It's possible (with the "Add to Menu", "Add to Toolbar" context // options) that the Places Toolbar Items have been moved without @@ -1182,7 +1182,7 @@ var PlacesToolbarHelper = { } }, - _resetView() { + _resetView: function() { if (this._viewElt) { // It's possible that the placesView might not exist, and we need to // do a full init. This could happen if the Bookmarks Toolbar Items are @@ -1274,7 +1274,7 @@ var BookmarkingUI = { this._getFormattedTooltip("starButtonOff.tooltip2"); }, - _getFormattedTooltip(strId) { + _getFormattedTooltip: function(strId) { let args = []; let shortcut = document.getElementById(this.BOOKMARK_BUTTON_SHORTCUT); if (shortcut) @@ -1287,7 +1287,7 @@ var BookmarkingUI = { * When in the panel, we don't update the button's icon. */ _currentAreaType: null, - _shouldUpdateStarState() { + _shouldUpdateStarState: function() { return this._currentAreaType == CustomizableUI.TYPE_TOOLBAR; }, @@ -1349,7 +1349,7 @@ var BookmarkingUI = { } }, - attachPlacesView(event, node) { + attachPlacesView: function(event, node) { // If the view is already there, bail out early. if (node.parentNode._placesView) return; @@ -1577,7 +1577,7 @@ var BookmarkingUI = { } }, - init() { + init: function() { CustomizableUI.addListener(this); this._updateCustomizationState(); }, @@ -1757,7 +1757,7 @@ var BookmarkingUI = { }, 1000); }, - _showSubview() { + _showSubview: function() { let view = document.getElementById("PanelUI-bookmarks"); view.addEventListener("ViewShowing", this); view.addEventListener("ViewHiding", this); @@ -1902,11 +1902,11 @@ var BookmarkingUI = { } }, - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onBeforeItemRemoved() {}, - onItemVisited() {}, - onItemMoved() {}, + onBeginUpdateBatch: function() {}, + onEndUpdateBatch: function() {}, + onBeforeItemRemoved: function() {}, + onItemVisited: function() {}, + onItemMoved: function() {}, // CustomizableUI events: _starButtonLabel: null, @@ -1920,7 +1920,7 @@ var BookmarkingUI = { return this._starButtonOverflowedStarredLabel = gNavigatorBundle.getString("starButtonOverflowedStarred.label"); }, - onWidgetOverflow(aNode, aContainer) { + onWidgetOverflow: function(aNode, aContainer) { let win = aNode.ownerGlobal; if (aNode.id != this.BOOKMARK_BUTTON_ID || win != window) return; @@ -1936,7 +1936,7 @@ var BookmarkingUI = { } }, - onWidgetUnderflow(aNode, aContainer) { + onWidgetUnderflow: function(aNode, aContainer) { let win = aNode.ownerGlobal; if (aNode.id != this.BOOKMARK_BUTTON_ID || win != window) return; diff --git a/browser/base/content/browser-plugins.js b/browser/base/content/browser-plugins.js index ddfe7ff7a519..fb68d262c65e 100644 --- a/browser/base/content/browser-plugins.js +++ b/browser/base/content/browser-plugins.js @@ -17,7 +17,7 @@ var gPluginHandler = { "PluginContent:LinkClickCallback", ], - init() { + init: function() { const mm = window.messageManager; for (let msg of this.MESSAGES) { mm.addMessageListener(msg, this); @@ -25,7 +25,7 @@ var gPluginHandler = { window.addEventListener("unload", this); }, - uninit() { + uninit: function() { const mm = window.messageManager; for (let msg of this.MESSAGES) { mm.removeMessageListener(msg, this); @@ -33,13 +33,13 @@ var gPluginHandler = { window.removeEventListener("unload", this); }, - handleEvent(event) { + handleEvent: function(event) { if (event.type == "unload") { this.uninit(); } }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "PluginContent:ShowClickToPlayNotification": this.showClickToPlayNotification(msg.target, msg.data.plugins, msg.data.showNow, @@ -83,13 +83,13 @@ var gPluginHandler = { }, // Callback for user clicking on a disabled plugin - managePlugins() { + managePlugins: function() { BrowserOpenAddonsMgr("addons://list/plugin"); }, // Callback for user clicking on the link in a click-to-play plugin // (where the plugin has an update) - openPluginUpdatePage(pluginTag) { + openPluginUpdatePage: function(pluginTag) { let url = Services.blocklist.getPluginInfoURL(pluginTag); if (!url) { url = Services.blocklist.getPluginBlocklistURL(pluginTag); @@ -106,12 +106,12 @@ var gPluginHandler = { }, // Callback for user clicking a "reload page" link - reloadPage(browser) { + reloadPage: function(browser) { browser.reload(); }, // Callback for user clicking the help icon - openHelpPage() { + openHelpPage: function() { openHelpLink("plugin-crashed", false); }, @@ -139,7 +139,7 @@ var gPluginHandler = { * and activate plugins if necessary. * aNewState should be either "allownow" "allowalways" or "block" */ - _updatePluginPermission(aNotification, aPluginInfo, aNewState) { + _updatePluginPermission: function(aNotification, aPluginInfo, aNewState) { let permission; let expireType; let expireTime; @@ -208,7 +208,7 @@ var gPluginHandler = { }); }, - showClickToPlayNotification(browser, plugins, showNow, + showClickToPlayNotification: function(browser, plugins, showNow, principal, location) { // It is possible that we've received a message from the frame script to show // a click to play notification for a principal that no longer matches the one @@ -281,8 +281,8 @@ var gPluginHandler = { persistent: showNow, eventCallback: this._clickToPlayNotificationEventCallback, primaryPlugin: primaryPluginPermission, - pluginData, - principal, + pluginData: pluginData, + principal: principal, }; PopupNotifications.show(browser, "click-to-play-plugins", "", "plugins-notification-icon", @@ -290,20 +290,20 @@ var gPluginHandler = { browser.messageManager.sendAsyncMessage("BrowserPlugins:NotificationShown"); }, - removeNotification(browser, name) { + removeNotification: function(browser, name) { let notification = PopupNotifications.getNotification(name, browser); if (notification) PopupNotifications.remove(notification); }, - hideNotificationBar(browser, name) { + hideNotificationBar: function(browser, name) { let notificationBox = gBrowser.getNotificationBox(browser); let notification = notificationBox.getNotificationWithValue(name); if (notification) notificationBox.removeNotification(notification, true); }, - updateHiddenPluginUI(browser, haveInsecure, actions, + updateHiddenPluginUI: function(browser, haveInsecure, actions, principal, location) { let origin = principal.originNoSuffix; @@ -391,7 +391,7 @@ var gPluginHandler = { { label: gNavigatorBundle.getString("pluginContinueBlocking.label"), accessKey: gNavigatorBundle.getString("pluginContinueBlocking.accesskey"), - callback() { + callback: function() { Services.telemetry.getHistogramById("PLUGINS_INFOBAR_BLOCK"). add(true); @@ -403,7 +403,7 @@ var gPluginHandler = { { label: gNavigatorBundle.getString("pluginActivateTrigger.label"), accessKey: gNavigatorBundle.getString("pluginActivateTrigger.accesskey"), - callback() { + callback: function() { Services.telemetry.getHistogramById("PLUGINS_INFOBAR_ALLOW"). add(true); @@ -437,14 +437,14 @@ var gPluginHandler = { } }, - contextMenuCommand(browser, plugin, command) { + contextMenuCommand: function(browser, plugin, command) { browser.messageManager.sendAsyncMessage("BrowserPlugins:ContextMenuCommand", - { command }, { plugin }); + { command: command }, { plugin: plugin }); }, // Crashed-plugin observer. Notified once per plugin crash, before events // are dispatched to individual plugin instances. - NPAPIPluginCrashed(subject, topic, data) { + NPAPIPluginCrashed : function(subject, topic, data) { let propertyBag = subject; if (!(propertyBag instanceof Ci.nsIPropertyBag2) || !(propertyBag instanceof Ci.nsIWritablePropertyBag2) || @@ -493,7 +493,7 @@ var gPluginHandler = { * For a GMP, this is the pluginID. For NPAPI plugins (where "pluginID" * means something different), this is the runID. */ - showPluginCrashedNotification(browser, messageString, pluginID) { + showPluginCrashedNotification: function(browser, messageString, pluginID) { // If there's already an existing notification bar, don't do anything. let notificationBox = gBrowser.getNotificationBox(browser); let notification = notificationBox.getNotificationWithValue("plugin-crashed"); @@ -511,7 +511,7 @@ var gPluginHandler = { label: reloadLabel, accessKey: reloadKey, popup: null, - callback() { browser.reload(); }, + callback: function() { browser.reload(); }, }]; if (AppConstants.MOZ_CRASHREPORTER && diff --git a/browser/base/content/browser-refreshblocker.js b/browser/base/content/browser-refreshblocker.js index 2c6f2da97930..50ea992c4006 100644 --- a/browser/base/content/browser-refreshblocker.js +++ b/browser/base/content/browser-refreshblocker.js @@ -17,7 +17,7 @@ var RefreshBlocker = { gBrowser.removeEventListener("RefreshBlocked", this); }, - handleEvent(event) { + handleEvent: function(event) { if (event.type == "RefreshBlocked") { this.block(event.originalTarget, event.detail); } @@ -68,7 +68,7 @@ var RefreshBlocker = { let buttons = [{ label: refreshButtonText, accessKey: refreshButtonAccesskey, - callback() { + callback: function() { if (browser.messageManager) { browser.messageManager.sendAsyncMessage("RefreshBlocker:Refresh", data); } diff --git a/browser/base/content/browser-safebrowsing.js b/browser/base/content/browser-safebrowsing.js index b8b5976e39e4..430d84f132bd 100644 --- a/browser/base/content/browser-safebrowsing.js +++ b/browser/base/content/browser-safebrowsing.js @@ -4,7 +4,7 @@ var gSafeBrowsing = { - setReportPhishingMenu() { + setReportPhishingMenu: function() { // In order to detect whether or not we're at the phishing warning // page, we have to check the documentURI instead of the currentURI. // This is because when the DocShell loads an error page, the @@ -42,7 +42,7 @@ var gSafeBrowsing = { * @param name String One of "Phish", "Error", "Malware" or "MalwareError" * @return String the report phishing URL. */ - getReportURL(name) { + getReportURL: function(name) { return SafeBrowsing.getReportURL(name, gBrowser.currentURI); } } diff --git a/browser/base/content/browser-sidebar.js b/browser/base/content/browser-sidebar.js index 76128ecd8b2b..5893e6015bb9 100644 --- a/browser/base/content/browser-sidebar.js +++ b/browser/base/content/browser-sidebar.js @@ -258,7 +258,7 @@ var SidebarUI = { let selBrowser = gBrowser.selectedBrowser; selBrowser.messageManager.sendAsyncMessage("Sidebar:VisibilityChange", - {commandID, isOpen: true} + {commandID: commandID, isOpen: true} ); BrowserUITelemetry.countSidebarEvent(commandID, "show"); }); @@ -296,7 +296,7 @@ var SidebarUI = { let selBrowser = gBrowser.selectedBrowser; selBrowser.focus(); selBrowser.messageManager.sendAsyncMessage("Sidebar:VisibilityChange", - {commandID, isOpen: false} + {commandID: commandID, isOpen: false} ); BrowserUITelemetry.countSidebarEvent(commandID, "hide"); }, diff --git a/browser/base/content/browser-syncui.js b/browser/base/content/browser-syncui.js index 6d219570f840..299b1743d065 100644 --- a/browser/base/content/browser-syncui.js +++ b/browser/base/content/browser-syncui.js @@ -39,7 +39,7 @@ var gSyncUI = { _syncStartTime: 0, _syncAnimationTimer: 0, - init() { + init: function() { Cu.import("resource://services-common/stringbundle.js"); // Proceed to set up the UI if Sync has already started up. @@ -137,7 +137,7 @@ var gSyncUI = { // Note that we don't show login errors in a notification bar here, but do // still need to track a login-failed state so the "Tools" menu updates // with the correct state. - _loginFailed() { + _loginFailed: function() { // If Sync isn't already ready, we don't want to force it to initialize // by referencing Weave.Status - and it isn't going to be accurate before // Sync is ready anyway. @@ -242,7 +242,7 @@ var gSyncUI = { this.updateUI(); }, - _getAppName() { + _getAppName: function() { let brand = new StringBundle("chrome://branding/locale/brand.properties"); return brand.get("brandShortName"); }, @@ -304,7 +304,7 @@ var gSyncUI = { }, // Open the legacy-sync device pairing UI. Note used for FxA Sync. - openAddDevice() { + openAddDevice: function() { if (!Weave.Utils.ensureMPUnlocked()) return; @@ -316,11 +316,11 @@ var gSyncUI = { "syncAddDevice", "centerscreen,chrome,resizable=no"); }, - openPrefs(entryPoint) { + openPrefs: function(entryPoint) { openPreferences("paneSync", { urlParams: { entrypoint: entryPoint } }); }, - openSignInAgainPage(entryPoint = "syncbutton") { + openSignInAgainPage: function(entryPoint = "syncbutton") { gFxAccounts.openSignInAgainPage(entryPoint); }, @@ -423,7 +423,7 @@ var gSyncUI = { } }), - formatLastSyncDate(date) { + formatLastSyncDate: function(date) { let dateFormat; let sixDaysAgo = (() => { let tempDate = new Date(); @@ -441,7 +441,7 @@ var gSyncUI = { return this._stringBundle.formatStringFromName("lastSync2.label", [lastSyncDateString], 1); }, - onClientsSynced() { + onClientsSynced: function() { let broadcaster = document.getElementById("sync-syncnow-state"); if (broadcaster) { if (Weave.Service.clientsEngine.stats.numClients > 1) { diff --git a/browser/base/content/browser-tabsintitlebar-stub.js b/browser/base/content/browser-tabsintitlebar-stub.js index 41325ec1bb32..f6b91506b8a1 100644 --- a/browser/base/content/browser-tabsintitlebar-stub.js +++ b/browser/base/content/browser-tabsintitlebar-stub.js @@ -7,9 +7,9 @@ // don't have CAN_DRAW_IN_TITLEBAR defined. var TabsInTitlebar = { - init() {}, - uninit() {}, - allowedBy(condition, allow) {}, + init: function() {}, + uninit: function() {}, + allowedBy: function(condition, allow) {}, updateAppearance: function updateAppearance(aForce) {}, get enabled() { return document.documentElement.getAttribute("tabsintitlebar") == "true"; diff --git a/browser/base/content/browser-tabsintitlebar.js b/browser/base/content/browser-tabsintitlebar.js index 1a8065179597..ab882c8948c9 100644 --- a/browser/base/content/browser-tabsintitlebar.js +++ b/browser/base/content/browser-tabsintitlebar.js @@ -7,7 +7,7 @@ // this one on platforms which don't have CAN_DRAW_IN_TITLEBAR defined. var TabsInTitlebar = { - init() { + init: function() { if (this._initialized) { return; } @@ -49,7 +49,7 @@ var TabsInTitlebar = { } }, - allowedBy(condition, allow) { + allowedBy: function(condition, allow) { if (allow) { if (condition in this._disallowed) { delete this._disallowed[condition]; @@ -69,18 +69,18 @@ var TabsInTitlebar = { return document.documentElement.getAttribute("tabsintitlebar") == "true"; }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { if (topic == "nsPref:changed") this._readPref(); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { if (aEvent.type == "resolutionchange" && aEvent.target == window) { this._update(true); } }, - _onMenuMutate(aMutations) { + _onMenuMutate: function(aMutations) { for (let mutation of aMutations) { if (mutation.attributeName == "inactive" || mutation.attributeName == "autohide") { @@ -96,12 +96,12 @@ var TabsInTitlebar = { _prefName: "browser.tabs.drawInTitlebar", _lastSizeMode: null, - _readPref() { + _readPref: function() { this.allowedBy("pref", Services.prefs.getBoolPref(this._prefName)); }, - _update(aForce = false) { + _update: function(aForce = false) { let $ = id => document.getElementById(id); let rect = ele => ele.getBoundingClientRect(); let verticalMargins = cstyle => parseFloat(cstyle.marginBottom) + parseFloat(cstyle.marginTop); @@ -253,12 +253,12 @@ var TabsInTitlebar = { } }, - _sizePlaceholder(type, width) { + _sizePlaceholder: function(type, width) { Array.forEach(document.querySelectorAll(".titlebar-placeholder[type='" + type + "']"), function(node) { node.width = width; }); }, - uninit() { + uninit: function() { this._initialized = false; removeEventListener("resolutionchange", this); Services.prefs.removeObserver(this._prefName, this); diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index 3d2eb02ac1d2..045a48f7af68 100755 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -170,10 +170,10 @@ XPCOMUtils.defineLazyGetter(this, "Win7Features", function() { Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available) { let AeroPeek = Cu.import("resource:///modules/WindowsPreviewPerTab.jsm", {}).AeroPeek; return { - onOpenWindow() { + onOpenWindow: function() { AeroPeek.onOpenWindow(window); }, - onCloseWindow() { + onCloseWindow: function() { AeroPeek.onCloseWindow(window); } }; @@ -408,7 +408,7 @@ const gClickAndHoldListenersOnElement = { }; const gSessionHistoryObserver = { - observe(subject, topic, data) + observe: function(subject, topic, data) { if (topic != "browser:purge-session-history") return; @@ -459,7 +459,7 @@ function findChildShell(aDocument, aDocShell, aSoughtURI) { var gPopupBlockerObserver = { _reportButton: null, - onReportButtonMousedown(aEvent) + onReportButtonMousedown: function(aEvent) { // If this method is called on the same event tick as the popup gets // hidden, do nothing to avoid re-opening the popup. @@ -470,7 +470,7 @@ var gPopupBlockerObserver = { .openPopup(this._reportButton, "after_end", 0, 2, false, false, aEvent); }, - handleEvent(aEvent) + handleEvent: function(aEvent) { if (aEvent.originalTarget != gBrowser.selectedBrowser) return; @@ -541,7 +541,7 @@ var gPopupBlockerObserver = { } }, - toggleAllowPopupsForSite(aEvent) + toggleAllowPopupsForSite: function(aEvent) { var pm = Services.perms; var shouldBlock = aEvent.target.getAttribute("block") == "true"; @@ -554,7 +554,7 @@ var gPopupBlockerObserver = { gBrowser.getNotificationBox().removeCurrentNotification(); }, - fillPopupList(aEvent) + fillPopupList: function(aEvent) { // XXXben - rather than using |currentURI| here, which breaks down on multi-framed sites // we should really walk the blockedPopups and create a list of "allow for " @@ -657,7 +657,7 @@ var gPopupBlockerObserver = { }, null); }, - onPopupHiding(aEvent) { + onPopupHiding: function(aEvent) { if (aEvent.target.anchorNode.id == "page-report-button") aEvent.target.anchorNode.removeAttribute("open"); @@ -672,7 +672,7 @@ var gPopupBlockerObserver = { } }, - showBlockedPopup(aEvent) + showBlockedPopup: function(aEvent) { var target = aEvent.target; var popupReportIndex = target.getAttribute("popupReportIndex"); @@ -680,7 +680,7 @@ var gPopupBlockerObserver = { browser.unblockPopup(popupReportIndex); }, - showAllBlockedPopups(aBrowser) + showAllBlockedPopups: function(aBrowser) { aBrowser.retrieveListOfBlockedPopups().then(popups => { for (let i = 0; i < popups.length; i++) { @@ -690,7 +690,7 @@ var gPopupBlockerObserver = { }, null); }, - editPopupSettings() + editPopupSettings: function() { let prefillValue = ""; try { @@ -729,7 +729,7 @@ var gPopupBlockerObserver = { "_blank", "resizable,dialog=no,centerscreen", params); }, - dontShowMessage() + dontShowMessage: function() { var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage"); gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage); @@ -824,7 +824,7 @@ function gKeywordURIFixup({ target: browser, data: fixupInfo }) { { label: yesMessage, accessKey: gNavigatorBundle.getString("keywordURIFixup.goTo.accesskey"), - callback() { + callback: function() { // Do not set this preference while in private browsing. if (!PrivateBrowsingUtils.isWindowPrivate(window)) { let pref = "browser.fixup.domainwhitelist." + asciiHost; @@ -836,7 +836,7 @@ function gKeywordURIFixup({ target: browser, data: fixupInfo }) { { label: gNavigatorBundle.getString("keywordURIFixup.dismiss"), accessKey: gNavigatorBundle.getString("keywordURIFixup.dismiss.accesskey"), - callback() { + callback: function() { let notification = notificationBox.getNotificationWithValue("keyword-uri-fixup"); notificationBox.removeNotification(notification, true); } @@ -896,11 +896,11 @@ function _loadURIWithFlags(browser, uri, params) { } let loadParams = { - uri, - flags, + uri: uri, + flags: flags, referrer: referrer ? referrer.spec : null, - referrerPolicy, - postData + referrerPolicy: referrerPolicy, + postData: postData } if (params.userContextId) { @@ -1001,7 +1001,7 @@ addEventListener("DOMContentLoaded", function onDCL() { var gBrowserInit = { delayedStartupFinished: false, - onLoad() { + onLoad: function() { gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver, false); Services.obs.addObserver(gPluginHandler.NPAPIPluginCrashed, "plugin-crashed", false); @@ -1104,12 +1104,12 @@ var gBrowserInit = { this._loadHandled = true; }, - _cancelDelayedStartup() { + _cancelDelayedStartup: function() { window.removeEventListener("MozAfterPaint", this._boundDelayedStartup); this._boundDelayedStartup = null; }, - _delayedStartup() { + _delayedStartup: function() { let tmp = {}; Cu.import("resource://gre/modules/TelemetryTimestamps.jsm", tmp); let TelemetryTimestamps = tmp.TelemetryTimestamps; @@ -1470,7 +1470,7 @@ var gBrowserInit = { }, // Returns the URI(s) to load at startup. - _getUriToLoad() { + _getUriToLoad: function() { // window.arguments[0]: URI to load (string), or an nsIArray of // nsISupportsStrings to load, or a xul:tab of // a tabbrowser, which will be replaced by this @@ -1494,7 +1494,7 @@ var gBrowserInit = { return uri; }, - onUnload() { + onUnload: function() { // In certain scenarios it's possible for unload to be fired before onload, // (e.g. if the window is being closed after browser.js loads but before the // load completes). In that case, there's nothing to do here. @@ -2054,7 +2054,7 @@ var gLastOpenDirectory = { gPrefService.setComplexValue("browser.open.lastDir", Ci.nsILocalFile, this._lastDir); }, - reset() { + reset: function() { this._lastDir = null; } }; @@ -2111,10 +2111,10 @@ function loadURI(uri, referrer, postData, allowThirdPartyFixup, referrerPolicy, try { openLinkIn(uri, "current", { referrerURI: referrer, - referrerPolicy, - postData, - allowThirdPartyFixup, - userContextId, + referrerPolicy: referrerPolicy, + postData: postData, + allowThirdPartyFixup: allowThirdPartyFixup, + userContextId: userContextId, originPrincipal, forceAboutBlankViewerInCurrent, }); @@ -2367,7 +2367,7 @@ function BrowserViewSourceOfDocument(aArgsOrDocument) { */ function BrowserViewSource(browser) { BrowserViewSourceOfDocument({ - browser, + browser: browser, outerWindowID: browser.outerWindowID, URL: browser.currentURI.spec, }); @@ -2616,21 +2616,21 @@ var gMenuButtonBadgeManager = { downloadBadge: null, appUpdateBadge: null, - init() { + init: function() { PanelUI.panel.addEventListener("popupshowing", this, true); }, - uninit() { + uninit: function() { PanelUI.panel.removeEventListener("popupshowing", this, true); }, - handleEvent(e) { + handleEvent: function(e) { if (e.type === "popupshowing") { this.clearBadges(); } }, - _showBadge() { + _showBadge: function() { let badgeToShow = this.downloadBadge || this.appUpdateBadge || this.fxaBadge; if (badgeToShow) { @@ -2640,7 +2640,7 @@ var gMenuButtonBadgeManager = { } }, - _changeBadge(badgeId, badgeStatus = null) { + _changeBadge: function(badgeId, badgeStatus = null) { if (badgeId == this.BADGEID_APPUPDATE) { this.appUpdateBadge = badgeStatus; } else if (badgeId == this.BADGEID_DOWNLOAD) { @@ -2653,7 +2653,7 @@ var gMenuButtonBadgeManager = { this._showBadge(); }, - addBadge(badgeId, badgeStatus) { + addBadge: function(badgeId, badgeStatus) { if (!badgeStatus) { Cu.reportError("badgeStatus must be defined"); return; @@ -2661,11 +2661,11 @@ var gMenuButtonBadgeManager = { this._changeBadge(badgeId, badgeStatus); }, - removeBadge(badgeId) { + removeBadge: function(badgeId) { this._changeBadge(badgeId); }, - clearBadges() { + clearBadges: function() { this.appUpdateBadge = null; this.downloadBadge = null; this.fxaBadge = null; @@ -2680,7 +2680,7 @@ var gMenuButtonUpdateBadge = { timer: null, cancelObserverRegistered: false, - init() { + init: function() { try { this.enabled = Services.prefs.getBoolPref("app.update.badge"); } catch (e) {} @@ -2695,7 +2695,7 @@ var gMenuButtonUpdateBadge = { } }, - uninit() { + uninit: function() { if (this.timer) this.timer.cancel(); if (this.enabled) { @@ -2709,7 +2709,7 @@ var gMenuButtonUpdateBadge = { } }, - onMenuPanelCommand(event) { + onMenuPanelCommand: function(event) { if (event.originalTarget.getAttribute("update-status") === "succeeded") { // restart the app let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"] @@ -2726,7 +2726,7 @@ var gMenuButtonUpdateBadge = { } }, - observe(subject, topic, status) { + observe: function(subject, topic, status) { if (topic == "update-canceled") { this.reset(); return; @@ -2746,7 +2746,7 @@ var gMenuButtonUpdateBadge = { // The timer callback will call uninit() when it completes. }, - notify() { + notify: function() { // If the update is successfully applied, or if the updater has fallen back // to non-staged updates, add a badge to the hamburger menu to indicate an // update will be applied once the browser restarts. @@ -2754,7 +2754,7 @@ var gMenuButtonUpdateBadge = { this.displayBadge(true); }, - displayBadge(succeeded) { + displayBadge: function(succeeded) { let status = succeeded ? "succeeded" : "failed"; let badgeStatus = "update-" + status; gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_APPUPDATE, badgeStatus); @@ -2780,7 +2780,7 @@ var gMenuButtonUpdateBadge = { updateButton.hidden = false; }, - reset() { + reset: function() { gMenuButtonBadgeManager.removeBadge( gMenuButtonBadgeManager.BADGEID_APPUPDATE); let updateButton = document.getElementById("PanelUI-update-status"); @@ -2808,7 +2808,7 @@ const PREF_SSL_IMPACT = PREF_SSL_IMPACT_ROOTS.reduce((prefs, root) => { * us via async messaging. */ var BrowserOnClick = { - init() { + init: function() { let mm = window.messageManager; mm.addMessageListener("Browser:CertExceptionError", this); mm.addMessageListener("Browser:OpenCaptivePortalPage", this); @@ -2825,7 +2825,7 @@ var BrowserOnClick = { Services.obs.addObserver(this, "captive-portal-login-success", false); }, - uninit() { + uninit: function() { let mm = window.messageManager; mm.removeMessageListener("Browser:CertExceptionError", this); mm.removeMessageListener("Browser:SiteBlockedError", this); @@ -2841,7 +2841,7 @@ var BrowserOnClick = { Services.obs.removeObserver(this, "captive-portal-login-success"); }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { switch (aTopic) { case "captive-portal-login-abort": case "captive-portal-login-success": @@ -2852,7 +2852,7 @@ var BrowserOnClick = { } }, - handleEvent(event) { + handleEvent: function(event) { if (!event.isTrusted || // Don't trust synthetic events event.button == 2) { return; @@ -2870,7 +2870,7 @@ var BrowserOnClick = { } }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "Browser:CertExceptionError": this.onCertError(msg.target, msg.data.elementId, @@ -2928,7 +2928,7 @@ var BrowserOnClick = { } }, - onSSLErrorReport(browser, uri, securityInfo) { + onSSLErrorReport: function(browser, uri, securityInfo) { if (!Services.prefs.getBoolPref("security.ssl.errorReporting.enabled")) { Cu.reportError("User requested certificate error report sending, but certificate error reporting is disabled"); return; @@ -2945,7 +2945,7 @@ var BrowserOnClick = { uri.host, uri.port); }, - onCertError(browser, elementId, isTopFrame, location, securityInfoAsString) { + onCertError: function(browser, elementId, isTopFrame, location, securityInfoAsString) { let secHistogram = Services.telemetry.getHistogramById("SECURITY_UI"); let securityInfo; @@ -2959,7 +2959,7 @@ var BrowserOnClick = { let sslStatus = securityInfo.QueryInterface(Ci.nsISSLStatusProvider) .SSLStatus; let params = { exceptionAdded : false, - sslStatus }; + sslStatus : sslStatus }; try { switch (Services.prefs.getIntPref("browser.ssl_override_behavior")) { @@ -3014,7 +3014,7 @@ var BrowserOnClick = { } }, - onOpenCaptivePortalPage() { + onOpenCaptivePortalPage: function() { // Open a new tab with the canonical URL that we use to check for a captive portal. // It will be redirected to the login page. let canonicalURL = Services.prefs.getCharPref("captivedetect.canonicalURL"); @@ -3036,7 +3036,7 @@ var BrowserOnClick = { Services.obs.addObserver(tabCloser, "captive-portal-login-success", false); }, - onAboutBlocked(elementId, reason, isTopFrame, location) { + onAboutBlocked: function(elementId, reason, isTopFrame, location) { // Depending on what page we are displaying here (malware/phishing/unwanted) // use the right strings and links for each. let bucketName = ""; @@ -3091,7 +3091,7 @@ var BrowserOnClick = { * the next page also in the parent) and instructs the browser to open the url * in the current tab which will make it update the remoteness of the tab. */ - onE10sAboutNewTab(event, ownerDoc) { + onE10sAboutNewTab: function(event, ownerDoc) { let isTopFrame = (ownerDoc.defaultView.parent === ownerDoc.defaultView); if (!isTopFrame) { return; @@ -3107,7 +3107,7 @@ var BrowserOnClick = { } }, - ignoreWarningButton(reason) { + ignoreWarningButton: function(reason) { // Allow users to override and continue through to the site, // but add a notify bar as a reminder, so that they don't lose // track after, e.g., tab switching. @@ -3122,7 +3122,7 @@ var BrowserOnClick = { let buttons = [{ label: gNavigatorBundle.getString("safebrowsing.getMeOutOfHereButton.label"), accessKey: gNavigatorBundle.getString("safebrowsing.getMeOutOfHereButton.accessKey"), - callback() { getMeOutOfHere(); } + callback: function() { getMeOutOfHere(); } }]; let title; @@ -3131,7 +3131,7 @@ var BrowserOnClick = { buttons[1] = { label: gNavigatorBundle.getString("safebrowsing.notAnAttackButton.label"), accessKey: gNavigatorBundle.getString("safebrowsing.notAnAttackButton.accessKey"), - callback() { + callback: function() { openUILinkIn(gSafeBrowsing.getReportURL('MalwareMistake'), 'tab'); } }; @@ -3140,7 +3140,7 @@ var BrowserOnClick = { buttons[1] = { label: gNavigatorBundle.getString("safebrowsing.notADeceptiveSiteButton.label"), accessKey: gNavigatorBundle.getString("safebrowsing.notADeceptiveSiteButton.accessKey"), - callback() { + callback: function() { openUILinkIn(gSafeBrowsing.getReportURL('PhishMistake'), 'tab'); } }; @@ -3374,7 +3374,7 @@ var PrintPreviewListener = { _tabBeforePrintPreview: null, _simplifyPageTab: null, - getPrintPreviewBrowser() { + getPrintPreviewBrowser: function() { if (!this._printPreviewTab) { let browser = gBrowser.selectedTab.linkedBrowser; let preferredRemoteType = browser.remoteType; @@ -3387,23 +3387,23 @@ var PrintPreviewListener = { } return gBrowser.getBrowserForTab(this._printPreviewTab); }, - createSimplifiedBrowser() { + createSimplifiedBrowser: function() { this._simplifyPageTab = gBrowser.loadOneTab("about:blank", { inBackground: true }); return this.getSimplifiedSourceBrowser(); }, - getSourceBrowser() { + getSourceBrowser: function() { return this._tabBeforePrintPreview ? this._tabBeforePrintPreview.linkedBrowser : gBrowser.selectedBrowser; }, - getSimplifiedSourceBrowser() { + getSimplifiedSourceBrowser: function() { return this._simplifyPageTab ? gBrowser.getBrowserForTab(this._simplifyPageTab) : null; }, - getNavToolbox() { + getNavToolbox: function() { return gNavToolbox; }, - onEnter() { + onEnter: function() { // We might have accidentally switched tabs since the user invoked print // preview if (gBrowser.selectedTab != this._printPreviewTab) { @@ -3412,7 +3412,7 @@ var PrintPreviewListener = { gInPrintPreviewMode = true; this._toggleAffectedChrome(); }, - onExit() { + onExit: function() { gBrowser.selectedTab = this._tabBeforePrintPreview; this._tabBeforePrintPreview = null; gInPrintPreviewMode = false; @@ -3425,7 +3425,7 @@ var PrintPreviewListener = { gBrowser.deactivatePrintPreviewBrowsers(); this._printPreviewTab = null; }, - _toggleAffectedChrome() { + _toggleAffectedChrome: function() { gNavToolbox.collapsed = gInPrintPreviewMode; if (gInPrintPreviewMode) @@ -3435,7 +3435,7 @@ var PrintPreviewListener = { TabsInTitlebar.allowedBy("print-preview", !gInPrintPreviewMode); }, - _hideChrome() { + _hideChrome: function() { this._chromeState = {}; this._chromeState.sidebarOpen = SidebarUI.isOpen; @@ -3463,7 +3463,7 @@ var PrintPreviewListener = { syncNotifications.notificationsHidden = true; } }, - _showChrome() { + _showChrome: function() { if (this._chromeState.notificationsOpen) gBrowser.getNotificationBox().notificationsHidden = false; @@ -3499,20 +3499,20 @@ function FillInHTMLTooltip(tipElement) var browserDragAndDrop = { canDropLink: aEvent => Services.droppedLinkHandler.canDropLink(aEvent, true), - dragOver(aEvent) + dragOver: function(aEvent) { if (this.canDropLink(aEvent)) { aEvent.preventDefault(); } }, - dropLinks(aEvent, aDisallowInherit) { + dropLinks: function(aEvent, aDisallowInherit) { return Services.droppedLinkHandler.dropLinks(aEvent, aDisallowInherit); } }; var homeButtonObserver = { - onDrop(aEvent) + onDrop: function(aEvent) { // disallow setting home pages that inherit the principal let links = browserDragAndDrop.dropLinks(aEvent, true); @@ -3521,7 +3521,7 @@ var homeButtonObserver = { } }, - onDragOver(aEvent) + onDragOver: function(aEvent) { if (gPrefService.prefIsLocked("browser.startup.homepage")) { return; @@ -3529,7 +3529,7 @@ var homeButtonObserver = { browserDragAndDrop.dragOver(aEvent); aEvent.dropEffect = "link"; }, - onDragExit(aEvent) + onDragExit: function(aEvent) { } } @@ -3596,14 +3596,14 @@ var newWindowButtonObserver = { } const DOMLinkHandler = { - init() { + init: function() { let mm = window.messageManager; mm.addMessageListener("Link:AddFeed", this); mm.addMessageListener("Link:SetIcon", this); mm.addMessageListener("Link:AddSearch", this); }, - receiveMessage(aMsg) { + receiveMessage: function(aMsg) { switch (aMsg.name) { case "Link:AddFeed": let link = {type: aMsg.data.type, href: aMsg.data.href, title: aMsg.data.title}; @@ -3620,7 +3620,7 @@ const DOMLinkHandler = { } }, - setIcon(aBrowser, aURL, aLoadingPrincipal) { + setIcon: function(aBrowser, aURL, aLoadingPrincipal) { if (gBrowser.isFailedIcon(aURL)) return false; @@ -3632,7 +3632,7 @@ const DOMLinkHandler = { return true; }, - addSearch(aBrowser, aEngine, aURL) { + addSearch: function(aBrowser, aEngine, aURL) { let tab = gBrowser.getTabForBrowser(aBrowser); if (!tab) return; @@ -3642,7 +3642,7 @@ const DOMLinkHandler = { } const BrowserSearch = { - addEngine(browser, engine, uri) { + addEngine: function(browser, engine, uri) { // Check to see whether we've already added an engine with this title if (browser.engines) { if (browser.engines.some(e => e.title == engine.title)) @@ -3678,7 +3678,7 @@ const BrowserSearch = { * available when a page is loaded or the user switches tabs to a page that * has search engines. */ - updateOpenSearchBadge() { + updateOpenSearchBadge: function() { var searchBar = this.searchBar; if (!searchBar) return; @@ -3770,7 +3770,7 @@ const BrowserSearch = { * @return engine The search engine used to perform a search, or null if no * search was performed. */ - _loadSearch(searchText, useNewTab, purpose) { + _loadSearch: function(searchText, useNewTab, purpose) { let engine; // If the search bar is visible, use the current engine, otherwise, fall @@ -3794,7 +3794,7 @@ const BrowserSearch = { openLinkIn(submission.uri.spec, useNewTab ? "tab" : "current", { postData: submission.postData, - inBackground, + inBackground: inBackground, relatedToCurrent: true }); return engine; @@ -3820,14 +3820,14 @@ const BrowserSearch = { * This should only be called from the context menu. See * BrowserSearch.loadSearch for the preferred API. */ - loadSearchFromContext(terms) { + loadSearchFromContext: function(terms) { let engine = BrowserSearch._loadSearch(terms, true, "contextmenu"); if (engine) { BrowserSearch.recordSearchInTelemetry(engine, "contextmenu"); } }, - pasteAndSearch(event) { + pasteAndSearch: function(event) { BrowserSearch.searchBar.select(); goDoCommand("cmd_paste"); BrowserSearch.searchBar.handleSearchCommand(event); @@ -3850,7 +3850,7 @@ const BrowserSearch = { openUILinkIn(this.searchEnginesURL, where); }, - _getSearchEngineId(engine) { + _getSearchEngineId: function(engine) { if (engine && engine.identifier) { return engine.identifier; } @@ -3879,7 +3879,7 @@ const BrowserSearch = { * indicates where the item was in the suggestion list and how the user * selected it: {selection: {index: The selected index, kind: "key" or "mouse"}} */ - recordSearchInTelemetry(engine, source, details = {}) { + recordSearchInTelemetry: function(engine, source, details = {}) { BrowserUITelemetry.countSearchEvent(source, null, details.selection); try { BrowserUsageTelemetry.recordSearch(engine, source, details); @@ -3903,7 +3903,7 @@ const BrowserSearch = { * @param where * (string) Where was the search link opened (e.g. new tab, current tab, ..). */ - recordOneoffSearchInTelemetry(engine, source, type, where) { + recordOneoffSearchInTelemetry: function(engine, source, type, where) { let id = this._getSearchEngineId(engine) + "." + source; BrowserUITelemetry.countOneoffSearchEvent(id, type, where); try { @@ -4295,7 +4295,7 @@ var XULBrowserWindow = { // Left here for add-on compatibility, see bug 752434 inContentWhitelist: [], - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (aIID.equals(Ci.nsIWebProgressListener) || aIID.equals(Ci.nsIWebProgressListener2) || aIID.equals(Ci.nsISupportsWeakReference) || @@ -4325,34 +4325,34 @@ var XULBrowserWindow = { return this.canViewSource = document.getElementById("canViewSource"); }, - init() { + init: function() { // Initialize the security button's state and tooltip text. var securityUI = gBrowser.securityUI; this.onSecurityChange(null, null, securityUI.state, true); }, - setJSStatus() { + setJSStatus: function() { // unsupported }, - forceInitialBrowserRemote(aRemoteType) { + forceInitialBrowserRemote: function(aRemoteType) { let initBrowser = document.getAnonymousElementByAttribute(gBrowser, "anonid", "initialBrowser"); gBrowser.updateBrowserRemoteness(initBrowser, true, { remoteType: aRemoteType }); }, - forceInitialBrowserNonRemote(aOpener) { + forceInitialBrowserNonRemote: function(aOpener) { let initBrowser = document.getAnonymousElementByAttribute(gBrowser, "anonid", "initialBrowser"); gBrowser.updateBrowserRemoteness(initBrowser, false, { opener: aOpener }); }, - setDefaultStatus(status) { + setDefaultStatus: function(status) { this.defaultStatus = status; this.updateStatusField(); }, - setOverLink(url, anchorElt) { + setOverLink: function(url, anchorElt) { // Encode bidirectional formatting characters. // (RFC 3987 sections 3.2 and 4.1 paragraph 6) url = url.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g, @@ -4365,7 +4365,7 @@ var XULBrowserWindow = { LinkTargetDisplay.update(); }, - showTooltip(x, y, tooltip, direction) { + showTooltip: function(x, y, tooltip, direction) { if (Cc["@mozilla.org/widget/dragservice;1"].getService(Ci.nsIDragService). getCurrentSession()) { return; @@ -4381,16 +4381,16 @@ var XULBrowserWindow = { elt.openPopupAtScreen(anchor.boxObject.screenX + x, anchor.boxObject.screenY + y, false, null); }, - hideTooltip() { + hideTooltip: function() { let elt = document.getElementById("remoteBrowserTooltip"); elt.hidePopup(); }, - getTabCount() { + getTabCount: function() { return gBrowser.tabs.length; }, - updateStatusField() { + updateStatusField: function() { var text, type, types = ["overLink"]; if (this._busyUI) types.push("status"); @@ -4414,14 +4414,14 @@ var XULBrowserWindow = { }, // Called before links are navigated to to allow us to retarget them if needed. - onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) { + onBeforeLinkTraversal: function(originalTarget, linkURI, linkNode, isAppTab) { let target = BrowserUtils.onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab); SocialUI.closeSocialPanelForLinkTraversal(target, linkNode); return target; }, // Check whether this URI should load in the current process - shouldLoadURI(aDocShell, aURI, aReferrer) { + shouldLoadURI: function(aDocShell, aURI, aReferrer) { if (!gMultiProcessBrowser) return true; @@ -4442,13 +4442,13 @@ var XULBrowserWindow = { return true; }, - onProgressChange(aWebProgress, aRequest, + onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { // Do nothing. }, - onProgressChange64(aWebProgress, aRequest, + onProgressChange64: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { return this.onProgressChange(aWebProgress, aRequest, @@ -4457,7 +4457,7 @@ var XULBrowserWindow = { }, // This function fires only for the currently selected tab. - onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { const nsIWebProgressListener = Ci.nsIWebProgressListener; const nsIChannel = Ci.nsIChannel; @@ -4541,7 +4541,7 @@ var XULBrowserWindow = { } }, - onLocationChange(aWebProgress, aRequest, aLocationURI, aFlags) { + onLocationChange: function(aWebProgress, aRequest, aLocationURI, aFlags) { var location = aLocationURI ? aLocationURI.spec : ""; // If displayed, hide the form validation popup. @@ -4685,15 +4685,15 @@ var XULBrowserWindow = { } }, - asyncUpdateUI() { + asyncUpdateUI: function() { FeedHandler.updateFeeds(); BrowserSearch.updateOpenSearchBadge(); }, // Left here for add-on compatibility, see bug 752434 - hideChromeForLocation() {}, + hideChromeForLocation: function() {}, - onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) { this.status = aMessage; this.updateStatusField(); }, @@ -4708,7 +4708,7 @@ var XULBrowserWindow = { // 3. Called directly during this object's initializations. // aRequest will be null always in case 2 and 3, and sometimes in case 1 (for // instance, there won't be a request when STATE_BLOCKED_TRACKING_CONTENT is observed). - onSecurityChange(aWebProgress, aRequest, aState, aIsSimulated) { + onSecurityChange: function(aWebProgress, aRequest, aState, aIsSimulated) { // Don't need to do anything if the data we use to update the UI hasn't // changed let uri = gBrowser.currentURI; @@ -4780,7 +4780,7 @@ var LinkTargetDisplay = { return XULBrowserWindow.statusTextField.label != ""; }, - update() { + update: function() { clearTimeout(this._timer); window.removeEventListener("mousemove", this, true); @@ -4801,7 +4801,7 @@ var LinkTargetDisplay = { } }, - handleEvent(event) { + handleEvent: function(event) { switch (event.type) { case "mousemove": // Restart the delay since the mouse was moved @@ -4811,14 +4811,14 @@ var LinkTargetDisplay = { } }, - _showDelayed() { + _showDelayed: function() { this._timer = setTimeout(function(self) { XULBrowserWindow.updateStatusField(); window.removeEventListener("mousemove", self, true); }, this.DELAY_SHOW, this); }, - _hide() { + _hide: function() { clearTimeout(this._timer); XULBrowserWindow.updateStatusField(); @@ -4826,7 +4826,7 @@ var LinkTargetDisplay = { }; var CombinedStopReload = { - init() { + init: function() { if (this._initialized) return; @@ -4843,7 +4843,7 @@ var CombinedStopReload = { this.stop = stop; }, - uninit() { + uninit: function() { if (!this._initialized) return; @@ -4854,14 +4854,14 @@ var CombinedStopReload = { this.stop = null; }, - handleEvent(event) { + handleEvent: function(event) { // the only event we listen to is "click" on the stop button if (event.button == 0 && !this.stop.disabled) this._stopClicked = true; }, - switchToStop() { + switchToStop: function() { if (!this._initialized) return; @@ -4869,7 +4869,7 @@ var CombinedStopReload = { this.reload.setAttribute("displaystop", "true"); }, - switchToReload(aDelay) { + switchToReload: function(aDelay) { if (!this._initialized) return; @@ -4896,7 +4896,7 @@ var CombinedStopReload = { }, 650, this); }, - _cancelTransition() { + _cancelTransition: function() { if (this._timer) { clearTimeout(this._timer); this._timer = 0; @@ -4909,7 +4909,7 @@ var TabsProgressListener = { // we won't see STATE_START events for pre-rendered tabs. _startedLoadTimer: new WeakSet(), - onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { // Collect telemetry data about tab load times. if (aWebProgress.isTopLevel && (!aRequest.originalURI || aRequest.originalURI.spec.scheme != "about")) { if (aStateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW) { @@ -4963,7 +4963,7 @@ var TabsProgressListener = { } }, - onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, + onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) { // Filter out location changes caused by anchor navigation // or history.push/pop/replaceState. @@ -5001,7 +5001,7 @@ function nsBrowserAccess() { } nsBrowserAccess.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIBrowserDOMWindow, Ci.nsISupports]), - _openURIInNewTab(aURI, aReferrer, aReferrerPolicy, aIsPrivate, + _openURIInNewTab: function(aURI, aReferrer, aReferrerPolicy, aIsPrivate, aIsExternal, aForceNotRemote = false, aUserContextId = Ci.nsIScriptSecurityManager.DEFAULT_USER_CONTEXT_ID, aOpener = null) { @@ -5045,7 +5045,7 @@ nsBrowserAccess.prototype = { return browser; }, - openURI(aURI, aOpener, aWhere, aFlags) { + openURI: function(aURI, aOpener, aWhere, aFlags) { // This function should only ever be called if we're opening a URI // from a non-remote browser window (via nsContentTreeOwner). if (aOpener && Cu.isCrossProcessWrapper(aOpener)) { @@ -5126,7 +5126,7 @@ nsBrowserAccess.prototype = { gBrowser.loadURIWithFlags(aURI.spec, { flags: loadflags, referrerURI: referrer, - referrerPolicy, + referrerPolicy: referrerPolicy, }); } if (!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground")) @@ -5160,7 +5160,7 @@ nsBrowserAccess.prototype = { return null; }, - isTabContentWindow(aWindow) { + isTabContentWindow: function(aWindow) { return gBrowser.browsers.some(browser => browser.contentWindow == aWindow); }, @@ -5376,7 +5376,7 @@ function displaySecurityInfo() var gHomeButton = { prefDomain: "browser.startup.homepage", - observe(aSubject, aTopic, aPrefName) + observe: function(aSubject, aTopic, aPrefName) { if (aTopic != "nsPref:changed" || aPrefName != this.prefDomain) return; @@ -5384,7 +5384,7 @@ var gHomeButton = { this.updateTooltip(); }, - updateTooltip(homeButton) + updateTooltip: function(homeButton) { if (!homeButton) homeButton = document.getElementById("home-button"); @@ -5398,7 +5398,7 @@ var gHomeButton = { } }, - getHomePage() + getHomePage: function() { var url; try { @@ -5703,8 +5703,8 @@ function handleLinkClick(event, href, linkNode) { let params = { charset: doc.characterSet, allowMixedContent: persistAllowMixedContentInChildTab, - referrerURI, - referrerPolicy, + referrerURI: referrerURI, + referrerPolicy: referrerPolicy, noReferrer: BrowserUtils.linkHasNoReferrer(linkNode), originPrincipal: doc.nodePrincipal, }; @@ -5884,7 +5884,7 @@ var gPageStyleMenu = { // _pageStyleSheets: new WeakMap(), - init() { + init: function() { let mm = window.messageManager; mm.addMessageListener("PageStyle:StyleSheets", (msg) => { this._pageStyleSheets.set(msg.target.permanentKey, msg.data); @@ -5904,7 +5904,7 @@ var gPageStyleMenu = { * See the documentation for gPageStyleMenu for a description * of the Object structure. */ - getBrowserStyleSheets(browser) { + getBrowserStyleSheets: function(browser) { if (!browser) { browser = gBrowser.selectedBrowser; } @@ -5916,7 +5916,7 @@ var gPageStyleMenu = { return data.filteredStyleSheets; }, - _getStyleSheetInfo(browser) { + _getStyleSheetInfo: function(browser) { let data = this._pageStyleSheets.get(browser.permanentKey); if (!data) { return { @@ -5929,7 +5929,7 @@ var gPageStyleMenu = { return data; }, - fillPopup(menuPopup) { + fillPopup: function(menuPopup) { let styleSheetInfo = this._getStyleSheetInfo(gBrowser.selectedBrowser); var noStyle = menuPopup.firstChild; var persistentOnly = noStyle.nextSibling; @@ -5973,12 +5973,12 @@ var gPageStyleMenu = { sep.hidden = (noStyle.hidden && persistentOnly.hidden) || !haveAltSheets; }, - switchStyleSheet(title) { + switchStyleSheet: function(title) { let mm = gBrowser.selectedBrowser.messageManager; - mm.sendAsyncMessage("PageStyle:Switch", {title}); + mm.sendAsyncMessage("PageStyle:Switch", {title: title}); }, - disableStyle() { + disableStyle: function() { let mm = gBrowser.selectedBrowser.messageManager; mm.sendAsyncMessage("PageStyle:Disable"); }, @@ -5999,7 +5999,7 @@ function setStyleDisabled(disabled) { var LanguageDetectionListener = { - init() { + init: function() { window.messageManager.addMessageListener("Translation:DocumentState", msg => { Translation.documentStateReceived(msg.target, msg.data); }); @@ -6011,7 +6011,7 @@ var BrowserOffline = { _inited: false, // BrowserOffline Public Methods - init() + init: function() { if (!this._uiElement) this._uiElement = document.getElementById("workOfflineMenuitemState"); @@ -6023,14 +6023,14 @@ var BrowserOffline = { this._inited = true; }, - uninit() + uninit: function() { if (this._inited) { Services.obs.removeObserver(this, "network:offline-status-changed"); } }, - toggleOfflineStatus() + toggleOfflineStatus: function() { var ioService = Services.io; @@ -6043,7 +6043,7 @@ var BrowserOffline = { }, // nsIObserver - observe(aSubject, aTopic, aState) + observe: function(aSubject, aTopic, aState) { if (aTopic != "network:offline-status-changed") return; @@ -6054,7 +6054,7 @@ var BrowserOffline = { }, // BrowserOffline Implementation Methods - _canGoOffline() + _canGoOffline: function() { try { var cancelGoOffline = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool); @@ -6071,7 +6071,7 @@ var BrowserOffline = { }, _uiElement: null, - _updateOfflineUI(aOffline) + _updateOfflineUI: function(aOffline) { var offlineLocked = gPrefService.prefIsLocked("network.online"); if (offlineLocked) @@ -6165,7 +6165,7 @@ var OfflineApps = { let mainAction = { label: gNavigatorBundle.getString("offlineApps.allowStoring.label"), accessKey: gNavigatorBundle.getString("offlineApps.allowStoring.accesskey"), - callback() { + callback: function() { for (let [ciBrowser, ciDocId, ciUri] of notification.options.controlledItems) { OfflineApps.allowSite(ciBrowser, ciDocId, ciUri); } @@ -6174,7 +6174,7 @@ var OfflineApps = { let secondaryActions = [{ label: gNavigatorBundle.getString("offlineApps.dontAllow.label"), accessKey: gNavigatorBundle.getString("offlineApps.dontAllow.accesskey"), - callback() { + callback: function() { for (let [, , ciUri] of notification.options.controlledItems) { OfflineApps.disallowSite(ciUri); } @@ -6283,7 +6283,7 @@ var IndexedDBPromptHelper = { var mainAction = { label: gNavigatorBundle.getString("offlineApps.allowStoring.label"), accessKey: gNavigatorBundle.getString("offlineApps.allowStoring.accesskey"), - callback() { + callback: function() { observer.observe(null, responseTopic, Ci.nsIPermissionManager.ALLOW_ACTION); } @@ -6293,7 +6293,7 @@ var IndexedDBPromptHelper = { { label: gNavigatorBundle.getString("offlineApps.dontAllow.label"), accessKey: gNavigatorBundle.getString("offlineApps.dontAllow.accesskey"), - callback() { + callback: function() { observer.observe(null, responseTopic, Ci.nsIPermissionManager.DENY_ACTION); } @@ -6414,11 +6414,11 @@ function warnAboutClosingWindow() { } var MailIntegration = { - sendLinkForBrowser(aBrowser) { + sendLinkForBrowser: function(aBrowser) { this.sendMessage(aBrowser.currentURI.spec, aBrowser.contentTitle); }, - sendMessage(aBody, aSubject) { + sendMessage: function(aBody, aSubject) { // generate a mailto url based on the url and the url's title var mailtoUrl = "mailto:"; if (aBody) { @@ -6435,7 +6435,7 @@ var MailIntegration = { // a generic method which can be used to pass arbitrary urls to the operating // system. // aURL --> a nsIURI which represents the url to launch - _launchExternalUrl(aURL) { + _launchExternalUrl: function(aURL) { var extProtocolSvc = Cc["@mozilla.org/uriloader/external-protocol-service;1"] .getService(Ci.nsIExternalProtocolService); @@ -6504,7 +6504,7 @@ function AddKeywordForSearchField() { PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , uri: makeURI(bookmarkData.spec) - , title + , title: title , description: bookmarkData.description , keyword: "" , postData: bookmarkData.postData @@ -6840,7 +6840,7 @@ var gIdentityHandler = { * Handler for mouseclicks on the "More Information" button in the * "identity-popup" panel. */ - handleMoreInfoClick(event) { + handleMoreInfoClick : function(event) { displaySecurityInfo(); event.stopPropagation(); this._identityPopup.hidePopup(); @@ -6898,7 +6898,7 @@ var gIdentityHandler = { * Helper to parse out the important parts of _sslStatus (of the SSL cert in * particular) for use in constructing identity UI strings */ - getIdentityData() { + getIdentityData : function() { var result = {}; var cert = this._sslStatus.serverCert; @@ -6999,7 +6999,7 @@ var gIdentityHandler = { /** * Attempt to provide proper IDN treatment for host names */ - getEffectiveHost() { + getEffectiveHost: function() { if (!this._IDNService) this._IDNService = Cc["@mozilla.org/network/idn-service;1"] .getService(Ci.nsIIDNService); @@ -7179,7 +7179,7 @@ var gIdentityHandler = { let buttons = [{ label: gNavigatorBundle.getString("revokeOverride.label"), accessKey: gNavigatorBundle.getString("revokeOverride.accesskey"), - callback(aNotification, aButton) { + callback: function(aNotification, aButton) { try { let weakCryptoOverride = Cc["@mozilla.org/security/weakcryptooverride;1"] .getService(Ci.nsIWeakCryptoOverride); @@ -7369,7 +7369,7 @@ var gIdentityHandler = { /** * Click handler for the identity-box element in primary chrome. */ - handleIdentityButtonEvent(event) { + handleIdentityButtonEvent : function(event) { event.stopPropagation(); if ((event.type == "click" && event.button != 0) || @@ -7430,7 +7430,7 @@ var gIdentityHandler = { } }, - onDragStart(event) { + onDragStart: function(event) { if (gURLBar.getAttribute("pageproxystate") != "valid") return; @@ -7446,12 +7446,12 @@ var gIdentityHandler = { dt.setDragImage(this._identityIcon, 16, 16); }, - onLocationChange() { + onLocationChange: function() { this._permissionJustRemoved = false; this.updatePermissionHint(); }, - updatePermissionHint() { + updatePermissionHint: function() { if (!this._permissionList.hasChildNodes() && !this._permissionJustRemoved) { this._permissionEmptyHint.removeAttribute("hidden"); } else { @@ -7465,7 +7465,7 @@ var gIdentityHandler = { } }, - updateSitePermissions() { + updateSitePermissions: function() { while (this._permissionList.hasChildNodes()) this._permissionList.removeChild(this._permissionList.lastChild); @@ -7504,7 +7504,7 @@ var gIdentityHandler = { this.updatePermissionHint(); }, - _handleHeightChange(aFunction, aWillShowReloadHint) { + _handleHeightChange: function(aFunction, aWillShowReloadHint) { let heightBefore = getComputedStyle(this._permissionList).height; aFunction(); let heightAfter = getComputedStyle(this._permissionList).height; @@ -7518,7 +7518,7 @@ var gIdentityHandler = { this._identityPopupMultiView.setHeightToFit(heightChange); }, - _createPermissionItem(aPermission) { + _createPermissionItem: function(aPermission) { let container = document.createElement("hbox"); container.setAttribute("class", "identity-popup-permission-item"); container.setAttribute("align", "center"); @@ -7681,7 +7681,7 @@ var gPrivateBrowsingUI = { }; var gRemoteTabsUI = { - init() { + init: function() { if (window.location.href != getBrowserURL() && // Also check hidden window for the Mac no-window case window.location.href != "chrome://browser/content/hiddenWindow.xul") { @@ -7828,7 +7828,7 @@ function switchToTabHavingURI(aURI, aOpenNew, aOpenParams = {}) { } var RestoreLastSessionObserver = { - init() { + init: function() { if (SessionStore.canRestoreLastSession && !PrivateBrowsingUtils.isWindowPrivate(window)) { Services.obs.addObserver(this, "sessionstore-last-session-cleared", true); @@ -7836,7 +7836,7 @@ var RestoreLastSessionObserver = { } }, - observe() { + observe: function() { // The last session can only be restored once so there's // no way we need to re-enable our menu item. Services.obs.removeObserver(this, "sessionstore-last-session-cleared"); @@ -8047,7 +8047,7 @@ var MousePosTracker = { return this._windowUtils = window.getInterface(Ci.nsIDOMWindowUtils); }, - addListener(listener) { + addListener: function(listener) { if (this._listeners.has(listener)) return; @@ -8057,11 +8057,11 @@ var MousePosTracker = { this._callListener(listener); }, - removeListener(listener) { + removeListener: function(listener) { this._listeners.delete(listener); }, - handleEvent(event) { + handleEvent: function(event) { var fullZoom = this._windowUtils.fullZoom; this._x = event.screenX / fullZoom - window.mozInnerScreenX; this._y = event.screenY / fullZoom - window.mozInnerScreenY; @@ -8075,7 +8075,7 @@ var MousePosTracker = { }, this); }, - _callListener(listener) { + _callListener: function(listener) { let rect = listener.getMouseTargetRect(); let hover = this._x >= rect.left && this._x <= rect.right && @@ -8097,7 +8097,7 @@ var MousePosTracker = { }; var ToolbarIconColor = { - init() { + init: function() { this._initialized = true; window.addEventListener("activate", this); @@ -8111,7 +8111,7 @@ var ToolbarIconColor = { this.inferFromText(); }, - uninit() { + uninit: function() { this._initialized = false; window.removeEventListener("activate", this); @@ -8119,7 +8119,7 @@ var ToolbarIconColor = { Services.obs.removeObserver(this, "lightweight-theme-styling-update"); }, - handleEvent(event) { + handleEvent: function(event) { switch (event.type) { case "activate": case "deactivate": @@ -8128,7 +8128,7 @@ var ToolbarIconColor = { } }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { switch (aTopic) { case "lightweight-theme-styling-update": // inferFromText needs to run after LightweightThemeConsumer.jsm's @@ -8138,7 +8138,7 @@ var ToolbarIconColor = { } }, - inferFromText() { + inferFromText: function() { if (!this._initialized) return; @@ -8172,14 +8172,14 @@ var ToolbarIconColor = { } var PanicButtonNotifier = { - init() { + init: function() { this._initialized = true; if (window.PanicButtonNotifierShouldNotify) { delete window.PanicButtonNotifierShouldNotify; this.notify(); } }, - notify() { + notify: function() { if (!this._initialized) { window.PanicButtonNotifierShouldNotify = true; return; @@ -8196,14 +8196,14 @@ var PanicButtonNotifier = { Cu.reportError(ex); } }, - close() { + close: function() { let popup = document.getElementById("panic-button-success-notification"); popup.hidePopup(); }, }; var AboutPrivateBrowsingListener = { - init() { + init: function() { window.messageManager.addMessageListener( "AboutPrivateBrowsing:OpenPrivateWindow", msg => { diff --git a/browser/base/content/content.js b/browser/base/content/content.js index 837cd5863b80..c5e1c0ec1451 100644 --- a/browser/base/content/content.js +++ b/browser/base/content/content.js @@ -103,8 +103,8 @@ var handleContentContextMenu = function(event) { let addonInfo = {}; let subject = { - event, - addonInfo, + event: event, + addonInfo: addonInfo, }; subject.wrappedJSObject = subject; Services.obs.notifyObservers(subject, "content-contextmenu", null); @@ -197,18 +197,18 @@ var handleContentContextMenu = function(event) { let mainWin = browser.ownerGlobal; mainWin.gContextMenuContentData = { isRemote: false, - event, + event: event, popupNode: event.target, - browser, - addonInfo, + browser: browser, + addonInfo: addonInfo, documentURIObject: doc.documentURIObject, - docLocation, - charSet, - referrer, - referrerPolicy, - contentType, - contentDisposition, - selectionInfo, + docLocation: docLocation, + charSet: charSet, + referrer: referrer, + referrerPolicy: referrerPolicy, + contentType: contentType, + contentDisposition: contentDisposition, + selectionInfo: selectionInfo, disableSetDesktopBackground: disableSetDesktopBg, loginFillInfo, parentAllowsMixedContent, @@ -262,7 +262,7 @@ function getSerializedSecurityInfo(docShell) { } var AboutNetAndCertErrorListener = { - init(chromeGlobal) { + init: function(chromeGlobal) { addMessageListener("CertErrorDetails", this); addMessageListener("Browser:CaptivePortalFreed", this); chromeGlobal.addEventListener('AboutNetErrorLoad', this, false, true); @@ -280,7 +280,7 @@ var AboutNetAndCertErrorListener = { return content.document.documentURI.startsWith("about:certerror"); }, - receiveMessage(msg) { + receiveMessage: function(msg) { if (!this.isAboutCertError) { return; } @@ -348,7 +348,7 @@ var AboutNetAndCertErrorListener = { content.dispatchEvent(new content.CustomEvent("AboutNetErrorCaptivePortalFreed")); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { if (!this.isAboutNetError && !this.isAboutCertError) { return; } @@ -372,7 +372,7 @@ var AboutNetAndCertErrorListener = { } }, - changedCertPrefs() { + changedCertPrefs: function() { for (let prefName of PREF_SSL_IMPACT) { if (Services.prefs.prefHasUserValue(prefName)) { return true; @@ -382,7 +382,7 @@ var AboutNetAndCertErrorListener = { return false; }, - onPageLoad(evt) { + onPageLoad: function(evt) { if (this.isAboutCertError) { let originalTarget = evt.originalTarget; let ownerDoc = originalTarget.ownerDocument; @@ -394,7 +394,7 @@ var AboutNetAndCertErrorListener = { detail: JSON.stringify({ enabled: Services.prefs.getBoolPref("security.ssl.errorReporting.enabled"), changedCertPrefs: this.changedCertPrefs(), - automatic + automatic: automatic }) })); @@ -402,16 +402,16 @@ var AboutNetAndCertErrorListener = { {reportStatus: TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN}); }, - openCaptivePortalPage(evt) { + openCaptivePortalPage: function(evt) { sendAsyncMessage("Browser:OpenCaptivePortalPage"); }, - onResetPreferences(evt) { + onResetPreferences: function(evt) { sendAsyncMessage("Browser:ResetSSLPreferences"); }, - onSetAutomatic(evt) { + onSetAutomatic: function(evt) { sendAsyncMessage("Browser:SetSSLErrorReportAuto", { automatic: evt.detail }); @@ -427,7 +427,7 @@ var AboutNetAndCertErrorListener = { } }, - onOverride(evt) { + onOverride: function(evt) { let {host, port} = content.document.mozDocumentURIIfNotForErrorPages; sendAsyncMessage("Browser:OverrideWeakCrypto", { uri: {host, port} }); } @@ -443,7 +443,7 @@ var ClickEventHandler = { .addSystemEventListener(global, "click", this, true); }, - handleEvent(event) { + handleEvent: function(event) { if (!event.isTrusted || event.defaultPrevented || event.button == 2) { return; } @@ -484,7 +484,7 @@ var ClickEventHandler = { let json = { button: event.button, shiftKey: event.shiftKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, href: null, title: null, - bookmark: false, referrerPolicy, + bookmark: false, referrerPolicy: referrerPolicy, originAttributes: principal ? principal.originAttributes : {}, isContentWindowPrivate: PrivateBrowsingUtils.isContentWindowPrivate(ownerDoc.defaultView)}; @@ -535,7 +535,7 @@ var ClickEventHandler = { } }, - onCertError(targetElement, ownerDoc) { + onCertError: function(targetElement, ownerDoc) { let docShell = ownerDoc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShell); @@ -547,7 +547,7 @@ var ClickEventHandler = { }); }, - onAboutBlocked(targetElement, ownerDoc) { + onAboutBlocked: function(targetElement, ownerDoc) { var reason = 'phishing'; if (/e=malwareBlocked/.test(ownerDoc.documentURI)) { reason = 'malware'; @@ -556,13 +556,13 @@ var ClickEventHandler = { } sendAsyncMessage("Browser:SiteBlockedError", { location: ownerDoc.location.href, - reason, + reason: reason, elementId: targetElement.getAttribute("id"), isTopFrame: (ownerDoc.defaultView.parent === ownerDoc.defaultView) }); }, - onAboutNetError(event, documentURI) { + onAboutNetError: function(event, documentURI) { let elmId = event.originalTarget.getAttribute("id"); if (elmId == "returnButton") { sendAsyncMessage("Browser:SSLErrorGoBack", {}); @@ -591,7 +591,7 @@ var ClickEventHandler = { * element. This includes SVG links, because callers expect |node| * to behave like an element, which SVG links (XLink) don't. */ - _hrefAndLinkNodeForClickEvent(event) { + _hrefAndLinkNodeForClickEvent: function(event) { function isHTMLLink(aNode) { // Be consistent with what nsContextMenu.js does. return ((aNode instanceof content.HTMLAnchorElement && aNode.href) || @@ -656,7 +656,7 @@ addMessageListener("webrtc:StartBrowserSharing", () => { let windowID = content.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils).outerWindowID; sendAsyncMessage("webrtc:response:StartBrowserSharing", { - windowID + windowID: windowID }); }); @@ -876,20 +876,20 @@ addMessageListener("Bookmarks:GetPageDetails", (message) => { let doc = content.document; let isErrorPage = /^about:(neterror|certerror|blocked)/.test(doc.documentURI); sendAsyncMessage("Bookmarks:GetPageDetails:Result", - { isErrorPage, + { isErrorPage: isErrorPage, description: PlacesUIUtils.getDescriptionFromDocument(doc) }); }); var LightWeightThemeWebInstallListener = { _previewWindow: null, - init() { + init: function() { addEventListener("InstallBrowserTheme", this, false, true); addEventListener("PreviewBrowserTheme", this, false, true); addEventListener("ResetBrowserThemePreview", this, false, true); }, - handleEvent(event) { + handleEvent: function(event) { switch (event.type) { case "InstallBrowserTheme": { sendAsyncMessage("LightWeightThemeWebInstaller:Install", { @@ -923,7 +923,7 @@ var LightWeightThemeWebInstallListener = { } }, - _resetPreviewWindow() { + _resetPreviewWindow: function() { this._previewWindow.removeEventListener("pagehide", this, true); this._previewWindow = null; } @@ -982,11 +982,11 @@ addMessageListener("ContextMenu:SetAsDesktopBackground", (message) => { var PageInfoListener = { - init() { + init: function() { addMessageListener("PageInfo:getData", this); }, - receiveMessage(message) { + receiveMessage: function(message) { let strings = message.data.strings; let window; let document; @@ -1017,7 +1017,7 @@ var PageInfoListener = { this.getMediaInfo(document, window, strings); }, - getImageInfo(imageElement) { + getImageInfo: function(imageElement) { let imageInfo = null; if (imageElement) { imageInfo = { @@ -1030,7 +1030,7 @@ var PageInfoListener = { return imageInfo; }, - getMetaInfo(document) { + getMetaInfo: function(document) { let metaViewRows = []; // Get the meta tags from the page. @@ -1044,7 +1044,7 @@ var PageInfoListener = { return metaViewRows; }, - getWindowInfo(window) { + getWindowInfo: function(window) { let windowInfo = {}; windowInfo.isTopWindow = window == window.top; @@ -1058,7 +1058,7 @@ var PageInfoListener = { return windowInfo; }, - getDocumentInfo(document) { + getDocumentInfo: function(document) { let docInfo = {}; docInfo.title = document.title; docInfo.location = document.location.toString(); @@ -1079,7 +1079,7 @@ var PageInfoListener = { return docInfo; }, - getFeedsInfo(document, strings) { + getFeedsInfo: function(document, strings) { let feeds = []; // Get the feeds from the page. let linkNodes = document.getElementsByTagName("link"); @@ -1110,13 +1110,13 @@ var PageInfoListener = { }, // Only called once to get the media tab's media elements from the content page. - getMediaInfo(document, window, strings) + getMediaInfo: function(document, window, strings) { let frameList = this.goThroughFrames(document, window); Task.spawn(() => this.processFrames(document, frameList, strings)); }, - goThroughFrames(document, window) + goThroughFrames: function(document, window) { let frameList = [document]; if (window && window.frames.length > 0) { @@ -1130,7 +1130,7 @@ var PageInfoListener = { return frameList; }, - *processFrames(document, frameList, strings) + processFrames: function*(document, frameList, strings) { let nodeCount = 0; for (let doc of frameList) { @@ -1155,7 +1155,7 @@ var PageInfoListener = { sendAsyncMessage("PageInfo:mediaData", {isComplete: true}); }, - getMediaItems(document, strings, elem) + getMediaItems: function(document, strings, elem) { // Check for images defined in CSS (e.g. background, borders) let computedStyle = elem.ownerGlobal.getComputedStyle(elem); @@ -1241,7 +1241,7 @@ var PageInfoListener = { * makePreview in pageInfo.js uses to figure out how to display the preview. */ - serializeElementInfo(document, url, type, alt, item, isBG) + serializeElementInfo: function(document, url, type, alt, item, isBG) { let result = {}; @@ -1322,7 +1322,7 @@ var PageInfoListener = { // Other Misc Stuff // Modified from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html // parse a node to extract the contents of the node - getValueText(node) + getValueText: function(node) { let valueText = ""; @@ -1362,7 +1362,7 @@ var PageInfoListener = { // Copied from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html. // Traverse the tree in search of an img or area element and grab its alt tag. - getAltText(node) + getAltText: function(node) { let altText = ""; @@ -1380,7 +1380,7 @@ var PageInfoListener = { // Copied from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html. // Strip leading and trailing whitespace, and replace multiple consecutive whitespace characters with a single space. - stripWS(text) + stripWS: function(text) { let middleRE = /\s+/g; let endRE = /(^\s+)|(\s+$)/g; diff --git a/browser/base/content/contentSearchUI.js b/browser/base/content/contentSearchUI.js index d3f8d5f143ce..688d8b1cfe4b 100644 --- a/browser/base/content/contentSearchUI.js +++ b/browser/base/content/contentSearchUI.js @@ -90,7 +90,7 @@ ContentSearchUIController.prototype = { } this._defaultEngine = { name: engine.name, - icon, + icon: icon, }; this._updateDefaultEngineHeader(); @@ -189,7 +189,7 @@ ContentSearchUIController.prototype = { return this._suggestionsList.children.length; }, - selectAndUpdateInput(idx) { + selectAndUpdateInput: function(idx) { this.selectedIndex = idx; let newValue = this.suggestionAtIndex(idx) || this._stickyInputValue; // Setting the input value when the value has not changed commits the current @@ -200,12 +200,12 @@ ContentSearchUIController.prototype = { this._updateSearchWithHeader(); }, - suggestionAtIndex(idx) { + suggestionAtIndex: function(idx) { let row = this._suggestionsList.children[idx]; return row ? row.textContent : null; }, - deleteSuggestionAtIndex(idx) { + deleteSuggestionAtIndex: function(idx) { // Only form history suggestions can be deleted. if (this.isFormHistorySuggestionAtIndex(idx)) { let suggestionStr = this.suggestionAtIndex(idx); @@ -215,20 +215,20 @@ ContentSearchUIController.prototype = { } }, - isFormHistorySuggestionAtIndex(idx) { + isFormHistorySuggestionAtIndex: function(idx) { let row = this._suggestionsList.children[idx]; return row && row.classList.contains("formHistory"); }, - addInputValueToFormHistory() { + addInputValueToFormHistory: function() { this._sendMsg("AddFormHistoryEntry", this.input.value); }, - handleEvent(event) { + handleEvent: function(event) { this["_on" + event.type[0].toUpperCase() + event.type.substr(1)](event); }, - _onCommand(aEvent) { + _onCommand: function(aEvent) { if (this.selectedButtonIndex == this._oneOffButtons.length) { // Settings button was selected. this._sendMsg("ManageEngines"); @@ -242,7 +242,7 @@ ContentSearchUIController.prototype = { } }, - search(aEvent) { + search: function(aEvent) { if (!this.defaultEngine) { return; // Not initialized yet. } @@ -291,7 +291,7 @@ ContentSearchUIController.prototype = { this.addInputValueToFormHistory(); }, - _onInput() { + _onInput: function() { if (!this.input.value) { this._stickyInputValue = ""; this._hideSuggestions(); @@ -304,7 +304,7 @@ ContentSearchUIController.prototype = { this._updateSearchWithHeader(); }, - _onKeypress(event) { + _onKeypress: function(event) { let selectedIndexDelta = 0; let selectedSuggestionDelta = 0; let selectedOneOffDelta = 0; @@ -451,7 +451,7 @@ ContentSearchUIController.prototype = { }, _currentEngineIndex: -1, - _cycleCurrentEngine(aReverse) { + _cycleCurrentEngine: function(aReverse) { if ((this._currentEngineIndex == this._engines.length - 1 && !aReverse) || (this._currentEngineIndex == 0 && aReverse)) { return; @@ -461,7 +461,7 @@ ContentSearchUIController.prototype = { this._sendMsg("SetCurrentEngine", engineName); }, - _onFocus() { + _onFocus: function() { if (this._mousedown) { return; } @@ -474,7 +474,7 @@ ContentSearchUIController.prototype = { this._speculativeConnect(); }, - _onBlur() { + _onBlur: function() { if (this._mousedown) { // At this point, this.input has lost focus, but a new element has not yet // received it. If we re-focus this.input directly, the new element will @@ -486,7 +486,7 @@ ContentSearchUIController.prototype = { this._hideSuggestions(); }, - _onMousemove(event) { + _onMousemove: function(event) { let idx = this._indexOfTableItem(event.target); if (idx >= this.numSuggestions) { this.selectedButtonIndex = idx - this.numSuggestions; @@ -495,14 +495,14 @@ ContentSearchUIController.prototype = { this.selectedIndex = idx; }, - _onMouseup(event) { + _onMouseup: function(event) { if (event.button == 2) { return; } this._onCommand(event); }, - _onMouseout(event) { + _onMouseout: function(event) { // We only deselect one-off buttons and the settings button when they are // moused out. let idx = this._indexOfTableItem(event.originalTarget); @@ -511,22 +511,22 @@ ContentSearchUIController.prototype = { } }, - _onClick(event) { + _onClick: function(event) { this._onMouseup(event); }, - _onContentSearchService(event) { + _onContentSearchService: function(event) { let methodName = "_onMsg" + event.detail.type; if (methodName in this) { this[methodName](event.detail.data); } }, - _onMsgFocusInput(event) { + _onMsgFocusInput: function(event) { this.input.focus(); }, - _onMsgSuggestions(suggestions) { + _onMsgSuggestions: function(suggestions) { // Ignore the suggestions if their search string or engine doesn't match // ours. Due to the async nature of message passing, this can easily happen // when the user types quickly. @@ -581,13 +581,13 @@ ContentSearchUIController.prototype = { } }, - _onMsgSuggestionsCancelled() { + _onMsgSuggestionsCancelled: function() { if (!this._table.hidden) { this._hideSuggestions(); } }, - _onMsgState(state) { + _onMsgState: function(state) { this.engines = state.engines; // No point updating the default engine (and the header) if there's no change. if (this.defaultEngine && @@ -598,16 +598,16 @@ ContentSearchUIController.prototype = { this.defaultEngine = state.currentEngine; }, - _onMsgCurrentState(state) { + _onMsgCurrentState: function(state) { this._onMsgState(state); }, - _onMsgCurrentEngine(engine) { + _onMsgCurrentEngine: function(engine) { this.defaultEngine = engine; this._pendingOneOffRefresh = true; }, - _onMsgStrings(strings) { + _onMsgStrings: function(strings) { this._strings = strings; this._updateDefaultEngineHeader(); this._updateSearchWithHeader(); @@ -616,7 +616,7 @@ ContentSearchUIController.prototype = { this.input.setAttribute("placeholder", this._strings.searchPlaceholder); }, - _updateDefaultEngineHeader() { + _updateDefaultEngineHeader: function() { let header = document.getElementById("contentSearchDefaultEngineHeader"); header.firstChild.setAttribute("src", this.defaultEngine.icon); if (!this._strings) { @@ -629,7 +629,7 @@ ContentSearchUIController.prototype = { this._strings.searchHeader.replace("%S", this.defaultEngine.name))); }, - _updateSearchWithHeader() { + _updateSearchWithHeader: function() { if (!this._strings) { return; } @@ -642,13 +642,13 @@ ContentSearchUIController.prototype = { } }, - _speculativeConnect() { + _speculativeConnect: function() { if (this.defaultEngine) { this._sendMsg("SpeculativeConnect", this.defaultEngine.name); } }, - _makeTableRow(type, suggestionStr, currentRow, searchWords) { + _makeTableRow: function(type, suggestionStr, currentRow, searchWords) { let row = document.createElementNS(HTML_NS, "tr"); row.dir = "auto"; row.classList.add("contentSearchSuggestionRow"); @@ -685,28 +685,28 @@ ContentSearchUIController.prototype = { }, // Converts favicon array buffer into a data URI. - _getFaviconURIFromBuffer(buffer) { + _getFaviconURIFromBuffer: function(buffer) { let blob = new Blob([buffer]); return URL.createObjectURL(blob); }, // Adds "@2x" to the name of the given PNG url for "retina" screens. - _getImageURIForCurrentResolution(uri) { + _getImageURIForCurrentResolution: function(uri) { if (window.devicePixelRatio > 1) { return uri.replace(/\.png$/, "@2x.png"); } return uri; }, - _getSearchEngines() { + _getSearchEngines: function() { this._sendMsg("GetState"); }, - _getStrings() { + _getStrings: function() { this._sendMsg("GetStrings"); }, - _getSuggestions() { + _getSuggestions: function() { this._stickyInputValue = this.input.value; if (this.defaultEngine) { this._sendMsg("GetSuggestions", { @@ -716,13 +716,13 @@ ContentSearchUIController.prototype = { } }, - _clearSuggestionRows() { + _clearSuggestionRows: function() { while (this._suggestionsList.firstElementChild) { this._suggestionsList.firstElementChild.remove(); } }, - _hideSuggestions() { + _hideSuggestions: function() { this.input.setAttribute("aria-expanded", "false"); this.selectedIndex = -1; this.selectedButtonIndex = -1; @@ -730,7 +730,7 @@ ContentSearchUIController.prototype = { this._table.hidden = true; }, - _indexOfTableItem(elt) { + _indexOfTableItem: function(elt) { if (elt.classList.contains("contentSearchOneOffItem")) { return this.numSuggestions + this._oneOffButtons.indexOf(elt); } @@ -746,7 +746,7 @@ ContentSearchUIController.prototype = { return elt.rowIndex; }, - _makeTable(id) { + _makeTable: function(id) { this._table = document.createElementNS(HTML_NS, "table"); this._table.id = id; this._table.hidden = true; @@ -815,7 +815,7 @@ ContentSearchUIController.prototype = { return this._table; }, - _setUpOneOffButtons() { + _setUpOneOffButtons: function() { // Sometimes we receive a CurrentEngine message from the ContentSearch service // before we've received a State message - i.e. before we have our engines. if (!this._engines) { @@ -896,11 +896,11 @@ ContentSearchUIController.prototype = { this._oneOffsTable.hidden = false; }, - _sendMsg(type, data = null) { + _sendMsg: function(type, data = null) { dispatchEvent(new CustomEvent("ContentSearchClient", { detail: { - type, - data, + type: type, + data: data, }, })); }, diff --git a/browser/base/content/pageinfo/pageInfo.js b/browser/base/content/pageinfo/pageInfo.js index dd4336951248..1e96c4e8b632 100644 --- a/browser/base/content/pageinfo/pageInfo.js +++ b/browser/base/content/pageinfo/pageInfo.js @@ -24,12 +24,12 @@ pageInfoTreeView.prototype = { set rowCount(c) { throw "rowCount is a readonly property"; }, get rowCount() { return this.rows; }, - setTree(tree) + setTree: function(tree) { this.tree = tree; }, - getCellText(row, column) + getCellText: function(row, column) { // row can be null, but js arrays are 0-indexed. // colidx cannot be null, but can be larger than the number @@ -38,16 +38,16 @@ pageInfoTreeView.prototype = { return this.data[row][column.index] || ""; }, - setCellValue(row, column, value) + setCellValue: function(row, column, value) { }, - setCellText(row, column, value) + setCellText: function(row, column, value) { this.data[row][column.index] = value; }, - addRow(row) + addRow: function(row) { this.rows = this.data.push(row); this.rowCountChanged(this.rows - 1, 1); @@ -56,24 +56,24 @@ pageInfoTreeView.prototype = { } }, - addRows(rows) + addRows: function(rows) { for (let row of rows) { this.addRow(row); } }, - rowCountChanged(index, count) + rowCountChanged: function(index, count) { this.tree.rowCountChanged(index, count); }, - invalidate() + invalidate: function() { this.tree.invalidate(); }, - clear() + clear: function() { if (this.tree) this.tree.rowCountChanged(0, -this.rows); @@ -81,12 +81,12 @@ pageInfoTreeView.prototype = { this.data = [ ]; }, - handleCopy(row) + handleCopy: function(row) { return (row < 0 || this.copycol < 0) ? "" : (this.data[row][this.copycol] || ""); }, - performActionOnRow(action, row) + performActionOnRow: function(action, row) { if (action == "copy") { var data = this.handleCopy(row) @@ -94,7 +94,7 @@ pageInfoTreeView.prototype = { } }, - onPageMediaSort(columnname) + onPageMediaSort : function(columnname) { var tree = document.getElementById(this.treeid); var treecol = tree.columns.getNamedColumn(columnname); @@ -121,29 +121,29 @@ pageInfoTreeView.prototype = { this.sortcol = treecol.index; }, - getRowProperties(row) { return ""; }, - getCellProperties(row, column) { return ""; }, - getColumnProperties(column) { return ""; }, - isContainer(index) { return false; }, - isContainerOpen(index) { return false; }, - isSeparator(index) { return false; }, - isSorted() { return this.sortcol > -1 }, - canDrop(index, orientation) { return false; }, - drop(row, orientation) { return false; }, - getParentIndex(index) { return 0; }, - hasNextSibling(index, after) { return false; }, - getLevel(index) { return 0; }, - getImageSrc(row, column) { }, - getProgressMode(row, column) { }, - getCellValue(row, column) { }, - toggleOpenState(index) { }, - cycleHeader(col) { }, - selectionChanged() { }, - cycleCell(row, column) { }, - isEditable(row, column) { return false; }, - isSelectable(row, column) { return false; }, - performAction(action) { }, - performActionOnCell(action, row, column) { } + getRowProperties: function(row) { return ""; }, + getCellProperties: function(row, column) { return ""; }, + getColumnProperties: function(column) { return ""; }, + isContainer: function(index) { return false; }, + isContainerOpen: function(index) { return false; }, + isSeparator: function(index) { return false; }, + isSorted: function() { return this.sortcol > -1 }, + canDrop: function(index, orientation) { return false; }, + drop: function(row, orientation) { return false; }, + getParentIndex: function(index) { return 0; }, + hasNextSibling: function(index, after) { return false; }, + getLevel: function(index) { return 0; }, + getImageSrc: function(row, column) { }, + getProgressMode: function(row, column) { }, + getCellValue: function(row, column) { }, + toggleOpenState: function(index) { }, + cycleHeader: function(col) { }, + selectionChanged: function() { }, + cycleCell: function(row, column) { }, + isEditable: function(row, column) { return false; }, + isSelectable: function(row, column) { return false; }, + performAction: function(action) { }, + performActionOnCell: function(action, row, column) { } }; // mmm, yummy. global variables. @@ -359,7 +359,7 @@ function loadPageInfo(frameOuterWindowID, imageElement, browser) // Look for pageInfoListener in content.js. Sends message to listener with arguments. mm.sendAsyncMessage("PageInfo:getData", {strings: gStrings, - frameOuterWindowID}, + frameOuterWindowID: frameOuterWindowID}, { imageElement }); let pageInfoData; @@ -517,10 +517,10 @@ function toggleGroupbox(id) function openCacheEntry(key, cb) { var checkCacheListener = { - onCacheEntryCheck(entry, appCache) { + onCacheEntryCheck: function(entry, appCache) { return Components.interfaces.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable(entry, isNew, appCache, status) { + onCacheEntryAvailable: function(entry, isNew, appCache, status) { cb(entry); } }; @@ -1004,7 +1004,7 @@ function makeBlockImage(url) } var imagePermissionObserver = { - observe(aSubject, aTopic, aData) + observe: function(aSubject, aTopic, aData) { if (document.getElementById("mediaPreviewBox").collapsed) return; diff --git a/browser/base/content/pageinfo/permissions.js b/browser/base/content/pageinfo/permissions.js index 5a563c035e97..b3e1720dc544 100644 --- a/browser/base/content/pageinfo/permissions.js +++ b/browser/base/content/pageinfo/permissions.js @@ -20,7 +20,7 @@ var gPermissions = SitePermissions.listPermissions().sort((a, b) => { gPermissions.push("plugins"); var permissionObserver = { - observe(aSubject, aTopic, aData) + observe: function(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { var permission = aSubject.QueryInterface(Components.interfaces.nsIPermission); diff --git a/browser/base/content/pageinfo/security.js b/browser/base/content/pageinfo/security.js index e3f0fdc886b9..2638cb13d76e 100644 --- a/browser/base/content/pageinfo/security.js +++ b/browser/base/content/pageinfo/security.js @@ -9,18 +9,18 @@ XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper", "resource://gre/modules/LoginHelper.jsm"); var security = { - init(uri, windowInfo) { + init: function(uri, windowInfo) { this.uri = uri; this.windowInfo = windowInfo; }, // Display the server certificate (static) - viewCert() { + viewCert : function() { var cert = security._cert; viewCertHelper(window, cert); }, - _getSecurityInfo() { + _getSecurityInfo : function() { const nsISSLStatusProvider = Components.interfaces.nsISSLStatusProvider; const nsISSLStatus = Components.interfaces.nsISSLStatus; @@ -54,15 +54,15 @@ var security = { this.mapIssuerOrganization(cert.issuerOrganization) || cert.issuerName; var retval = { - hostName, + hostName : hostName, cAName : issuerName, encryptionAlgorithm : undefined, encryptionStrength : undefined, version: undefined, - isBroken, - isMixed, - isEV, - cert, + isBroken : isBroken, + isMixed : isMixed, + isEV : isEV, + cert : cert, certificateTransparency : undefined }; @@ -117,21 +117,21 @@ var security = { return retval; } return { - hostName, + hostName : hostName, cAName : "", encryptionAlgorithm : "", encryptionStrength : 0, version: "", - isBroken, - isMixed, - isEV, + isBroken : isBroken, + isMixed : isMixed, + isEV : isEV, cert : null, certificateTransparency : null }; }, // Find the secureBrowserUI object (if present) - _getSecurityUI() { + _getSecurityUI : function() { if (window.opener.gBrowser) return window.opener.gBrowser.securityUI; return null; @@ -140,7 +140,7 @@ var security = { // Interface for mapping a certificate issuer organization to // the value to be displayed. // Bug 82017 - this implementation should be moved to pipnss C++ code - mapIssuerOrganization(name) { + mapIssuerOrganization: function(name) { if (!name) return null; if (name == "RSA Data Security, Inc.") return "Verisign, Inc."; @@ -152,7 +152,7 @@ var security = { /** * Open the cookie manager window */ - viewCookies() + viewCookies : function() { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); @@ -181,7 +181,7 @@ var security = { /** * Open the login manager window */ - viewPasswords() { + viewPasswords : function() { LoginHelper.openPasswordManager(window, this._getSecurityInfo().hostName); }, diff --git a/browser/base/content/sanitize.js b/browser/base/content/sanitize.js index 53cf4e943d37..725daa64ed5a 100644 --- a/browser/base/content/sanitize.js +++ b/browser/base/content/sanitize.js @@ -38,14 +38,14 @@ function Sanitizer() { } Sanitizer.prototype = { // warning to the caller: this one may raise an exception (e.g. bug #265028) - clearItem(aItemName) + clearItem: function(aItemName) { this.items[aItemName].clear(); }, prefDomain: "", - getNameFromPreference(aPreferenceName) + getNameFromPreference: function(aPreferenceName) { return aPreferenceName.substr(this.prefDomain.length); }, @@ -516,7 +516,7 @@ Sanitizer.prototype = { openWindows: { privateStateForNewWindow: "non-private", - _canCloseWindow(aWindow) { + _canCloseWindow: function(aWindow) { if (aWindow.CanCloseWindow()) { // We already showed PermitUnload for the window, so let's // make sure we don't do it again when we actually close the @@ -526,7 +526,7 @@ Sanitizer.prototype = { } return false; }, - _resetAllWindowClosures(aWindowList) { + _resetAllWindowClosures: function(aWindowList) { for (let win of aWindowList) { win.skipNextCanClose = false; } diff --git a/browser/base/content/social-content.js b/browser/base/content/social-content.js index 071d057d522c..b5fa6a5c4bda 100644 --- a/browser/base/content/social-content.js +++ b/browser/base/content/social-content.js @@ -114,7 +114,7 @@ const SocialErrorListener = { webNav.loadURI(url, null, null, null, null); } sendAsyncMessage("Social:ErrorPageNotify", { - origin, + origin: origin, url: src }); }, diff --git a/browser/base/content/sync/aboutSyncTabs.js b/browser/base/content/sync/aboutSyncTabs.js index 731a0edfee81..e49411c7434f 100644 --- a/browser/base/content/sync/aboutSyncTabs.js +++ b/browser/base/content/sync/aboutSyncTabs.js @@ -23,7 +23,7 @@ if (AppConstants.MOZ_SERVICES_CLOUDSYNC) { var RemoteTabViewer = { _tabsList: null, - init() { + init: function() { Services.obs.addObserver(this, "weave:service:login:finish", false); Services.obs.addObserver(this, "weave:engine:sync:finish", false); @@ -34,14 +34,14 @@ var RemoteTabViewer = { this.buildList(true); }, - uninit() { + uninit: function() { Services.obs.removeObserver(this, "weave:service:login:finish"); Services.obs.removeObserver(this, "weave:engine:sync:finish"); Services.obs.removeObserver(this, "cloudsync:tabs:update"); }, - createItem(attrs) { + createItem: function(attrs) { let item = document.createElement("richlistitem"); // Copy the attributes from the argument into the item. @@ -56,7 +56,7 @@ var RemoteTabViewer = { return item; }, - filterTabs(event) { + filterTabs: function(event) { let val = event.target.value.toLowerCase(); let numTabs = this._tabsList.getRowCount(); let clientTabs = 0; @@ -89,7 +89,7 @@ var RemoteTabViewer = { } }, - openSelected() { + openSelected: function() { let items = this._tabsList.selectedItems; let urls = []; for (let i = 0; i < items.length; i++) { @@ -105,14 +105,14 @@ var RemoteTabViewer = { } }, - bookmarkSingleTab() { + bookmarkSingleTab: function() { let item = this._tabsList.selectedItems[0]; let uri = Weave.Utils.makeURI(item.getAttribute("url")); let title = item.getAttribute("title"); PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" - , uri - , title + , uri: uri + , title: title , hiddenRows: [ "description" , "location" , "loadInSidebar" @@ -120,7 +120,7 @@ var RemoteTabViewer = { }, window.top); }, - bookmarkSelectedTabs() { + bookmarkSelectedTabs: function() { let items = this._tabsList.selectedItems; let URIs = []; for (let i = 0; i < items.length; i++) { @@ -142,7 +142,7 @@ var RemoteTabViewer = { } }, - getIcon(iconUri, defaultIcon) { + getIcon: function(iconUri, defaultIcon) { try { let iconURI = Weave.Utils.makeURI(iconUri); return PlacesUtils.favicons.getFaviconLinkForIcon(iconURI).spec; @@ -158,7 +158,7 @@ var RemoteTabViewer = { _buildListRequested: false, - buildList(forceSync) { + buildList: function(forceSync) { if (this._waitingForBuildList) { this._buildListRequested = true; return; @@ -192,7 +192,7 @@ var RemoteTabViewer = { } }, - _clearTabList() { + _clearTabList: function() { let list = this._tabsList; // Clear out existing richlistitems. @@ -204,7 +204,7 @@ var RemoteTabViewer = { } }, - _generateWeaveTabList() { + _generateWeaveTabList: function() { let engine = Weave.Service.engineManager.get("tabs"); let list = this._tabsList; @@ -236,7 +236,7 @@ var RemoteTabViewer = { let attrs = { type: "tab", title: title || url, - url, + url: url, icon: this.getIcon(icon), } let tab = this.createItem(attrs); @@ -245,7 +245,7 @@ var RemoteTabViewer = { } }, - _generateCloudSyncTabList() { + _generateCloudSyncTabList: function() { let updateTabList = function(remoteTabs) { let list = this._tabsList; @@ -275,7 +275,7 @@ var RemoteTabViewer = { .then(updateTabList, Promise.reject.bind(Promise)); }, - adjustContextMenu(event) { + adjustContextMenu: function(event) { let mode = "all"; switch (this._tabsList.selectedItems.length) { case 0: @@ -300,7 +300,7 @@ var RemoteTabViewer = { } }, - _refetchTabs(force) { + _refetchTabs: function(force) { if (!force) { // Don't bother refetching tabs if we already did so recently let lastFetch = 0; @@ -325,7 +325,7 @@ var RemoteTabViewer = { return true; }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case "weave:service:login:finish": // A login has finished, which means that a Sync is about to start and @@ -346,7 +346,7 @@ var RemoteTabViewer = { } }, - handleClick(event) { + handleClick: function(event) { if (event.target.getAttribute("type") != "tab") { return; } diff --git a/browser/base/content/sync/genericChange.js b/browser/base/content/sync/genericChange.js index 5828e5dbb900..a9571b662f6d 100644 --- a/browser/base/content/sync/genericChange.js +++ b/browser/base/content/sync/genericChange.js @@ -136,7 +136,7 @@ var Change = { window.setTimeout(window.close, 1500); }, - onDialogAccept() { + onDialogAccept: function() { switch (this._dialogType) { case "UpdatePassphrase": case "ResetPassphrase": @@ -147,7 +147,7 @@ var Change = { return undefined; }, - doGeneratePassphrase() { + doGeneratePassphrase: function() { let passphrase = Weave.Utils.generatePassphrase(); this._passphraseBox.value = Weave.Utils.hyphenatePassphrase(passphrase); this._dialog.getButton("finish").disabled = false; @@ -201,7 +201,7 @@ var Change = { return false; }, - validate(event) { + validate: function(event) { let valid = false; let errorString = ""; diff --git a/browser/base/content/sync/setup.js b/browser/base/content/sync/setup.js index 9190263283a9..ab7f61001565 100644 --- a/browser/base/content/sync/setup.js +++ b/browser/base/content/sync/setup.js @@ -61,7 +61,7 @@ var gSyncSetup = { return document.getElementById("existingServer").selectedIndex == 0; }, - init() { + init: function() { let obs = [ ["weave:service:change-passphrase", "onResetPassphrase"], ["weave:service:login:start", "onLoginStart"], @@ -121,14 +121,14 @@ var gSyncSetup = { .getAttribute("accesskey"); }, - startNewAccountSetup() { + startNewAccountSetup: function() { if (!Weave.Utils.ensureMPUnlocked()) return; this._settingUpNew = true; this.wizard.pageIndex = NEW_ACCOUNT_START_PAGE; }, - useExistingAccount() { + useExistingAccount: function() { if (!Weave.Utils.ensureMPUnlocked()) return; this._settingUpNew = false; @@ -173,22 +173,22 @@ var gSyncSetup = { gSyncUtils.resetPassphrase(true); }, - onResetPassphrase() { + onResetPassphrase: function() { document.getElementById("existingPassphrase").value = Weave.Utils.hyphenatePassphrase(Weave.Service.identity.syncKey); this.checkFields(); this.wizard.advance(); }, - onLoginStart() { + onLoginStart: function() { this.toggleLoginFeedback(false); }, - onLoginEnd() { + onLoginEnd: function() { this.toggleLoginFeedback(true); }, - sendCredentialsAfterSync() { + sendCredentialsAfterSync: function() { let send = function() { Services.obs.removeObserver("weave:service:sync:finish", send); Services.obs.removeObserver("weave:service:sync:error", send); @@ -202,7 +202,7 @@ var gSyncSetup = { Services.obs.addObserver("weave:service:sync:error", send, false); }, - toggleLoginFeedback(stop) { + toggleLoginFeedback: function(stop) { document.getElementById("login-throbber").hidden = stop; let password = document.getElementById("existingPasswordFeedbackRow"); let server = document.getElementById("existingServerFeedbackRow"); @@ -231,7 +231,7 @@ var gSyncSetup = { this._setFeedbackMessage(feedback, false, Weave.Status.login); }, - setupInitialSync() { + setupInitialSync: function() { let action = document.getElementById("mergeChoiceRadio").selectedItem.id; switch (action) { case "resetClient": @@ -248,11 +248,11 @@ var gSyncSetup = { }, // fun with validation! - checkFields() { + checkFields: function() { this.wizard.canAdvance = this.readyToAdvance(); }, - readyToAdvance() { + readyToAdvance: function() { switch (this.wizard.pageIndex) { case INTRO_PAGE: return false; @@ -293,7 +293,7 @@ var gSyncSetup = { this.pin3.value.length == PIN_PART_LENGTH); }, - onEmailInput() { + onEmailInput: function() { // Check account validity when the user stops typing for 1 second. if (this._checkAccountTimer) window.clearTimeout(this._checkAccountTimer); @@ -302,7 +302,7 @@ var gSyncSetup = { }, 1000); }, - checkAccount() { + checkAccount: function() { delete this._checkAccountTimer; let value = Weave.Utils.normalizeAccount( document.getElementById("weaveEmail").value); @@ -337,7 +337,7 @@ var gSyncSetup = { this.checkFields(); }, - onPasswordChange() { + onPasswordChange: function() { let password = document.getElementById("weavePassword"); let pwconfirm = document.getElementById("weavePasswordConfirm"); let [valid, errorString] = gSyncUtils.validatePassword(password, pwconfirm); @@ -349,7 +349,7 @@ var gSyncSetup = { this.checkFields(); }, - onPageShow() { + onPageShow: function() { switch (this.wizard.pageIndex) { case PAIR_PAGE: this.wizard.getButton("back").hidden = true; @@ -420,7 +420,7 @@ var gSyncSetup = { } }, - onWizardAdvance() { + onWizardAdvance: function() { // Check pageIndex so we don't prompt before the Sync setup wizard appears. // This is a fallback in case the Master Password gets locked mid-wizard. if ((this.wizard.pageIndex >= 0) && @@ -509,7 +509,7 @@ var gSyncSetup = { return true; }, - onWizardBack() { + onWizardBack: function() { switch (this.wizard.pageIndex) { case NEW_ACCOUNT_START_PAGE: this.wizard.pageIndex = INTRO_PAGE; @@ -535,7 +535,7 @@ var gSyncSetup = { return true; }, - wizardFinish() { + wizardFinish: function() { this.setupInitialSync(); if (this.wizardType == "pair") { @@ -563,7 +563,7 @@ var gSyncSetup = { window.close(); }, - onWizardCancel() { + onWizardCancel: function() { if (this._resettingSync) return; @@ -572,12 +572,12 @@ var gSyncSetup = { Weave.Service.startOver(); }, - onSyncOptions() { + onSyncOptions: function() { this._beforeOptionsPage = this.wizard.pageIndex; this.wizard.pageIndex = OPTIONS_PAGE; }, - returnFromOptions() { + returnFromOptions: function() { this.wizard.getButton("next").label = this._nextButtonLabel; this.wizard.getButton("next").setAttribute("accesskey", this._nextButtonAccesskey); @@ -644,7 +644,7 @@ var gSyncSetup = { this._jpakeclient.controller = controller; }, - startEasySetup() { + startEasySetup: function() { // Don't do anything if we have a client already (e.g. we went to // Sync Options and just came back). if (this._jpakeclient) @@ -691,7 +691,7 @@ var gSyncSetup = { this._jpakeclient.receiveNoPIN(); }, - abortEasySetup() { + abortEasySetup: function() { document.getElementById("easySetupPIN1").value = ""; document.getElementById("easySetupPIN2").value = ""; document.getElementById("easySetupPIN3").value = ""; @@ -702,7 +702,7 @@ var gSyncSetup = { delete this._jpakeclient; }, - manualSetup() { + manualSetup: function() { this.abortEasySetup(); this.wizard.pageIndex = EXISTING_ACCOUNT_LOGIN_PAGE; }, @@ -710,7 +710,7 @@ var gSyncSetup = { // _handleNoScript is needed because it blocks the captcha. So we temporarily // allow the necessary sites so that we can verify the user is in fact a human. // This was done with the help of Giorgio (NoScript author). See bug 508112. - _handleNoScript(addExceptions) { + _handleNoScript: function(addExceptions) { // if NoScript isn't installed, or is disabled, bail out. let ns = Cc["@maone.net/noscript-service;1"]; if (ns == null) @@ -734,7 +734,7 @@ var gSyncSetup = { } }, - onExistingServerCommand() { + onExistingServerCommand: function() { let control = document.getElementById("existingServer"); if (control.selectedIndex == 0) { control.removeAttribute("editable"); @@ -750,7 +750,7 @@ var gSyncSetup = { this.checkFields(); }, - onExistingServerInput() { + onExistingServerInput: function() { // Check custom server validity when the user stops typing for 1 second. if (this._existingServerTimer) window.clearTimeout(this._existingServerTimer); @@ -759,7 +759,7 @@ var gSyncSetup = { }, 1000); }, - onServerCommand() { + onServerCommand: function() { setVisibility(document.getElementById("TOSRow"), this._usingMainServers); let control = document.getElementById("server"); if (!this._usingMainServers) { @@ -783,7 +783,7 @@ var gSyncSetup = { this.checkFields(); }, - onServerInput() { + onServerInput: function() { // Check custom server validity when the user stops typing for 1 second. if (this._checkServerTimer) window.clearTimeout(this._checkServerTimer); @@ -792,7 +792,7 @@ var gSyncSetup = { }, 1000); }, - checkServer() { + checkServer: function() { delete this._checkServerTimer; let el = document.getElementById("server"); let valid = false; @@ -813,7 +813,7 @@ var gSyncSetup = { this.checkFields(); }, - _validateServer(element) { + _validateServer: function(element) { let valid = false; let val = element.value; if (!val) @@ -859,7 +859,7 @@ var gSyncSetup = { return valid; }, - _handleChoice() { + _handleChoice: function() { let desc = document.getElementById("mergeChoiceRadio").selectedIndex; document.getElementById("chosenActionDeck").selectedIndex = desc; switch (desc) { @@ -983,7 +983,7 @@ var gSyncSetup = { // sets class and string on a feedback element // if no property string is passed in, we clear label/style - _setFeedback(element, success, string) { + _setFeedback: function(element, success, string) { element.hidden = success || !string; let classname = success ? "success" : "error"; let image = element.getElementsByAttribute("class", "statusIcon")[0]; @@ -993,7 +993,7 @@ var gSyncSetup = { }, // shim - _setFeedbackMessage(element, success, string) { + _setFeedbackMessage: function(element, success, string) { let str = ""; if (string) { try { @@ -1015,7 +1015,7 @@ var gSyncSetup = { } }, - onStateChange(webProgress, request, stateFlags, status) { + onStateChange: function(webProgress, request, stateFlags, status) { // We're only looking for the end of the frame load if ((stateFlags & Ci.nsIWebProgressListener.STATE_STOP) == 0) return; @@ -1029,10 +1029,10 @@ var gSyncSetup = { setVisibility(this.captchaBrowser, responseStatus != 404); // XXX TODO we should really log any responseStatus other than 200 }, - onProgressChange() {}, - onStatusChange() {}, - onSecurityChange() {}, - onLocationChange() {} + onProgressChange: function() {}, + onStatusChange: function() {}, + onSecurityChange: function() {}, + onLocationChange: function() {} }; // Define lazy getters for various XUL elements. diff --git a/browser/base/content/sync/utils.js b/browser/base/content/sync/utils.js index ea60ba1a0541..c49d4b3b71fb 100644 --- a/browser/base/content/sync/utils.js +++ b/browser/base/content/sync/utils.js @@ -22,7 +22,7 @@ var gSyncUtils = { }, // opens in a new window if we're in a modal prefwindow world, in a new tab otherwise - _openLink(url) { + _openLink: function(url) { let thisDocEl = document.documentElement, openerDocEl = window.opener && window.opener.document.documentElement; if (thisDocEl.id == "accountSetup" && window.opener && @@ -58,22 +58,22 @@ var gSyncUtils = { type, duringSetup); }, - changePassword() { + changePassword: function() { if (Weave.Utils.ensureMPUnlocked()) this.openChange("ChangePassword"); }, - resetPassphrase(duringSetup) { + resetPassphrase: function(duringSetup) { if (Weave.Utils.ensureMPUnlocked()) this.openChange("ResetPassphrase", duringSetup); }, - updatePassphrase() { + updatePassphrase: function() { if (Weave.Utils.ensureMPUnlocked()) this.openChange("UpdatePassphrase"); }, - resetPassword() { + resetPassword: function() { this._openLink(Weave.Service.pwResetURL); }, @@ -82,7 +82,7 @@ var gSyncUtils = { return Weave.Svc.Prefs.get(root + "termsURL"); }, - openToS() { + openToS: function() { this._openLink(this.tosURL); }, @@ -91,7 +91,7 @@ var gSyncUtils = { return Weave.Svc.Prefs.get(root + "privacyURL"); }, - openPrivacyPolicy() { + openPrivacyPolicy: function() { this._openLink(this.privacyPolicyURL); }, @@ -102,7 +102,7 @@ var gSyncUtils = { * @param elid : ID of the form element containing the passphrase. * @param callback : Function called once the iframe has loaded. */ - _preparePPiframe(elid, callback) { + _preparePPiframe: function(elid, callback) { let pp = document.getElementById(elid).value; // Create an invisible iframe whose contents we can print. @@ -137,7 +137,7 @@ var gSyncUtils = { * * @param elid : ID of the form element containing the passphrase. */ - passphrasePrint(elid) { + passphrasePrint: function(elid) { this._preparePPiframe(elid, function(iframe) { let webBrowserPrint = iframe.contentWindow .QueryInterface(Ci.nsIInterfaceRequestor) @@ -165,7 +165,7 @@ var gSyncUtils = { * * @param elid : ID of the form element containing the passphrase. */ - passphraseSave(elid) { + passphraseSave: function(elid) { let dialogTitle = this.bundle.GetStringFromName("save.recoverykey.title"); let defaultSaveName = this.bundle.GetStringFromName("save.recoverykey.defaultfilename"); this._preparePPiframe(elid, function(iframe) { @@ -203,7 +203,7 @@ var gSyncUtils = { * * returns [valid, errorString] */ - validatePassword(el1, el2) { + validatePassword: function(el1, el2) { let valid = false; let val1 = el1.value; let val2 = el2 ? el2.value : ""; diff --git a/browser/base/content/tab-content.js b/browser/base/content/tab-content.js index 67db5b5fc183..34eb58627207 100644 --- a/browser/base/content/tab-content.js +++ b/browser/base/content/tab-content.js @@ -27,7 +27,7 @@ XPCOMUtils.defineLazyGetter(this, "SimpleServiceDiscovery", function() { ssdp.registerDevice({ id: "roku:ecp", target: "roku:ecp", - factory(aService) { + factory: function(aService) { Cu.import("resource://gre/modules/RokuApp.jsm"); return new RokuApp(aService); }, @@ -98,13 +98,13 @@ addMessageListener("SecondScreen:tab-mirror", function(message) { if (app) { let width = content.innerWidth; let height = content.innerHeight; - let viewport = {cssWidth: width, cssHeight: height, width, height}; + let viewport = {cssWidth: width, cssHeight: height, width: width, height: height}; app.mirror(function() {}, content, viewport, function() {}, content); } }); var AboutHomeListener = { - init(chromeGlobal) { + init: function(chromeGlobal) { chromeGlobal.addEventListener('AboutHomeLoad', this, false, true); }, @@ -112,7 +112,7 @@ var AboutHomeListener = { return content.document.documentURI.toLowerCase() == "about:home"; }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { if (!this.isAboutHome) { return; } @@ -129,7 +129,7 @@ var AboutHomeListener = { } }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { if (!this.isAboutHome) { return; } @@ -140,7 +140,7 @@ var AboutHomeListener = { } }, - onUpdate(aData) { + onUpdate: function(aData) { let doc = content.document; if (aData.showRestoreLastSession && !PrivateBrowsingUtils.isContentWindowPrivate(content)) doc.getElementById("launcher").setAttribute("session", "true"); @@ -154,7 +154,7 @@ var AboutHomeListener = { docElt.setAttribute("snippetsVersion", aData.snippetsVersion); }, - onPageLoad() { + onPageLoad: function() { addMessageListener("AboutHome:Update", this); addEventListener("click", this, true); addEventListener("pagehide", this, true); @@ -163,7 +163,7 @@ var AboutHomeListener = { sendAsyncMessage("AboutHome:RequestUpdate"); }, - onClick(aEvent) { + onClick: function(aEvent) { if (!aEvent.isTrusted || // Don't trust synthetic events aEvent.button == 2 || aEvent.target.localName != "button") { return; @@ -210,7 +210,7 @@ var AboutHomeListener = { } }, - onPageHide(aEvent) { + onPageHide: function(aEvent) { if (aEvent.target.defaultView.frameElement) { return; } @@ -260,7 +260,7 @@ var AboutReaderListener = { _isLeavingReaderMode: false, - init() { + init: function() { addEventListener("AboutReaderContentLoaded", this, false, true); addEventListener("DOMContentLoaded", this, false); addEventListener("pageshow", this, false); @@ -269,7 +269,7 @@ var AboutReaderListener = { addMessageListener("Reader:PushState", this); }, - receiveMessage(message) { + receiveMessage: function(message) { switch (message.name) { case "Reader:ToggleReaderMode": if (!this.isAboutReader) { @@ -294,7 +294,7 @@ var AboutReaderListener = { return content.document.documentURI.startsWith("about:reader"); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { if (aEvent.originalTarget.defaultView != content) { return; } @@ -344,7 +344,7 @@ var AboutReaderListener = { * this is a suitable document). Calling it on things which won't be * painted is not going to work. */ - updateReaderButton(forceNonArticle) { + updateReaderButton: function(forceNonArticle) { if (!ReaderMode.isEnabledForParseOnLoad || this.isAboutReader || !content || !(content.document instanceof content.HTMLDocument) || content.document.mozSyntheticDocument) { @@ -354,14 +354,14 @@ var AboutReaderListener = { this.scheduleReadabilityCheckPostPaint(forceNonArticle); }, - cancelPotentialPendingReadabilityCheck() { + cancelPotentialPendingReadabilityCheck: function() { if (this._pendingReadabilityCheck) { removeEventListener("MozAfterPaint", this._pendingReadabilityCheck); delete this._pendingReadabilityCheck; } }, - scheduleReadabilityCheckPostPaint(forceNonArticle) { + scheduleReadabilityCheckPostPaint: function(forceNonArticle) { if (this._pendingReadabilityCheck) { // We need to stop this check before we re-add one because we don't know // if forceNonArticle was true or false last time. @@ -371,7 +371,7 @@ var AboutReaderListener = { addEventListener("MozAfterPaint", this._pendingReadabilityCheck); }, - onPaintWhenWaitedFor(forceNonArticle, event) { + onPaintWhenWaitedFor: function(forceNonArticle, event) { // In non-e10s, we'll get called for paints other than ours, and so it's // possible that this page hasn't been laid out yet, in which case we // should wait until we get an event that does relate to our layout. We @@ -401,18 +401,18 @@ var ContentSearchMediator = { "about:newtab", ]), - init(chromeGlobal) { + init: function(chromeGlobal) { chromeGlobal.addEventListener("ContentSearchClient", this, true, true); addMessageListener("ContentSearch", this); }, - handleEvent(event) { + handleEvent: function(event) { if (this._contentWhitelisted) { this._sendMsg(event.detail.type, event.detail.data); } }, - receiveMessage(msg) { + receiveMessage: function(msg) { if (msg.data.type == "AddToWhitelist") { for (let uri of msg.data.data) { this.whitelist.add(uri); @@ -429,18 +429,18 @@ var ContentSearchMediator = { return this.whitelist.has(content.document.documentURI); }, - _sendMsg(type, data = null) { + _sendMsg: function(type, data = null) { sendAsyncMessage("ContentSearch", { - type, - data, + type: type, + data: data, }); }, - _fireEvent(type, data = null) { + _fireEvent: function(type, data = null) { let event = Cu.cloneInto({ detail: { - type, - data, + type: type, + data: data, }, }, content); content.dispatchEvent(new content.CustomEvent("ContentSearchService", @@ -450,7 +450,7 @@ var ContentSearchMediator = { ContentSearchMediator.init(this); var PageStyleHandler = { - init() { + init: function() { addMessageListener("PageStyle:Switch", this); addMessageListener("PageStyle:Disable", this); addEventListener("pageshow", () => this.sendStyleSheetInfo()); @@ -460,23 +460,23 @@ var PageStyleHandler = { return docShell.contentViewer; }, - sendStyleSheetInfo() { + sendStyleSheetInfo: function() { let filteredStyleSheets = this._filterStyleSheets(this.getAllStyleSheets()); sendAsyncMessage("PageStyle:StyleSheets", { - filteredStyleSheets, + filteredStyleSheets: filteredStyleSheets, authorStyleDisabled: this.markupDocumentViewer.authorStyleDisabled, preferredStyleSheetSet: content.document.preferredStyleSheetSet }); }, - getAllStyleSheets(frameset = content) { + getAllStyleSheets: function(frameset = content) { let selfSheets = Array.slice(frameset.document.styleSheets); let subSheets = Array.map(frameset.frames, frame => this.getAllStyleSheets(frame)); return selfSheets.concat(...subSheets); }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "PageStyle:Switch": this.markupDocumentViewer.authorStyleDisabled = false; @@ -491,7 +491,7 @@ var PageStyleHandler = { this.sendStyleSheetInfo(); }, - _stylesheetSwitchAll(frameset, title) { + _stylesheetSwitchAll: function(frameset, title) { if (!title || this._stylesheetInFrame(frameset, title)) { this._stylesheetSwitchFrame(frameset, title); } @@ -502,7 +502,7 @@ var PageStyleHandler = { } }, - _stylesheetSwitchFrame(frame, title) { + _stylesheetSwitchFrame: function(frame, title) { var docStyleSheets = frame.document.styleSheets; for (let i = 0; i < docStyleSheets.length; ++i) { @@ -515,11 +515,11 @@ var PageStyleHandler = { } }, - _stylesheetInFrame(frame, title) { + _stylesheetInFrame: function(frame, title) { return Array.some(frame.document.styleSheets, (styleSheet) => styleSheet.title == title); }, - _filterStyleSheets(styleSheets) { + _filterStyleSheets: function(styleSheets) { let result = []; for (let currentStyleSheet of styleSheets) { @@ -661,13 +661,13 @@ let PrerenderContentHandler = { sendAsyncMessage("Prerender:Request", { href: aHref.spec, referrer: aReferrer ? aReferrer.spec : null, - id, + id: id, }); this._pending.push({ href: aHref, referrer: aReferrer, - id, + id: id, success: null, failure: null, }); @@ -699,12 +699,12 @@ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { } var WebBrowserChrome = { - onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) { + onBeforeLinkTraversal: function(originalTarget, linkURI, linkNode, isAppTab) { return BrowserUtils.onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab); }, // Check whether this URI should load in the current process - shouldLoadURI(aDocShell, aURI, aReferrer) { + shouldLoadURI: function(aDocShell, aURI, aReferrer) { if (!E10SUtils.shouldLoadURI(aDocShell, aURI, aReferrer)) { E10SUtils.redirectLoad(aDocShell, aURI, aReferrer); return false; @@ -713,23 +713,23 @@ var WebBrowserChrome = { return true; }, - shouldLoadURIInThisProcess(aURI) { + shouldLoadURIInThisProcess: function(aURI) { return E10SUtils.shouldLoadURIInThisProcess(aURI); }, // Try to reload the currently active or currently loading page in a new process. - reloadInFreshProcess(aDocShell, aURI, aReferrer) { + reloadInFreshProcess: function(aDocShell, aURI, aReferrer) { E10SUtils.redirectLoad(aDocShell, aURI, aReferrer, true); return true; }, - startPrerenderingDocument(aHref, aReferrer) { + startPrerenderingDocument: function(aHref, aReferrer) { if (PrerenderContentHandler.initialized) { PrerenderContentHandler.startPrerenderingDocument(aHref, aReferrer); } }, - shouldSwitchToPrerenderedDocument(aHref, aReferrer, aSuccess, aFailure) { + shouldSwitchToPrerenderedDocument: function(aHref, aReferrer, aSuccess, aFailure) { if (PrerenderContentHandler.initialized) { return PrerenderContentHandler.shouldSwitchToPrerenderedDocument( aHref, aReferrer, aSuccess, aFailure); @@ -747,7 +747,7 @@ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { var DOMFullscreenHandler = { - init() { + init: function() { addMessageListener("DOMFullscreen:Entered", this); addMessageListener("DOMFullscreen:CleanUp", this); addEventListener("MozDOMFullscreen:Request", this); @@ -765,7 +765,7 @@ var DOMFullscreenHandler = { .getInterface(Ci.nsIDOMWindowUtils); }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { let windowUtils = this._windowUtils; switch (aMessage.name) { case "DOMFullscreen:Entered": { @@ -793,7 +793,7 @@ var DOMFullscreenHandler = { } }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "MozDOMFullscreen:Request": { sendAsyncMessage("DOMFullscreen:Request"); diff --git a/browser/base/content/tabbrowser.xml b/browser/base/content/tabbrowser.xml index 2ccf6d8add39..f105ad15d024 100644 --- a/browser/base/content/tabbrowser.xml +++ b/browser/base/content/tabbrowser.xml @@ -566,18 +566,18 @@ // count of open requests (should always be 0 or 1) mRequestCount: 0, - destroy() { + destroy: function() { delete this.mTab; delete this.mBrowser; delete this.mTabBrowser; }, - _callProgressListeners() { + _callProgressListeners: function() { Array.unshift(arguments, this.mBrowser); return this.mTabBrowser._callProgressListeners.apply(this.mTabBrowser, arguments); }, - _shouldShowProgress(aRequest) { + _shouldShowProgress: function(aRequest) { if (this.mBlank) return false; @@ -591,9 +591,9 @@ return true; }, - onProgressChange(aWebProgress, aRequest, - aCurSelfProgress, aMaxSelfProgress, - aCurTotalProgress, aMaxTotalProgress) { + onProgressChange: function(aWebProgress, aRequest, + aCurSelfProgress, aMaxSelfProgress, + aCurTotalProgress, aMaxTotalProgress) { this.mTotalProgress = aMaxTotalProgress ? aCurTotalProgress / aMaxTotalProgress : 0; if (!this._shouldShowProgress(aRequest)) @@ -608,15 +608,15 @@ aCurTotalProgress, aMaxTotalProgress]); }, - onProgressChange64(aWebProgress, aRequest, - aCurSelfProgress, aMaxSelfProgress, - aCurTotalProgress, aMaxTotalProgress) { + onProgressChange64: function(aWebProgress, aRequest, + aCurSelfProgress, aMaxSelfProgress, + aCurTotalProgress, aMaxTotalProgress) { return this.onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress); }, - onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { if (!aRequest) return; @@ -757,8 +757,8 @@ this.mStatus = aStatus; }, - onLocationChange(aWebProgress, aRequest, aLocation, - aFlags) { + onLocationChange: function(aWebProgress, aRequest, aLocation, + aFlags) { // OnLocationChange is called for both the top-level content // and the subframes. let topLevel = aWebProgress.isTopLevel; @@ -838,7 +838,7 @@ } }, - onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) { if (this.mBlank) return; @@ -848,17 +848,17 @@ this.mMessage = aMessage; }, - onSecurityChange(aWebProgress, aRequest, aState) { + onSecurityChange: function(aWebProgress, aRequest, aState) { this._callProgressListeners("onSecurityChange", [aWebProgress, aRequest, aState]); }, - onRefreshAttempted(aWebProgress, aURI, aDelay, aSameURI) { + onRefreshAttempted: function(aWebProgress, aURI, aDelay, aSameURI) { return this._callProgressListeners("onRefreshAttempted", [aWebProgress, aURI, aDelay, aSameURI]); }, - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (aIID.equals(Components.interfaces.nsIWebProgressListener) || aIID.equals(Components.interfaces.nsIWebProgressListener2) || aIID.equals(Components.interfaces.nsISupportsWeakReference) || @@ -2072,7 +2072,7 @@ // No preloaded browser found, create one. browser = this._createBrowser({permanentKey: aTab.permanentKey, remoteType, - uriIsAboutBlank, + uriIsAboutBlank: uriIsAboutBlank, userContextId: aParams.userContextId, relatedBrowser: aParams.relatedBrowser, opener: aParams.opener, @@ -2124,7 +2124,7 @@ var evt = new CustomEvent("TabBrowserInserted", { bubbles: true, detail: {} }); aTab.dispatchEvent(evt); - return { usingPreloadedContent }; + return { usingPreloadedContent: usingPreloadedContent }; ]]> @@ -3661,7 +3661,7 @@ // Wraps nsITimer. Must not use the vanilla setTimeout and // clearTimeout, because they will be blocked by nsIPromptService // dialogs. - setTimer(callback, timeout) { + setTimer: function(callback, timeout) { let event = { notify: callback }; @@ -3672,11 +3672,11 @@ return timer; }, - clearTimer(timer) { + clearTimer: function(timer) { timer.cancel(); }, - getTabState(tab) { + getTabState: function(tab) { let state = this.tabState.get(tab); if (state === undefined) { return this.STATE_UNLOADED; @@ -3692,7 +3692,7 @@ } }, - setTabState(tab, state) { + setTabState: function(tab, state) { this.setTabStateNoAction(tab, state); let browser = tab.linkedBrowser; @@ -3715,7 +3715,7 @@ return window.windowState == window.STATE_MINIMIZED; }, - init() { + init: function() { this.log("START"); // If we minimized the window before the switcher was activated, @@ -3735,7 +3735,7 @@ } }, - destroy() { + destroy: function() { if (this.unloadTimer) { this.clearTimer(this.unloadTimer); this.unloadTimer = null; @@ -3761,7 +3761,7 @@ this.activeSuppressDisplayport.clear(); }, - finish() { + finish: function() { this.log("FINISH"); this.assert(this.tabbrowser._switcher); @@ -3796,7 +3796,7 @@ // This function is called after all the main state changes to // make sure we display the right tab. - updateDisplay() { + updateDisplay: function() { // Figure out which tab we actually want visible right now. let showTab = null; if (this.getTabState(this.requestedTab) != this.STATE_LOADED && @@ -3855,7 +3855,7 @@ this.lastVisibleTab = this.visibleTab; }, - assert(cond) { + assert: function(cond) { if (!cond) { dump("Assertion failure\n" + Error().stack); @@ -3867,7 +3867,7 @@ }, // We've decided to try to load requestedTab. - loadRequestedTab() { + loadRequestedTab: function() { this.assert(!this.loadTimer); this.assert(!this.minimized); @@ -3882,7 +3882,7 @@ // This function runs before every event. It fixes up the state // to account for closed tabs. - preActions() { + preActions: function() { this.assert(this.tabbrowser._switcher); this.assert(this.tabbrowser._switcher === this); @@ -3910,7 +3910,7 @@ // tab. It's expected that we've already updated all the principal // state variables. This function takes care of updating any auxilliary // state. - postActions() { + postActions: function() { // Once we finish loading loadingTab, we null it out. So the state should // always be LOADING. this.assert(!this.loadingTab || @@ -3962,7 +3962,7 @@ }, // Fires when we're ready to unload unused tabs. - onUnloadTimeout() { + onUnloadTimeout: function() { this.logState("onUnloadTimeout"); this.unloadTimer = null; this.preActions(); @@ -3998,7 +3998,7 @@ }, // Fires when an ongoing load has taken too long. - onLoadTimeout() { + onLoadTimeout: function() { this.logState("onLoadTimeout"); this.preActions(); this.loadTimer = null; @@ -4007,7 +4007,7 @@ }, // Fires when the layers become available for a tab. - onLayersReady(browser) { + onLayersReady: function(browser) { let tab = this.tabbrowser.getTabForBrowser(browser); this.logState(`onLayersReady(${tab._tPos})`); @@ -4027,13 +4027,13 @@ // Fires when we paint the screen. Any tab switches we initiated // previously are done, so there's no need to keep the old layers // around. - onPaint() { + onPaint: function() { this.maybeVisibleTabs.clear(); this.maybeFinishTabSwitch(); }, // Called when we're done clearing the layers for a tab. - onLayersCleared(browser) { + onLayersCleared: function(browser) { let tab = this.tabbrowser.getTabForBrowser(browser); if (tab) { this.logState(`onLayersCleared(${tab._tPos})`); @@ -4046,7 +4046,7 @@ // Called when a tab switches from remote to non-remote. In this case // a MozLayerTreeReady notification that we requested may never fire, // so we need to simulate it. - onRemotenessChange(tab) { + onRemotenessChange: function(tab) { this.logState(`onRemotenessChange(${tab._tPos}, ${tab.linkedBrowser.isRemoteBrowser})`); if (!tab.linkedBrowser.isRemoteBrowser) { if (this.getTabState(tab) == this.STATE_LOADING) { @@ -4059,7 +4059,7 @@ // Called when a tab has been removed, and the browser node is // about to be removed from the DOM. - onTabRemoved(tab) { + onTabRemoved: function(tab) { if (this.lastVisibleTab == tab) { // The browser that was being presented to the user is // going to be removed during this tick of the event loop. @@ -4152,7 +4152,7 @@ }, // Called when the user asks to switch to a given tab. - requestTab(tab) { + requestTab: function(tab) { if (tab === this.requestedTab) { return; } @@ -4179,7 +4179,7 @@ this.postActions(); }, - handleEvent(event, delayed = false) { + handleEvent: function(event, delayed = false) { if (this._processing) { this.setTimer(() => this.handleEvent(event, true), 0); return; @@ -4217,7 +4217,7 @@ * timing. */ - startTabSwitch() { + startTabSwitch: function() { TelemetryStopwatch.cancel("FX_TAB_SWITCH_TOTAL_E10S_MS", window); TelemetryStopwatch.start("FX_TAB_SWITCH_TOTAL_E10S_MS", window); this.addMarker("AsyncTabSwitch:Start"); @@ -4230,7 +4230,7 @@ * are hidden). This checks to make sure all conditions are * satisfied, and then records the tab switch as finished. */ - maybeFinishTabSwitch() { + maybeFinishTabSwitch: function() { if (this.switchInProgress && this.requestedTab && this.getTabState(this.requestedTab) == this.STATE_LOADED) { // After this point the tab has switched from the content thread's point of view. @@ -4245,7 +4245,7 @@ } }, - spinnerDisplayed() { + spinnerDisplayed: function() { this.assert(!this.spinnerTab); TelemetryStopwatch.start("FX_TAB_SWITCH_SPINNER_VISIBLE_MS", window); // We have a second, similar probe for capturing recordings of @@ -4254,7 +4254,7 @@ this.addMarker("AsyncTabSwitch:SpinnerShown"); }, - spinnerHidden() { + spinnerHidden: function() { this.assert(this.spinnerTab); this.log("DEBUG: spinner time = " + TelemetryStopwatch.timeElapsed("FX_TAB_SWITCH_SPINNER_VISIBLE_MS", window)); @@ -4265,7 +4265,7 @@ this.maybeFinishTabSwitch(); }, - addMarker(marker) { + addMarker: function(marker) { if (Services.profiler) { Services.profiler.AddMarker(marker); } @@ -4278,7 +4278,7 @@ _useDumpForLogging: false, _logInit: false, - logging() { + logging: function() { if (this._useDumpForLogging) return true; if (this._logInit) @@ -4293,14 +4293,14 @@ return this._shouldLog; }, - tinfo(tab) { + tinfo: function(tab) { if (tab) { return tab._tPos + "(" + tab.linkedBrowser.currentURI.spec + ")"; } return "null"; }, - log(s) { + log: function(s) { if (!this.logging()) return; if (this._useDumpForLogging) { @@ -4310,7 +4310,7 @@ } }, - logState(prefix) { + logState: function(prefix) { if (!this.logging()) return; @@ -4721,13 +4721,13 @@ gContextMenuContentData = { isRemote: true, event: aMessage.objects.event, popupNode: aMessage.objects.popupNode, - browser, + browser: browser, editFlags: data.editFlags, - spellInfo, + spellInfo: spellInfo, principal: data.principal, customMenuItems: data.customMenuItems, addonInfo: data.addonInfo, - documentURIObject, + documentURIObject: documentURIObject, docLocation: data.docLocation, charSet: data.charSet, referrer: data.referrer, @@ -5127,14 +5127,14 @@ self: this, childNodes: [null, this.tabContextMenu, this.tabContainer], firstChild: { nextSibling: this.tabContextMenu }, - getElementsByAttribute(attr, attrValue) { + getElementsByAttribute: function(attr, attrValue) { if (attr == "anonid" && attrValue == "tabContextMenu") return [this.self.tabContextMenu]; return []; }, // Also support adding event listeners (forward to the tab container) - addEventListener(a, b, c) { this.self.tabContainer.addEventListener(a, b, c); }, - removeEventListener(a, b, c) { this.self.tabContainer.removeEventListener(a, b, c); } + addEventListener: function(a, b, c) { this.self.tabContainer.addEventListener(a, b, c); }, + removeEventListener: function(a, b, c) { this.self.tabContainer.removeEventListener(a, b, c); } }); ]]> diff --git a/browser/base/content/test/general/browser_aboutAccounts.js b/browser/base/content/test/general/browser_aboutAccounts.js index 173ac8c52fde..c825c91cd02d 100644 --- a/browser/base/content/test/general/browser_aboutAccounts.js +++ b/browser/base/content/test/general/browser_aboutAccounts.js @@ -36,11 +36,11 @@ registerCleanupFunction(function() { var gTests = [ { desc: "Test the remote commands", - *teardown() { + teardown: function* () { gBrowser.removeCurrentTab(); yield signOut(); }, - *run() + run: function* () { setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/browser/browser/base/content/test/general/accounts_testRemoteCommands.html"); @@ -76,7 +76,7 @@ var gTests = [ { desc: "Test action=signin - no user logged in", teardown: () => gBrowser.removeCurrentTab(), - *run() + run: function* () { // When this loads with no user logged-in, we expect the "normal" URL const expected_url = "https://example.com/?is_sign_in"; @@ -95,11 +95,11 @@ var gTests = [ }, { desc: "Test action=signin - user logged in", - *teardown() { + teardown: function* () { gBrowser.removeCurrentTab(); yield signOut(); }, - *run() + run: function* () { // When this loads with a user logged-in, we expect the normal URL to // have been ignored and the "manage" page to be shown. @@ -124,7 +124,7 @@ var gTests = [ { desc: "Test action=signin - captive portal", teardown: () => gBrowser.removeCurrentTab(), - *run() + run: function* () { const signinUrl = "https://redirproxy.example.com/test"; setPref("identity.fxaccounts.remote.signin.uri", signinUrl); @@ -144,7 +144,7 @@ var gTests = [ gBrowser.removeCurrentTab(); BrowserOffline.toggleOfflineStatus(); }, - *run() + run: function* () { BrowserOffline.toggleOfflineStatus(); Services.cache2.clear(); @@ -164,7 +164,7 @@ var gTests = [ { desc: "Test action=signup - no user logged in", teardown: () => gBrowser.removeCurrentTab(), - *run() + run: function* () { const expected_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", expected_url); @@ -183,7 +183,7 @@ var gTests = [ { desc: "Test action=signup - user logged in", teardown: () => gBrowser.removeCurrentTab(), - *run() + run: function* () { const expected_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", expected_url); @@ -202,11 +202,11 @@ var gTests = [ }, { desc: "Test action=reauth", - *teardown() { + teardown: function* () { gBrowser.removeCurrentTab(); yield signOut(); }, - *run() + run: function* () { const expected_url = "https://example.com/?is_force_auth"; setPref("identity.fxaccounts.remote.force_auth.uri", expected_url); @@ -220,11 +220,11 @@ var gTests = [ }, { desc: "Test with migrateToDevEdition enabled (success)", - *teardown() { + teardown: function* () { gBrowser.removeCurrentTab(); yield signOut(); }, - *run() + run: function* () { let fxAccountsCommon = {}; Cu.import("resource://gre/modules/FxAccountsCommon.js", fxAccountsCommon); @@ -281,11 +281,11 @@ var gTests = [ }, { desc: "Test with migrateToDevEdition enabled (no user to migrate)", - *teardown() { + teardown: function* () { gBrowser.removeCurrentTab(); yield signOut(); }, - *run() + run: function* () { const pref = "identity.fxaccounts.migrateToDevEdition"; changedPrefs.add(pref); @@ -321,10 +321,10 @@ var gTests = [ }, { desc: "Test observers about:accounts", - teardown() { + teardown: function() { gBrowser.removeCurrentTab(); }, - *run() { + run: function* () { setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/"); yield setSignedInUser(); let tab = yield promiseNewTabLoadEvent("about:accounts"); @@ -339,7 +339,7 @@ var gTests = [ { desc: "Test entrypoint query string, no action, no user logged in", teardown: () => gBrowser.removeCurrentTab(), - *run() { + run: function* () { // When this loads with no user logged-in, we expect the "normal" URL setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/"); let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?entrypoint=abouthome"); @@ -349,7 +349,7 @@ var gTests = [ { desc: "Test entrypoint query string for signin", teardown: () => gBrowser.removeCurrentTab(), - *run() { + run: function* () { // When this loads with no user logged-in, we expect the "normal" URL const expected_url = "https://example.com/?is_sign_in"; setPref("identity.fxaccounts.remote.signin.uri", expected_url); @@ -360,7 +360,7 @@ var gTests = [ { desc: "Test entrypoint query string for signup", teardown: () => gBrowser.removeCurrentTab(), - *run() { + run: function* () { // When this loads with no user logged-in, we expect the "normal" URL const sign_up_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", sign_up_url); @@ -374,7 +374,7 @@ var gTests = [ teardown() { gBrowser.removeCurrentTab(); }, - *run() { + run: function* () { let signupURL = "https://example.com/"; setPref("identity.fxaccounts.remote.signup.uri", signupURL); let queryStr = "email=foo%40example.com&foo=bar&baz=quux"; @@ -390,7 +390,7 @@ var gTests = [ teardown() { gBrowser.removeCurrentTab(); }, - *run() { + run: function* () { let signupURL = "https://example.com/?param"; setPref("identity.fxaccounts.remote.signup.uri", signupURL); let queryStr = "email=foo%40example.com&foo=bar&baz=quux"; @@ -472,7 +472,7 @@ function checkVisibilities(tab, data) { } deferred.resolve(); }); - mm.sendAsyncMessage("test:check-visibilities", {ids}); + mm.sendAsyncMessage("test:check-visibilities", {ids: ids}); return deferred.promise; } diff --git a/browser/base/content/test/general/browser_aboutHealthReport.js b/browser/base/content/test/general/browser_aboutHealthReport.js index 2b7eb1b08741..4027db223feb 100644 --- a/browser/base/content/test/general/browser_aboutHealthReport.js +++ b/browser/base/content/test/general/browser_aboutHealthReport.js @@ -68,7 +68,7 @@ var gTests = [ Preferences.set("datareporting.healthreport.about.reportUrl", HTTPS_BASE + "healthreport_testRemoteCommands.html"); }), - run(iframe) + run: function(iframe) { let deferred = Promise.defer(); let results = 0; diff --git a/browser/base/content/test/general/browser_aboutHome.js b/browser/base/content/test/general/browser_aboutHome.js index cf9ed841e481..ba5abf34732c 100644 --- a/browser/base/content/test/general/browser_aboutHome.js +++ b/browser/base/content/test/general/browser_aboutHome.js @@ -495,7 +495,7 @@ add_task(function* () { let oldOpenPrefs = window.openPreferences; let openPrefsPromise = new Promise(resolve => { window.openPreferences = function(pane, params) { - resolve({ pane, params }); + resolve({ pane: pane, params: params }); }; }); @@ -647,7 +647,7 @@ function promiseNewEngine(basename) { return new Promise((resolve, reject) => { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess(engine) { + onSuccess: function(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => { try { @@ -656,7 +656,7 @@ function promiseNewEngine(basename) { }); resolve(engine); }, - onError(errCode) { + onError: function(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/general/browser_alltabslistener.js b/browser/base/content/test/general/browser_alltabslistener.js index 622be9cd2eab..da5e8ddd1933 100644 --- a/browser/base/content/test/general/browser_alltabslistener.js +++ b/browser/base/content/test/general/browser_alltabslistener.js @@ -4,12 +4,12 @@ const gCompleteState = Ci.nsIWebProgressListener.STATE_STOP + Ci.nsIWebProgressListener.STATE_IS_NETWORK; var gFrontProgressListener = { - onProgressChange(aWebProgress, aRequest, + onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { }, - onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { var state = "onStateChange"; info("FrontProgress: " + state + " 0x" + aStateFlags.toString(16)); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -17,7 +17,7 @@ var gFrontProgressListener = { gFrontNotificationsPos++; }, - onLocationChange(aWebProgress, aRequest, aLocationURI, aFlags) { + onLocationChange: function(aWebProgress, aRequest, aLocationURI, aFlags) { var state = "onLocationChange"; info("FrontProgress: " + state + " " + aLocationURI.spec); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -25,10 +25,10 @@ var gFrontProgressListener = { gFrontNotificationsPos++; }, - onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) { }, - onSecurityChange(aWebProgress, aRequest, aState) { + onSecurityChange: function(aWebProgress, aRequest, aState) { var state = "onSecurityChange"; info("FrontProgress: " + state + " 0x" + aState.toString(16)); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -38,7 +38,7 @@ var gFrontProgressListener = { } var gAllProgressListener = { - onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { var state = "onStateChange"; info("AllProgress: " + state + " 0x" + aStateFlags.toString(16)); ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); @@ -53,7 +53,7 @@ var gAllProgressListener = { } }, - onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, + onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) { var state = "onLocationChange"; info("AllProgress: " + state + " " + aLocationURI.spec); @@ -63,12 +63,12 @@ var gAllProgressListener = { gAllNotificationsPos++; }, - onStatusChange(aBrowser, aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange: function(aBrowser, aWebProgress, aRequest, aStatus, aMessage) { var state = "onStatusChange"; ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); }, - onSecurityChange(aBrowser, aWebProgress, aRequest, aState) { + onSecurityChange: function(aBrowser, aWebProgress, aRequest, aState) { var state = "onSecurityChange"; info("AllProgress: " + state + " 0x" + aState.toString(16)); ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); diff --git a/browser/base/content/test/general/browser_blockHPKP.js b/browser/base/content/test/general/browser_blockHPKP.js index d470a219f58d..47106cbb4623 100644 --- a/browser/base/content/test/general/browser_blockHPKP.js +++ b/browser/base/content/test/general/browser_blockHPKP.js @@ -60,7 +60,7 @@ function loadPinningPage() { // After the site is pinned try to load with a subdomain site that should // fail to validate var successfulPinningPageListener = { - handleEvent() { + handleEvent: function() { gBrowser.selectedBrowser.removeEventListener("load", this, true); BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kBadPinningDomain).then(function() { return promiseErrorPageLoaded(gBrowser.selectedBrowser); diff --git a/browser/base/content/test/general/browser_bug321000.js b/browser/base/content/test/general/browser_bug321000.js index a65b2703ee91..b30b7101d568 100644 --- a/browser/base/content/test/general/browser_bug321000.js +++ b/browser/base/content/test/general/browser_bug321000.js @@ -49,7 +49,7 @@ function test_paste(aCurrentTest) { // Register input listener. var inputListener = { test: aCurrentTest, - handleEvent(event) { + handleEvent: function(event) { element.removeEventListener(event.type, this, false); is(element.value, this.test.expected, this.test.desc); diff --git a/browser/base/content/test/general/browser_bug356571.js b/browser/base/content/test/general/browser_bug356571.js index 8af6b4a79003..1bfa73ea1587 100644 --- a/browser/base/content/test/general/browser_bug356571.js +++ b/browser/base/content/test/general/browser_bug356571.js @@ -15,7 +15,7 @@ const kPromptServiceFactory = Cm.getClassObject(Cc[kPromptServiceContractID], Ci.nsIFactory); var fakePromptServiceFactory = { - createInstance(aOuter, aIid) { + createInstance: function(aOuter, aIid) { if (aOuter != null) throw Cr.NS_ERROR_NO_AGGREGATION; return promptService.QueryInterface(aIid); @@ -24,7 +24,7 @@ var fakePromptServiceFactory = { var promptService = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]), - alert() { + alert: function() { didFail = true; } }; @@ -47,7 +47,7 @@ const kURIs = [ var gProgressListener = { _runCount: 0, - onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { if ((aStateFlags & kCompleteState) == kCompleteState) { if (++this._runCount != kURIs.length) return; diff --git a/browser/base/content/test/general/browser_bug424101.js b/browser/base/content/test/general/browser_bug424101.js index 501448b8d399..8000d2ae9d5e 100644 --- a/browser/base/content/test/general/browser_bug424101.js +++ b/browser/base/content/test/general/browser_bug424101.js @@ -24,7 +24,7 @@ add_task(function *() { let test = tests[index]; yield ContentTask.spawn(gBrowser.selectedBrowser, - { element: test.element, type: test.type, index }, + { element: test.element, type: test.type, index: index }, function* (arg) { let element = content.document.createElement(arg.element); element.id = "element" + arg.index; diff --git a/browser/base/content/test/general/browser_bug553455.js b/browser/base/content/test/general/browser_bug553455.js index e3bfc7854492..b6004e0d3e5d 100644 --- a/browser/base/content/test/general/browser_bug553455.js +++ b/browser/base/content/test/general/browser_bug553455.js @@ -152,13 +152,13 @@ function waitForInstallDialog() { let window = yield new Promise(resolve => { Services.wm.addListener({ - onOpenWindow(aXULWindow) { + onOpenWindow: function(aXULWindow) { Services.wm.removeListener(this); resolve(aXULWindow); }, - onCloseWindow(aXULWindow) { + onCloseWindow: function(aXULWindow) { }, - onWindowTitleChange(aXULWindow, aNewTitle) { + onWindowTitleChange: function(aXULWindow, aNewTitle) { } }); }); @@ -1055,7 +1055,7 @@ function test_cancel() { let install = notification.notification.options.installs[0]; let cancelledPromise = new Promise(resolve => { install.addListener({ - onDownloadCancelled() { + onDownloadCancelled: function() { install.removeListener(this); resolve(); } @@ -1124,7 +1124,7 @@ function test_failedSecurity() { var gTestStart = null; var XPInstallObserver = { - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo); info("Observed " + aTopic + " for " + installInfo.installs.length + " installs"); installInfo.installs.forEach(function(aInstall) { diff --git a/browser/base/content/test/general/browser_bug561636.js b/browser/base/content/test/general/browser_bug561636.js index 585800b9e4c7..19e816716faf 100644 --- a/browser/base/content/test/general/browser_bug561636.js +++ b/browser/base/content/test/general/browser_bug561636.js @@ -17,7 +17,7 @@ function checkPopupHide() var gObserver = { QueryInterface : XPCOMUtils.generateQI([Ci.nsIFormSubmitObserver]), - notifyInvalidSubmit(aFormElement, aInvalidElements) + notifyInvalidSubmit : function(aFormElement, aInvalidElements) { } }; diff --git a/browser/base/content/test/general/browser_bug592338.js b/browser/base/content/test/general/browser_bug592338.js index 3744f26e4814..ca9cc361a84e 100644 --- a/browser/base/content/test/general/browser_bug592338.js +++ b/browser/base/content/test/general/browser_bug592338.js @@ -144,7 +144,7 @@ function test() { AddonManager.getInstallForURL(TESTROOT + "theme.xpi", function(aInstall) { aInstall.addListener({ - onInstallEnded() { + onInstallEnded: function() { AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(aAddon) { isnot(aAddon, null, "Should have installed the test theme."); diff --git a/browser/base/content/test/general/browser_bug676619.js b/browser/base/content/test/general/browser_bug676619.js index 4e3341d76ca3..a5f49f0d423e 100644 --- a/browser/base/content/test/general/browser_bug676619.js +++ b/browser/base/content/test/general/browser_bug676619.js @@ -64,7 +64,7 @@ function test() { function addWindowListener(aURL, aCallback) { Services.wm.addListener({ - onOpenWindow(aXULWindow) { + onOpenWindow: function(aXULWindow) { info("window opened, waiting for focus"); Services.wm.removeListener(this); @@ -75,8 +75,8 @@ function addWindowListener(aURL, aCallback) { aCallback(domwindow); }, domwindow); }, - onCloseWindow(aXULWindow) { }, - onWindowTitleChange(aXULWindow, aNewTitle) { } + onCloseWindow: function(aXULWindow) { }, + onWindowTitleChange: function(aXULWindow, aNewTitle) { } }); } @@ -98,7 +98,7 @@ TabOpenListener.prototype = { tab: null, browser: null, - handleEvent(event) { + handleEvent: function(event) { if (event.type == "TabOpen") { gBrowser.tabContainer.removeEventListener("TabOpen", this, false); this.tab = event.originalTarget; diff --git a/browser/base/content/test/general/browser_bug734076.js b/browser/base/content/test/general/browser_bug734076.js index 4f0eda31083c..d7aca0250f09 100644 --- a/browser/base/content/test/general/browser_bug734076.js +++ b/browser/base/content/test/general/browser_bug734076.js @@ -15,15 +15,15 @@ add_task(function* () name: "view background image", url: "http://mochi.test:8888/", element: "body", - go() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { + go: function() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { let contentBody = content.document.body; contentBody.style.backgroundImage = "url('" + arg.writeDomainURL + "')"; return "context-viewbgimage"; }); }, - verify() { + verify: function() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for view background image"); @@ -34,8 +34,8 @@ add_task(function* () name: "view image", url: "http://mochi.test:8888/", element: "img", - go() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { + go: function() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { let doc = content.document; let img = doc.createElement("img"); img.height = 100; @@ -46,7 +46,7 @@ add_task(function* () return "context-viewimage"; }); }, - verify() { + verify: function() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for view image"); @@ -57,8 +57,8 @@ add_task(function* () name: "show only this frame", url: "http://mochi.test:8888/", element: "iframe", - go() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { + go: function() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { let doc = content.document; let iframe = doc.createElement("iframe"); iframe.setAttribute("src", arg.writeDomainURL); @@ -73,7 +73,7 @@ add_task(function* () }); }); }, - verify() { + verify: function() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for 'show only this frame'"); diff --git a/browser/base/content/test/general/browser_contentAltClick.js b/browser/base/content/test/general/browser_contentAltClick.js index bce845ca7148..f6922b9efd6f 100644 --- a/browser/base/content/test/general/browser_contentAltClick.js +++ b/browser/base/content/test/general/browser_contentAltClick.js @@ -54,7 +54,7 @@ add_task(function* test_alt_click() // When 1 download has been attempted then resolve the promise. let finishedAllDownloads = new Promise( (resolve) => { downloadView = { - onDownloadAdded(aDownload) { + onDownloadAdded: function(aDownload) { downloads.push(aDownload); resolve(); }, @@ -83,7 +83,7 @@ add_task(function* test_alt_click_on_xlinks() // When all 2 downloads have been attempted then resolve the promise. let finishedAllDownloads = new Promise( (resolve) => { downloadView = { - onDownloadAdded(aDownload) { + onDownloadAdded: function(aDownload) { downloads.push(aDownload); if (downloads.length == 2) { resolve(); diff --git a/browser/base/content/test/general/browser_contentAreaClick.js b/browser/base/content/test/general/browser_contentAreaClick.js index db91dd11c71c..921416b82385 100644 --- a/browser/base/content/test/general/browser_contentAreaClick.js +++ b/browser/base/content/test/general/browser_contentAreaClick.js @@ -18,8 +18,8 @@ var gTests = [ { desc: "Simple left click", - setup() {}, - clean() {}, + setup: function() {}, + clean: function() {}, event: {}, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [], @@ -28,8 +28,8 @@ var gTests = [ { desc: "Ctrl/Cmd left click", - setup() {}, - clean() {}, + setup: function() {}, + clean: function() {}, event: { ctrlKey: true, metaKey: true }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], @@ -41,10 +41,10 @@ var gTests = [ // just be like Alt click. { desc: "Shift+Alt left click", - setup() { + setup: function() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean() { + clean: function() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { shiftKey: true, @@ -56,10 +56,10 @@ var gTests = [ { desc: "Shift+Alt left click on XLinks", - setup() { + setup: function() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean() { + clean: function() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { shiftKey: true, @@ -71,8 +71,8 @@ var gTests = [ { desc: "Shift click", - setup() {}, - clean() {}, + setup: function() {}, + clean: function() {}, event: { shiftKey: true }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ], @@ -81,10 +81,10 @@ var gTests = [ { desc: "Alt click", - setup() { + setup: function() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean() { + clean: function() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { altKey: true }, @@ -95,10 +95,10 @@ var gTests = [ { desc: "Alt click on XLinks", - setup() { + setup: function() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean() { + clean: function() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { altKey: true }, @@ -109,8 +109,8 @@ var gTests = [ { desc: "Panel click", - setup() {}, - clean() {}, + setup: function() {}, + clean: function() {}, event: {}, targets: [ "panellink" ], expectedInvokedMethods: [ "urlSecurityCheck", "loadURI" ], @@ -119,8 +119,8 @@ var gTests = [ { desc: "Simple middle click opentab", - setup() {}, - clean() {}, + setup: function() {}, + clean: function() {}, event: { button: 1 }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ], @@ -129,10 +129,10 @@ var gTests = [ { desc: "Simple middle click openwin", - setup() { + setup: function() { gPrefService.setBoolPref("browser.tabs.opentabfor.middleclick", false); }, - clean() { + clean: function() { gPrefService.clearUserPref("browser.tabs.opentabfor.middleclick"); }, event: { button: 1 }, @@ -143,11 +143,11 @@ var gTests = [ { desc: "Middle mouse paste", - setup() { + setup: function() { gPrefService.setBoolPref("middlemouse.contentLoadURL", true); gPrefService.setBoolPref("general.autoScroll", false); }, - clean() { + clean: function() { gPrefService.clearUserPref("middlemouse.contentLoadURL"); gPrefService.clearUserPref("general.autoScroll"); }, @@ -199,7 +199,7 @@ function test() { // Click handler used to steal click events. var gClickHandler = { - handleEvent(event) { + handleEvent: function(event) { let linkId = event.target.id || event.target.localName; is(event.type, "click", gCurrentTest.desc + ":Handler received a click event on " + linkId); diff --git a/browser/base/content/test/general/browser_contentSearchUI.js b/browser/base/content/test/general/browser_contentSearchUI.js index 9dc5fbcfb612..aa346ed2cedd 100644 --- a/browser/base/content/test/general/browser_contentSearchUI.js +++ b/browser/base/content/test/general/browser_contentSearchUI.js @@ -195,28 +195,28 @@ add_task(function* cycleSuggestions() { accelKey: true, }; - let state = yield msg("key", { key: "VK_DOWN", modifiers }); + let state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); }); @@ -249,22 +249,22 @@ add_task(function* cycleOneOffs() { altKey: true, }; - state = yield msg("key", { key: "VK_DOWN", modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); - state = yield msg("key", { key: "VK_DOWN", modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); - state = yield msg("key", { key: "VK_DOWN", modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1); - state = yield msg("key", { key: "VK_UP", modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); - state = yield msg("key", { key: "VK_UP", modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); - state = yield msg("key", { key: "VK_UP", modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1); // If the settings button is selected, pressing alt+up/down should select the @@ -274,13 +274,13 @@ add_task(function* cycleOneOffs() { state = yield msg("key", "VK_TAB"); // Settings button selected. checkState(state, "xbar", ["xfoo", "xbar"], 1, 2); - state = yield msg("key", { key: "VK_UP", modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); state = yield msg("key", "VK_TAB"); checkState(state, "xbar", ["xfoo", "xbar"], 1, 2); - state = yield msg("key", { key: "VK_DOWN", modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); yield msg("removeLastOneOff"); @@ -418,7 +418,7 @@ add_task(function* search() { // Test typing a query and pressing enter. let p = msg("waitForSearch"); yield msg("key", { key: "x", waitForSuggestions: true }); - yield msg("key", { key: "VK_RETURN", modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); let mesg = yield p; let eventData = { engineName: TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME, @@ -437,7 +437,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("key", "VK_DOWN"); yield msg("key", "VK_DOWN"); - yield msg("key", { key: "VK_RETURN", modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME; @@ -455,7 +455,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("key", "VK_UP"); yield msg("key", "VK_UP"); - yield msg("key", { key: "VK_RETURN", modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); mesg = yield p; delete eventData.selection; eventData.searchString = "x"; @@ -470,7 +470,7 @@ add_task(function* search() { modifiers.button = 0; yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("mousemove", -1); - yield msg("click", { eltIdx: -1, modifiers }); + yield msg("click", { eltIdx: -1, modifiers: modifiers }); mesg = yield p; eventData.originalEvent = modifiers; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME; @@ -483,7 +483,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); p = msg("waitForSearch"); yield msg("mousemove", 1); - yield msg("click", { eltIdx: 1, modifiers }); + yield msg("click", { eltIdx: 1, modifiers: modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.selection = { @@ -499,7 +499,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); p = msg("waitForSearch"); yield msg("mousemove", 3); - yield msg("click", { eltIdx: 3, modifiers }); + yield msg("click", { eltIdx: 3, modifiers: modifiers }); mesg = yield p; eventData.searchString = "x"; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_2_BASENAME; @@ -515,7 +515,7 @@ add_task(function* search() { p = msg("waitForSearch"); yield msg("mousemove", 1); yield msg("mousemove", 3); - yield msg("click", { eltIdx: 3, modifiers }); + yield msg("click", { eltIdx: 3, modifiers: modifiers }); mesg = yield p; eventData.searchString = "xfoo" eventData.selection = { @@ -534,7 +534,7 @@ add_task(function* search() { yield msg("key", "VK_DOWN"); yield msg("key", "VK_DOWN"); yield msg("key", "VK_TAB"); - yield msg("key", { key: "VK_RETURN", modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); mesg = yield p; eventData.selection = { index: 1, @@ -554,7 +554,7 @@ add_task(function* search() { yield msg("commitComposition"); delete modifiers.button; p = msg("waitForSearch"); - yield msg("key", { key: "VK_RETURN", modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); mesg = yield p; eventData.searchString = "x" eventData.originalEvent = modifiers; @@ -583,7 +583,7 @@ add_task(function* search() { modifiers.button = 0; p = msg("waitForSearch"); - yield msg("click", { eltIdx: 1, modifiers }); + yield msg("click", { eltIdx: 1, modifiers: modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.originalEvent = modifiers; @@ -662,8 +662,8 @@ function setUp(aNoEngine) { function msg(type, data = null) { gMsgMan.sendAsyncMessage(TEST_MSG, { - type, - data, + type: type, + data: data, }); let deferred = Promise.defer(); gMsgMan.addMessageListener(TEST_MSG, function onMsg(msgObj) { diff --git a/browser/base/content/test/general/browser_contextmenu.js b/browser/base/content/test/general/browser_contextmenu.js index 88bf6a2f6192..3e0135848ee4 100644 --- a/browser/base/content/test/general/browser_contextmenu.js +++ b/browser/base/content/test/general/browser_contextmenu.js @@ -500,7 +500,7 @@ add_task(function* test_contenteditable() { add_task(function* test_copylinkcommand() { yield test_contextmenu("#test-link", null, { - *postCheckContextMenuFn() { + postCheckContextMenuFn: function*() { document.commandDispatcher .getControllerForCommand("cmd_copyLink") .doCommand("cmd_copyLink"); @@ -562,7 +562,7 @@ add_task(function* test_pagemenu() { "context-viewsource", true, "context-viewinfo", true ], - {*postCheckContextMenuFn() { + {postCheckContextMenuFn: function*() { let item = contextMenu.getElementsByAttribute("generateditemid", "1")[0]; ok(item, "Got generated XUL menu item"); item.doCommand(); @@ -820,11 +820,11 @@ add_task(function* test_click_to_play_blocked_plugin() { "context-viewinfo", true ], { - *preCheckContextMenuFn() { + preCheckContextMenuFn: function*() { pushPrefs(["plugins.click_to_play", true]); setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY); }, - *postCheckContextMenuFn() { + postCheckContextMenuFn: function*() { getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_ENABLED; } } diff --git a/browser/base/content/test/general/browser_devedition.js b/browser/base/content/test/general/browser_devedition.js index 4369b6b2bcd2..d11a26e264be 100644 --- a/browser/base/content/test/general/browser_devedition.js +++ b/browser/base/content/test/general/browser_devedition.js @@ -80,7 +80,7 @@ add_task(function* testDevtoolsTheme() { function dummyLightweightTheme(id) { return { - id, + id: id, name: id, headerURL: "resource:///chrome/browser/content/browser/defaultthemes/devedition.header.png", iconURL: "resource:///chrome/browser/content/browser/defaultthemes/devedition.icon.png", diff --git a/browser/base/content/test/general/browser_documentnavigation.js b/browser/base/content/test/general/browser_documentnavigation.js index 2047795491c9..eb789d0766a9 100644 --- a/browser/base/content/test/general/browser_documentnavigation.js +++ b/browser/base/content/test/general/browser_documentnavigation.js @@ -60,7 +60,7 @@ function* expectFocusOnF6(backward, expectedDocument, expectedElement, onContent details += "," + contentFM.focusedElement.id; } - sendSyncMessage("BrowserTest:FocusChanged", { details }); + sendSyncMessage("BrowserTest:FocusChanged", { details : details }); }, true); }); } diff --git a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js b/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js index 01c9389ef997..b1dde6b5ae62 100644 --- a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js +++ b/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js @@ -114,7 +114,7 @@ var gTests = [ { desc: "F11 key", affectsFullscreenMode: true, - exitFunc() { + exitFunc: function() { executeSoon(() => EventUtils.synthesizeKey("VK_F11", {})); } } diff --git a/browser/base/content/test/general/browser_e10s_about_process.js b/browser/base/content/test/general/browser_e10s_about_process.js index d3dcc56b9e57..2b4816754aa2 100644 --- a/browser/base/content/test/general/browser_e10s_about_process.js +++ b/browser/base/content/test/general/browser_e10s_about_process.js @@ -27,11 +27,11 @@ function AboutModule() { } AboutModule.prototype = { - newChannel(aURI, aLoadInfo) { + newChannel: function(aURI, aLoadInfo) { throw Components.results.NS_ERROR_NOT_IMPLEMENTED; }, - getURIFlags(aURI) { + getURIFlags: function(aURI) { for (let module of TEST_MODULES) { if (aURI.path.startsWith(module.path)) { return module.flags; @@ -42,7 +42,7 @@ AboutModule.prototype = { return 0; }, - getIndexedDBOriginPostfix(aURI) { + getIndexedDBOriginPostfix: function(aURI) { return null; }, @@ -50,13 +50,13 @@ AboutModule.prototype = { }; var AboutModuleFactory = { - createInstance(aOuter, aIID) { + createInstance: function(aOuter, aIID) { if (aOuter) throw Components.results.NS_ERROR_NO_AGGREGATION; return new AboutModule().QueryInterface(aIID); }, - lockFactory(aLock) { + lockFactory: function(aLock) { throw Components.results.NS_ERROR_NOT_IMPLEMENTED; }, diff --git a/browser/base/content/test/general/browser_fullscreen-window-open.js b/browser/base/content/test/general/browser_fullscreen-window-open.js index 169657ff1aa0..f6e0063328c6 100644 --- a/browser/base/content/test/general/browser_fullscreen-window-open.js +++ b/browser/base/content/test/general/browser_fullscreen-window-open.js @@ -66,7 +66,7 @@ function test_open() { title: "test_open", param: "", }, - finalizeFn() {}, + finalizeFn: function() {}, }); } @@ -77,7 +77,7 @@ function test_open_with_size() { title: "test_open_with_size", param: "width=400,height=400", }, - finalizeFn() {}, + finalizeFn: function() {}, }); } @@ -88,7 +88,7 @@ function test_open_with_pos() { title: "test_open_with_pos", param: "top=200,left=200", }, - finalizeFn() {}, + finalizeFn: function() {}, }); } @@ -100,11 +100,11 @@ function test_open_with_outerSize() { title: "test_open_with_outerSize", param: "outerWidth=200,outerHeight=200", }, - successFn() { + successFn: function() { is(window.outerWidth, outerWidth, "Don't change window.outerWidth."); is(window.outerHeight, outerHeight, "Don't change window.outerHeight."); }, - finalizeFn() {}, + finalizeFn: function() {}, }); } @@ -116,11 +116,11 @@ function test_open_with_innerSize() { title: "test_open_with_innerSize", param: "innerWidth=200,innerHeight=200", }, - successFn() { + successFn: function() { is(window.innerWidth, innerWidth, "Don't change window.innerWidth."); is(window.innerHeight, innerHeight, "Don't change window.innerHeight."); }, - finalizeFn() {}, + finalizeFn: function() {}, }); } @@ -131,7 +131,7 @@ function test_open_with_dialog() { title: "test_open_with_dialog", param: "dialog=yes", }, - finalizeFn() {}, + finalizeFn: function() {}, }); } @@ -148,7 +148,7 @@ function test_open_when_open_new_window_by_pref() { title: "test_open_when_open_new_window_by_pref", param: "width=400,height=400", }, - finalizeFn() { + finalizeFn: function() { Services.prefs.clearUserPref(PREF_NAME); }, }); @@ -163,7 +163,7 @@ function test_open_with_pref_to_disable_in_fullscreen() { title: "test_open_with_pref_disabled_in_fullscreen", param: "width=400,height=400", }, - finalizeFn() { + finalizeFn: function() { Services.prefs.setBoolPref(PREF_DISABLE_OPEN_NEW_WINDOW, true); }, }); @@ -177,7 +177,7 @@ function test_open_from_chrome() { title: "test_open_from_chrome", param: "", }, - finalizeFn() {} + finalizeFn: function() {} }); } @@ -251,7 +251,7 @@ function waitForWindowOpen(aOptions) { let listener = new WindowListener(message.title, getBrowserURL(), { onSuccess: aOptions.successFn, - onFinalize, + onFinalize: onFinalize, }); Services.wm.addListener(listener); @@ -292,7 +292,7 @@ function waitForWindowOpenFromChrome(aOptions) { let listener = new WindowListener(message.title, getBrowserURL(), { onSuccess: aOptions.successFn, - onFinalize, + onFinalize: onFinalize, }); Services.wm.addListener(listener); @@ -312,7 +312,7 @@ WindowListener.prototype = { callback_onSuccess: null, callBack_onFinalize: null, - onOpenWindow(aXULWindow) { + onOpenWindow: function(aXULWindow) { Services.wm.removeListener(this); let domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -340,8 +340,8 @@ WindowListener.prototype = { }; domwindow.addEventListener("load", onLoad, true); }, - onCloseWindow(aXULWindow) {}, - onWindowTitleChange(aXULWindow, aNewTitle) {}, + onCloseWindow: function(aXULWindow) {}, + onWindowTitleChange: function(aXULWindow, aNewTitle) {}, QueryInterface: XPCOMUtils.generateQI([Ci.nsIWindowMediatorListener, Ci.nsISupports]), }; diff --git a/browser/base/content/test/general/browser_fxa_oauth.js b/browser/base/content/test/general/browser_fxa_oauth.js index 5babfa638e9e..b676d2bd06d9 100644 --- a/browser/base/content/test/general/browser_fxa_oauth.js +++ b/browser/base/content/test/general/browser_fxa_oauth.js @@ -21,7 +21,7 @@ const HTTP_ENDPOINT_WITH_KEYS = "/browser/browser/base/content/test/general/brow var gTests = [ { desc: "FxA OAuth - should open a new tab, complete OAuth flow", - run() { + run: function() { return new Promise(function(resolve, reject) { let tabOpened = false; let properURL = "http://example.com/browser/browser/base/content/test/general/browser_fxa_oauth.html"; @@ -74,7 +74,7 @@ var gTests = [ }, { desc: "FxA OAuth - should open a new tab, complete OAuth flow when forcing auth", - run() { + run: function() { return new Promise(function(resolve, reject) { let tabOpened = false; let properURL = "http://example.com/browser/browser/base/content/test/general/browser_fxa_oauth.html"; @@ -131,7 +131,7 @@ var gTests = [ }, { desc: "FxA OAuth - should receive an error when there's a state mismatch", - run() { + run: function() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -169,7 +169,7 @@ var gTests = [ }, { desc: "FxA OAuth - should be able to request keys during OAuth flow", - run() { + run: function() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -211,7 +211,7 @@ var gTests = [ }, { desc: "FxA OAuth - should not receive keys if not explicitly requested", - run() { + run: function() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -252,7 +252,7 @@ var gTests = [ }, { desc: "FxA OAuth - should receive an error if keys could not be obtained", - run() { + run: function() { return new Promise(function(resolve, reject) { let tabOpened = false; diff --git a/browser/base/content/test/general/browser_fxa_web_channel.js b/browser/base/content/test/general/browser_fxa_web_channel.js index a87c2338a6b4..ad4fb7b57ae4 100644 --- a/browser/base/content/test/general/browser_fxa_web_channel.js +++ b/browser/base/content/test/general/browser_fxa_web_channel.js @@ -23,7 +23,7 @@ const TEST_CHANNEL_ID = "account_updates_test"; var gTests = [ { desc: "FxA Web Channel - should receive message about profile changes", - *run() { + run: function* () { let client = new FxAccountsWebChannel({ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, @@ -37,7 +37,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser, + gBrowser: gBrowser, url: TEST_BASE_URL + "?profile_change" }, function* () { yield promiseObserver; @@ -46,7 +46,7 @@ var gTests = [ }, { desc: "fxa web channel - login messages should notify the fxAccounts object", - *run() { + run: function* () { let promiseLogin = new Promise((resolve, reject) => { let login = (accountData) => { @@ -66,13 +66,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - login + login: login } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser, + gBrowser: gBrowser, url: TEST_BASE_URL + "?login" }, function* () { yield promiseLogin; @@ -81,7 +81,7 @@ var gTests = [ }, { desc: "fxa web channel - can_link_account messages should respond", - *run() { + run: function* () { let properUrl = TEST_BASE_URL + "?can_link_account"; let promiseEcho = new Promise((resolve, reject) => { @@ -114,7 +114,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser, + gBrowser: gBrowser, url: properUrl }, function* () { yield promiseEcho; @@ -123,7 +123,7 @@ var gTests = [ }, { desc: "fxa web channel - logout messages should notify the fxAccounts object", - *run() { + run: function* () { let promiseLogout = new Promise((resolve, reject) => { let logout = (uid) => { Assert.equal(uid, 'uid'); @@ -136,13 +136,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - logout + logout: logout } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser, + gBrowser: gBrowser, url: TEST_BASE_URL + "?logout" }, function* () { yield promiseLogout; @@ -151,7 +151,7 @@ var gTests = [ }, { desc: "fxa web channel - delete messages should notify the fxAccounts object", - *run() { + run: function* () { let promiseDelete = new Promise((resolve, reject) => { let logout = (uid) => { Assert.equal(uid, 'uid'); @@ -164,13 +164,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - logout + logout: logout } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser, + gBrowser: gBrowser, url: TEST_BASE_URL + "?delete" }, function* () { yield promiseDelete; diff --git a/browser/base/content/test/general/browser_fxaccounts.js b/browser/base/content/test/general/browser_fxaccounts.js index ae61ce0f3874..cc7abad9ffdb 100644 --- a/browser/base/content/test/general/browser_fxaccounts.js +++ b/browser/base/content/test/general/browser_fxaccounts.js @@ -16,7 +16,7 @@ const TEST_ROOT = "http://example.com/browser/browser/base/content/test/general/ // The stub functions. let stubs = { - updateAppMenuItem() { + updateAppMenuItem: function() { return unstubs['updateAppMenuItem'].call(gFxAccounts).then(() => { Services.obs.notifyObservers(null, "test:browser_fxaccounts:updateAppMenuItem", null); }); @@ -25,7 +25,7 @@ const TEST_ROOT = "http://example.com/browser/browser/base/content/test/general/ // due to the promises it fires off at load time and there's no clear way to // know when they are done. // So just ensure openPreferences is called rather than whether it opens. - openPreferences() { + openPreferences: function() { Services.obs.notifyObservers(null, "test:browser_fxaccounts:openPreferences", null); } }; @@ -237,7 +237,7 @@ function setSignedInUser(verified) { sessionToken: "dead", kA: "beef", kB: "cafe", - verified, + verified: verified, oauthTokens: { // a token for the profile server. diff --git a/browser/base/content/test/general/browser_getshortcutoruri.js b/browser/base/content/test/general/browser_getshortcutoruri.js index 7c54ac4975e1..a318ab6d1f04 100644 --- a/browser/base/content/test/general/browser_getshortcutoruri.js +++ b/browser/base/content/test/general/browser_getshortcutoruri.js @@ -19,7 +19,7 @@ function keywordResult(aURL, aPostData, aIsUnsafe) { function keyWordData() {} keyWordData.prototype = { - init(aKeyWord, aURL, aPostData, aSearchWord) { + init: function(aKeyWord, aURL, aPostData, aSearchWord) { this.keyword = aKeyWord; this.uri = makeURI(aURL); this.postData = aPostData; diff --git a/browser/base/content/test/general/browser_homeDrop.js b/browser/base/content/test/general/browser_homeDrop.js index 32228fca459e..061ea17f0033 100644 --- a/browser/base/content/test/general/browser_homeDrop.js +++ b/browser/base/content/test/general/browser_homeDrop.js @@ -32,7 +32,7 @@ add_task(function*() { let setHomepagePromise = new Promise(function(resolve) { let observer = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), - observe(subject, topic, data) { + observe: function(subject, topic, data) { is(topic, "nsPref:changed", "observed correct topic"); is(data, HOMEPAGE_PREF, "observed correct data"); let modified = Services.prefs.getComplexValue(HOMEPAGE_PREF, @@ -57,7 +57,7 @@ add_task(function*() { function dropInvalidURI() { return new Promise(resolve => { let consoleListener = { - observe(m) { + observe: function(m) { if (m.message.includes("NS_ERROR_DOM_BAD_URI")) { ok(true, "drop was blocked"); resolve(); diff --git a/browser/base/content/test/general/browser_keywordSearch.js b/browser/base/content/test/general/browser_keywordSearch.js index ff6ef4a0832f..4d64febef6d8 100644 --- a/browser/base/content/test/general/browser_keywordSearch.js +++ b/browser/base/content/test/general/browser_keywordSearch.js @@ -20,7 +20,7 @@ function test() { waitForExplicitFinish(); let windowObserver = { - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { ok(false, "Alert window opened"); let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget); diff --git a/browser/base/content/test/general/browser_plainTextLinks.js b/browser/base/content/test/general/browser_plainTextLinks.js index a6f436dec1df..7a304fce0c89 100644 --- a/browser/base/content/test/general/browser_plainTextLinks.js +++ b/browser/base/content/test/general/browser_plainTextLinks.js @@ -119,7 +119,7 @@ add_task(function *() { let contentAreaContextMenu = document.getElementById("contentAreaContextMenu"); for (let testid = 0; testid < checks.length; testid++) { - let menuPosition = yield ContentTask.spawn(gBrowser.selectedBrowser, { testid }, function* (arg) { + let menuPosition = yield ContentTask.spawn(gBrowser.selectedBrowser, { testid: testid }, function* (arg) { let range = content.tests[arg.testid](); // Get the range of the selection and determine its coordinates. These diff --git a/browser/base/content/test/general/browser_restore_isAppTab.js b/browser/base/content/test/general/browser_restore_isAppTab.js index 1e98ae0dc118..3e53efd326f7 100644 --- a/browser/base/content/test/general/browser_restore_isAppTab.js +++ b/browser/base/content/test/general/browser_restore_isAppTab.js @@ -14,7 +14,7 @@ function getMinidumpDirectory() { // This observer is needed so we can clean up all evidence of the crash so // the testrunner thinks things are peachy. var CrashObserver = { - observe(subject, topic, data) { + observe: function(subject, topic, data) { is(topic, 'ipc:content-shutdown', 'Received correct observer topic.'); ok(subject instanceof Ci.nsIPropertyBag2, 'Subject implements nsIPropertyBag2.'); diff --git a/browser/base/content/test/general/browser_sanitize-timespans.js b/browser/base/content/test/general/browser_sanitize-timespans.js index 813e72f1af7a..f1096246c35c 100644 --- a/browser/base/content/test/general/browser_sanitize-timespans.js +++ b/browser/base/content/test/general/browser_sanitize-timespans.js @@ -31,7 +31,7 @@ function promiseDownloadRemoved(list) { let deferred = Promise.defer(); let view = { - onDownloadRemoved(download) { + onDownloadRemoved: function(download) { list.removeView(view); deferred.resolve(); } @@ -58,11 +58,11 @@ function countEntries(name, message, check) { let count; FormHistory.count(obj, { handleResult: result => count = result, - handleError(error) { + handleError: function(error) { deferred.reject(error) throw new Error("Error occurred searching form history: " + error); }, - handleCompletion(reason) { + handleCompletion: function(reason) { if (!reason) { check(count, message); deferred.resolve(); @@ -493,11 +493,11 @@ function* setupFormHistory() { let results = []; FormHistory.search(terms, params, { handleResult: result => results.push(result), - handleError(error) { + handleError: function(error) { deferred.reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion(reason) { deferred.resolve(results); } + handleCompletion: function(reason) { deferred.resolve(results); } }); return deferred.promise; } @@ -505,11 +505,11 @@ function* setupFormHistory() { function update(changes) { let deferred = Promise.defer(); - FormHistory.update(changes, { handleError(error) { + FormHistory.update(changes, { handleError: function(error) { deferred.reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion(reason) { deferred.resolve(); } + handleCompletion: function(reason) { deferred.resolve(); } }); return deferred.promise; } diff --git a/browser/base/content/test/general/browser_sanitizeDialog.js b/browser/base/content/test/general/browser_sanitizeDialog.js index 7b469e76eeb4..e7708aede954 100644 --- a/browser/base/content/test/general/browser_sanitizeDialog.js +++ b/browser/base/content/test/general/browser_sanitizeDialog.js @@ -572,7 +572,7 @@ add_task(function* test_offline_cache() { // Check if the cache has been deleted var size = -1; var visitor = { - onCacheStorageInfo(aEntryCount, aConsumption, aCapacity, aDiskDirectory) + onCacheStorageInfo: function(aEntryCount, aConsumption, aCapacity, aDiskDirectory) { size = aConsumption; } @@ -583,8 +583,8 @@ add_task(function* test_offline_cache() { }; var cacheListener = { - onCacheEntryCheck() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable(entry, isnew, unused, status) { + onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, + onCacheEntryAvailable: function(entry, isnew, unused, status) { is(status, Cr.NS_OK); var stream = entry.openOutputStream(0); var content = "content"; @@ -648,7 +648,7 @@ WindowHelper.prototype = { /** * "Presses" the dialog's OK button. */ - acceptDialog() { + acceptDialog: function() { is(this.win.document.documentElement.getButton("accept").disabled, false, "Dialog's OK button should not be disabled"); this.win.document.documentElement.acceptDialog(); @@ -657,7 +657,7 @@ WindowHelper.prototype = { /** * "Presses" the dialog's Cancel button. */ - cancelDialog() { + cancelDialog: function() { this.win.document.documentElement.cancelDialog(); }, @@ -669,7 +669,7 @@ WindowHelper.prototype = { * @param aShouldBeShown * True if you expect the details to be shown and false if hidden */ - checkDetails(aShouldBeShown) { + checkDetails: function(aShouldBeShown) { let button = this.getDetailsButton(); let list = this.getItemList(); let hidden = list.hidden || list.collapsed; @@ -700,7 +700,7 @@ WindowHelper.prototype = { * @param aCheckState * True if the checkbox should be checked, false otherwise */ - checkPrefCheckbox(aPrefName, aCheckState) { + checkPrefCheckbox: function(aPrefName, aCheckState) { var pref = "privacy.cpd." + aPrefName; var cb = this.win.document.querySelectorAll( "#itemList > [preference='" + pref + "']"); @@ -712,7 +712,7 @@ WindowHelper.prototype = { /** * Makes sure all the checkboxes are checked. */ - _checkAllCheckboxesCustom(check) { + _checkAllCheckboxesCustom: function(check) { var cb = this.win.document.querySelectorAll("#itemList > [preference]"); ok(cb.length > 1, "found checkboxes for preferences"); for (var i = 0; i < cb.length; ++i) { @@ -722,39 +722,39 @@ WindowHelper.prototype = { } }, - checkAllCheckboxes() { + checkAllCheckboxes: function() { this._checkAllCheckboxesCustom(true); }, - uncheckAllCheckboxes() { + uncheckAllCheckboxes: function() { this._checkAllCheckboxesCustom(false); }, /** * @return The details progressive disclosure button */ - getDetailsButton() { + getDetailsButton: function() { return this.win.document.getElementById("detailsExpander"); }, /** * @return The dialog's duration dropdown */ - getDurationDropdown() { + getDurationDropdown: function() { return this.win.document.getElementById("sanitizeDurationChoice"); }, /** * @return The item list hidden by the details progressive disclosure button */ - getItemList() { + getItemList: function() { return this.win.document.getElementById("itemList"); }, /** * @return The clear-everything warning box */ - getWarningPanel() { + getWarningPanel: function() { return this.win.document.getElementById("sanitizeEverythingWarningBox"); }, @@ -762,7 +762,7 @@ WindowHelper.prototype = { * @return True if the "Everything" warning panel is visible (as opposed to * the tree) */ - isWarningPanelVisible() { + isWarningPanelVisible: function() { return !this.getWarningPanel().hidden; }, @@ -774,7 +774,7 @@ WindowHelper.prototype = { * caller is expected to call waitForAsyncUpdates at some point; if false is * returned, waitForAsyncUpdates is called automatically. */ - open() { + open: function() { let wh = this; function windowObserver(aSubject, aTopic, aData) { @@ -835,7 +835,7 @@ WindowHelper.prototype = { * @param aDurVal * One of the Sanitizer.TIMESPAN_* values */ - selectDuration(aDurVal) { + selectDuration: function(aDurVal) { this.getDurationDropdown().value = aDurVal; if (aDurVal === Sanitizer.TIMESPAN_EVERYTHING) { is(this.isWarningPanelVisible(), true, @@ -850,7 +850,7 @@ WindowHelper.prototype = { /** * Toggles the details progressive disclosure button. */ - toggleDetails() { + toggleDetails: function() { this.getDetailsButton().click(); } }; @@ -898,11 +898,11 @@ function promiseAddFormEntryWithMinutesAgo(aMinutesAgo) { return new Promise((resolve, reject) => FormHistory.update({ op: "add", fieldname: name, value: "dummy", firstUsed: timestamp }, - { handleError(error) { + { handleError: function(error) { reject(); throw new Error("Error occurred updating form history: " + error); }, - handleCompletion(reason) { + handleCompletion: function(reason) { resolve(name); } }) @@ -918,11 +918,11 @@ function formNameExists(name) let count = 0; FormHistory.count({ fieldname: name }, { handleResult: result => count = result, - handleError(error) { + handleError: function(error) { reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion(reason) { + handleCompletion: function(reason) { if (!reason) { resolve(count); } diff --git a/browser/base/content/test/general/browser_save_link_when_window_navigates.js b/browser/base/content/test/general/browser_save_link_when_window_navigates.js index 103985ac9f6f..2da54eb92351 100644 --- a/browser/base/content/test/general/browser_save_link_when_window_navigates.js +++ b/browser/base/content/test/general/browser_save_link_when_window_navigates.js @@ -90,13 +90,13 @@ function triggerSave(aWindow, aCallback) { var windowObserver = { - setCallback(aCallback) { + setCallback: function(aCallback) { if (this._callback) { ok(false, "Should only be dealing with one callback at a time."); } this._callback = aCallback; }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic != "domwindowopened") { return; } diff --git a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js index 6da92c10e478..92fb7bd0392f 100644 --- a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js +++ b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js @@ -15,17 +15,17 @@ function createTemporarySaveDirectory() { function promiseNoCacheEntry(filename) { return new Promise((resolve, reject) => { Visitor.prototype = { - onCacheStorageInfo(num, consumption) + onCacheStorageInfo: function(num, consumption) { info("disk storage contains " + num + " entries"); }, - onCacheEntryInfo(uri) + onCacheEntryInfo: function(uri) { let urispec = uri.asciiSpec; info(urispec); is(urispec.includes(filename), false, "web content present in disk cache"); }, - onCacheEntryVisitCompleted() + onCacheEntryVisitCompleted: function() { resolve(); } diff --git a/browser/base/content/test/general/browser_tabfocus.js b/browser/base/content/test/general/browser_tabfocus.js index 42552caa5ae4..96b6b315388b 100644 --- a/browser/base/content/test/general/browser_tabfocus.js +++ b/browser/base/content/test/general/browser_tabfocus.js @@ -53,7 +53,7 @@ function* getFocusedElementForBrowser(browser, dontCheckExtraFocus = false) // additional focus related properties. This is needed as both URLs are // loaded using the same child process and share focus managers. browser.messageManager.sendAsyncMessage("Browser:GetFocusedElement", - { dontCheckExtraFocus }); + { dontCheckExtraFocus : dontCheckExtraFocus }); }); } var focusedWindow = {}; @@ -113,7 +113,7 @@ function focusInChild() } } - sendSyncMessage("Browser:GetCurrentFocus", { details }); + sendSyncMessage("Browser:GetCurrentFocus", { details : details }); }); } @@ -122,7 +122,7 @@ function focusElementInChild(elementid, type) let browser = (elementid.indexOf("1") >= 0) ? browser1 : browser2; if (gMultiProcessBrowser) { browser.messageManager.sendAsyncMessage("Browser:ChangeFocus", - { id: elementid, type }); + { id: elementid, type: type }); } else { browser.contentDocument.getElementById(elementid)[type](); diff --git a/browser/base/content/test/general/browser_tabopen_reflows.js b/browser/base/content/test/general/browser_tabopen_reflows.js index eed2eecb1417..4eb6c77ab1ab 100644 --- a/browser/base/content/test/general/browser_tabopen_reflows.js +++ b/browser/base/content/test/general/browser_tabopen_reflows.js @@ -113,7 +113,7 @@ add_task(function*() { }); var observer = { - reflow(start, end) { + reflow: function(start, end) { // Gather information about the current code path. let path = (new Error().stack).split("\n").slice(1).map(line => { return line.replace(/:\d+:\d+$/, ""); @@ -136,7 +136,7 @@ var observer = { ok(false, "unexpected uninterruptible reflow '" + pathWithLineNumbers + "'"); }, - reflowInterruptible(start, end) { + reflowInterruptible: function(start, end) { // We're not interested in interruptible reflows. }, diff --git a/browser/base/content/test/general/browser_trackingUI_4.js b/browser/base/content/test/general/browser_trackingUI_4.js index ba0478f7f852..234b790acb44 100644 --- a/browser/base/content/test/general/browser_trackingUI_4.js +++ b/browser/base/content/test/general/browser_trackingUI_4.js @@ -28,7 +28,7 @@ function waitForSecurityChange(numChanges = 1) { return new Promise(resolve => { let n = 0; let listener = { - onSecurityChange() { + onSecurityChange: function() { n = n + 1; info("Received onSecurityChange event " + n + " of " + numChanges); if (n >= numChanges) { diff --git a/browser/base/content/test/general/browser_trackingUI_6.js b/browser/base/content/test/general/browser_trackingUI_6.js index 33a337231f1e..be47263ba3c1 100644 --- a/browser/base/content/test/general/browser_trackingUI_6.js +++ b/browser/base/content/test/general/browser_trackingUI_6.js @@ -4,7 +4,7 @@ function waitForSecurityChange(numChanges = 1) { return new Promise(resolve => { let n = 0; let listener = { - onSecurityChange() { + onSecurityChange: function() { n = n + 1; info("Received onSecurityChange event " + n + " of " + numChanges); if (n >= numChanges) { diff --git a/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js b/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js index 2afedba0dac9..eedc7116b30c 100644 --- a/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js +++ b/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js @@ -1,7 +1,7 @@ function wait_while_tab_is_busy() { return new Promise(resolve => { let progressListener = { - onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) { gBrowser.removeProgressListener(this); setTimeout(resolve, 0); diff --git a/browser/base/content/test/general/browser_web_channel.js b/browser/base/content/test/general/browser_web_channel.js index ab7eaaf21f8d..f1bcd4711bd7 100644 --- a/browser/base/content/test/general/browser_web_channel.js +++ b/browser/base/content/test/general/browser_web_channel.js @@ -20,7 +20,7 @@ const HTTP_REDIRECTED_IFRAME_PATH = "http://example.org"; var gTests = [ { desc: "WebChannel generic message", - *run() { + run: function* () { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("generic", Services.io.newURI(HTTP_PATH, null, null)); @@ -38,7 +38,7 @@ var gTests = [ }, { desc: "WebChannel generic message in a private window.", - *run() { + run: function* () { let promiseTestDone = new Promise(function(resolve, reject) { let channel = new WebChannel("generic", Services.io.newURI(HTTP_PATH, null, null)); channel.listen(function(id, message, target) { @@ -58,7 +58,7 @@ var gTests = [ }, { desc: "WebChannel two way communication", - *run() { + run: function* () { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("twoway", Services.io.newURI(HTTP_PATH, null, null)); @@ -85,7 +85,7 @@ var gTests = [ }, { desc: "WebChannel two way communication in an iframe", - *run() { + run: function* () { let parentChannel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); let iframeChannel = new WebChannel("twoway", Services.io.newURI(HTTP_IFRAME_PATH, null, null)); let promiseTestDone = new Promise(function(resolve, reject) { @@ -108,7 +108,7 @@ var gTests = [ }); }); yield BrowserTestUtils.withNewTab({ - gBrowser, + gBrowser: gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?iframe" }, function* () { yield promiseTestDone; @@ -119,7 +119,7 @@ var gTests = [ }, { desc: "WebChannel response to a redirected iframe", - *run() { + run: function* () { /** * This test checks that WebChannel responses are only sent * to an iframe if the iframe has not redirected to another origin. @@ -172,7 +172,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser, + gBrowser: gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?iframe_pre_redirect" }, function* () { yield promiseTestDone; @@ -183,7 +183,7 @@ var gTests = [ }, { desc: "WebChannel multichannel", - *run() { + run: function* () { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("multichannel", Services.io.newURI(HTTP_PATH, null, null)); @@ -200,7 +200,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send, using system principal", - *run() { + run: function* () { let channel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); // an unsolicted message is sent from Chrome->Content which is then @@ -230,7 +230,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send, using target origin's principal", - *run() { + run: function* () { let targetURI = Services.io.newURI(HTTP_PATH, null, null); let channel = new WebChannel("echo", targetURI); @@ -263,7 +263,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send with principal mismatch", - *run() { + run: function* () { let targetURI = Services.io.newURI(HTTP_PATH, null, null); let channel = new WebChannel("echo", targetURI); @@ -284,7 +284,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser, + gBrowser: gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?unsolicited" }, function* (targetBrowser) { @@ -314,7 +314,7 @@ var gTests = [ }, { desc: "WebChannel non-window target", - *run() { + run: function* () { /** * This test ensures messages can be received from and responses * sent to non-window elements. @@ -350,7 +350,7 @@ var gTests = [ }, { desc: "WebChannel disallows non-string message from non-whitelisted origin", - *run() { + run: function* () { /** * This test ensures that non-string messages can't be sent via WebChannels. * We create a page (on a non-whitelisted origin) which should send us two @@ -377,7 +377,7 @@ var gTests = [ }, { desc: "WebChannel allows both string and non-string message from whitelisted origin", - *run() { + run: function* () { /** * Same process as above, but we whitelist the origin before loading the page, * and expect to get *both* messages back (each exactly once). @@ -419,7 +419,7 @@ var gTests = [ }, { desc: "WebChannel errors handling the message are delivered back to content", - *run() { + run: function* () { const ERRNO_UNKNOWN_ERROR = 999; // WebChannel.jsm doesn't export this. // The channel where we purposely fail responding to a command. @@ -455,7 +455,7 @@ var gTests = [ }, { desc: "WebChannel errors due to an invalid channel are delivered back to content", - *run() { + run: function* () { const ERRNO_NO_SUCH_CHANNEL = 2; // WebChannel.jsm doesn't export this. // The channel where we see the response when the content sees the error let echoChannel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); diff --git a/browser/base/content/test/general/browser_windowactivation.js b/browser/base/content/test/general/browser_windowactivation.js index 4759bb68b80c..cac9e8866d6c 100644 --- a/browser/base/content/test/general/browser_windowactivation.js +++ b/browser/base/content/test/general/browser_windowactivation.js @@ -109,8 +109,8 @@ function reallyRunTests() { function sendGetBackgroundRequest(ifChanged) { - browser1.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged }); - browser2.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged }); + browser1.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged: ifChanged }); + browser2.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged: ifChanged }); } function runOtherWindowTests() { @@ -177,7 +177,7 @@ function childFunction() if (oldColor != color || !ifChanged) { expectingResponse = false; oldColor = color; - sendAsyncMessage("Test:BackgroundColorChanged", { color }); + sendAsyncMessage("Test:BackgroundColorChanged", { color: color }); } }, 20); } diff --git a/browser/base/content/test/general/browser_windowopen_reflows.js b/browser/base/content/test/general/browser_windowopen_reflows.js index c5b3d15f3065..8d82b715a5d4 100644 --- a/browser/base/content/test/general/browser_windowopen_reflows.js +++ b/browser/base/content/test/general/browser_windowopen_reflows.js @@ -73,7 +73,7 @@ function test() { } var observer = { - reflow(start, end) { + reflow: function(start, end) { // Gather information about the current code path. let stack = new Error().stack; let path = stack.split("\n").slice(1).map(line => { @@ -99,7 +99,7 @@ var observer = { ok(false, "unexpected uninterruptible reflow '" + pathWithLineNumbers + "'"); }, - reflowInterruptible(start, end) { + reflowInterruptible: function(start, end) { // We're not interested in interruptible reflows. }, diff --git a/browser/base/content/test/general/contentSearchUI.js b/browser/base/content/test/general/contentSearchUI.js index 87851f65c4e3..bbb9a2d85b87 100644 --- a/browser/base/content/test/general/contentSearchUI.js +++ b/browser/base/content/test/general/contentSearchUI.js @@ -15,7 +15,7 @@ addMessageListener(TEST_MSG, msg => { var messageHandlers = { - init() { + init: function() { Services.search.currentEngine = Services.search.getEngineByName(ENGINE_NAME); let input = content.document.querySelector("input"); gController = @@ -29,19 +29,19 @@ var messageHandlers = { }); }, - key(arg) { + key: function(arg) { let keyName = typeof(arg) == "string" ? arg : arg.key; content.synthesizeKey(keyName, arg.modifiers || {}); let wait = arg.waitForSuggestions ? waitForSuggestions : cb => cb(); wait(ack.bind(null, "key")); }, - startComposition(arg) { + startComposition: function(arg) { content.synthesizeComposition({ type: "compositionstart", data: "" }); ack("startComposition"); }, - changeComposition(arg) { + changeComposition: function(arg) { let data = typeof(arg) == "string" ? arg : arg.data; content.synthesizeCompositionChange({ composition: { @@ -56,31 +56,31 @@ var messageHandlers = { wait(ack.bind(null, "changeComposition")); }, - commitComposition() { + commitComposition: function() { content.synthesizeComposition({ type: "compositioncommitasis" }); ack("commitComposition"); }, - focus() { + focus: function() { gController.input.focus(); ack("focus"); }, - blur() { + blur: function() { gController.input.blur(); ack("blur"); }, - waitForSearch() { + waitForSearch: function() { waitForContentSearchEvent("Search", aData => ack("waitForSearch", aData)); }, - waitForSearchSettings() { + waitForSearchSettings: function() { waitForContentSearchEvent("ManageEngines", aData => ack("waitForSearchSettings", aData)); }, - mousemove(itemIndex) { + mousemove: function(itemIndex) { let row; if (itemIndex == -1) { row = gController._table.firstChild; @@ -102,7 +102,7 @@ var messageHandlers = { content.synthesizeMouseAtCenter(row, event); }, - click(arg) { + click: function(arg) { let eltIdx = typeof(arg) == "object" ? arg.eltIdx : arg; let row; if (eltIdx == -1) { @@ -121,12 +121,12 @@ var messageHandlers = { ack("click"); }, - addInputValueToFormHistory() { + addInputValueToFormHistory: function() { gController.addInputValueToFormHistory(); ack("addInputValueToFormHistory"); }, - addDuplicateOneOff() { + addDuplicateOneOff: function() { let btn = gController._oneOffButtons[gController._oneOffButtons.length - 1]; let newBtn = btn.cloneNode(true); btn.parentNode.appendChild(newBtn); @@ -134,12 +134,12 @@ var messageHandlers = { ack("addDuplicateOneOff"); }, - removeLastOneOff() { + removeLastOneOff: function() { gController._oneOffButtons.pop().remove(); ack("removeLastOneOff"); }, - reset() { + reset: function() { // Reset both the input and suggestions by select all + delete. If there was // no text entered, this won't have any effect, so also escape to ensure the // suggestions table is closed. diff --git a/browser/base/content/test/general/head.js b/browser/base/content/test/general/head.js index 3bdd3f6fb710..7becbbf91ceb 100644 --- a/browser/base/content/test/general/head.js +++ b/browser/base/content/test/general/head.js @@ -307,9 +307,9 @@ function waitForAsyncUpdates(aCallback, aScope, aArguments) { let commit = db.createAsyncStatement("COMMIT"); commit.executeAsync({ - handleResult() {}, - handleError() {}, - handleCompletion(aReason) { + handleResult: function() {}, + handleError: function() {}, + handleCompletion: function(aReason) { aCallback.apply(scope, args); } }); @@ -418,7 +418,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows } let progressListener = { - onStateChange(webProgress, req, flags, status) { + onStateChange: function(webProgress, req, flags, status) { dump("waitForDocLoadAndStopIt: onStateChange " + flags.toString(16) + ": " + req.name + "\n"); if (webProgress.isTopLevel && @@ -470,7 +470,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows function waitForDocLoadComplete(aBrowser = gBrowser) { return new Promise(resolve => { let listener = { - onStateChange(webProgress, req, flags, status) { + onStateChange: function(webProgress, req, flags, status) { let docStop = Ci.nsIWebProgressListener.STATE_IS_NETWORK | Ci.nsIWebProgressListener.STATE_STOP; info("Saw state " + flags.toString(16) + " and status " + status.toString(16)); @@ -918,12 +918,12 @@ function promiseNewSearchEngine(basename) { info("Waiting for engine to be added: " + basename); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess(engine) { + onSuccess: function(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => Services.search.removeEngine(engine)); resolve(engine); }, - onError(errCode) { + onError: function(errCode) { Assert.ok(false, "addEngine failed with error code " + errCode); reject(); }, @@ -966,7 +966,7 @@ function isSecurityState(expectedState) { function promiseOnBookmarkItemAdded(aExpectedURI) { return new Promise((resolve, reject) => { let bookmarksObserver = { - onItemAdded(aItemId, aFolderId, aIndex, aItemType, aURI) { + onItemAdded: function(aItemId, aFolderId, aIndex, aItemType, aURI) { info("Added a bookmark to " + aURI.spec); PlacesUtils.bookmarks.removeObserver(bookmarksObserver); if (aURI.equals(aExpectedURI)) { @@ -976,12 +976,12 @@ function promiseOnBookmarkItemAdded(aExpectedURI) { reject(new Error("Added an unexpected bookmark")); } }, - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onItemRemoved() {}, - onItemChanged() {}, - onItemVisited() {}, - onItemMoved() {}, + onBeginUpdateBatch: function() {}, + onEndUpdateBatch: function() {}, + onItemRemoved: function() {}, + onItemChanged: function() {}, + onItemVisited: function() {}, + onItemMoved: function() {}, QueryInterface: XPCOMUtils.generateQI([ Ci.nsINavBookmarkObserver, ]) @@ -1006,7 +1006,7 @@ function* loadBadCertPage(url) { // When the certificate exception dialog has opened, click the button to add // an exception. let certExceptionDialogObserver = { - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic == "cert-exception-ui-ready") { Services.obs.removeObserver(this, "cert-exception-ui-ready"); let certExceptionDialog = getCertExceptionDialog(EXCEPTION_DIALOG_URI); @@ -1073,7 +1073,7 @@ function setupRemoteClientsFixture(fixture) { Object.getOwnPropertyDescriptor(gFxAccounts, "remoteClients").get; Object.defineProperty(gFxAccounts, "remoteClients", { - get() { return fixture; } + get: function() { return fixture; } }); return oldRemoteClientsGetter; } diff --git a/browser/base/content/test/general/offlineByDefault.js b/browser/base/content/test/general/offlineByDefault.js index fe6418f84f25..72f7e52a01bc 100644 --- a/browser/base/content/test/general/offlineByDefault.js +++ b/browser/base/content/test/general/offlineByDefault.js @@ -1,7 +1,7 @@ var offlineByDefault = { defaultValue: false, prefBranch: SpecialPowers.Cc["@mozilla.org/preferences-service;1"].getService(SpecialPowers.Ci.nsIPrefBranch), - set(allow) { + set: function(allow) { try { this.defaultValue = this.prefBranch.getBoolPref("offline-apps.allow_by_default"); } catch (e) { @@ -9,7 +9,7 @@ var offlineByDefault = { } this.prefBranch.setBoolPref("offline-apps.allow_by_default", allow); }, - reset() { + reset: function() { this.prefBranch.setBoolPref("offline-apps.allow_by_default", this.defaultValue); } } diff --git a/browser/base/content/test/general/parsingTestHelpers.jsm b/browser/base/content/test/general/parsingTestHelpers.jsm index fc8b620300a9..69c764483ec8 100644 --- a/browser/base/content/test/general/parsingTestHelpers.jsm +++ b/browser/base/content/test/general/parsingTestHelpers.jsm @@ -86,7 +86,7 @@ function iterateOverPath(path, extensions) { try { // Iterate through the directory yield iterator.forEach(pathEntryIterator); - resolve({files, subdirs}); + resolve({files: files, subdirs: subdirs}); } catch (ex) { reject(ex); } finally { diff --git a/browser/base/content/test/newtab/browser_newtab_bug722273.js b/browser/base/content/test/newtab/browser_newtab_bug722273.js index 1a6c9a401756..9a61a09f6491 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug722273.js +++ b/browser/base/content/test/newtab/browser_newtab_bug722273.js @@ -38,13 +38,13 @@ function promiseAddFakeVisits() { let place = { uri: makeURI(URL), title: "fake site", - visits + visits: visits }; return new Promise((resolve, reject) => { PlacesUtils.asyncHistory.updatePlaces(place, { handleError: () => reject(new Error("Couldn't add visit")), - handleResult() {}, - handleCompletion() { + handleResult: function() {}, + handleCompletion: function() { NewTabUtils.links.populateCache(function() { NewTabUtils.allPages.update(); resolve(); diff --git a/browser/base/content/test/newtab/browser_newtab_bug725996.js b/browser/base/content/test/newtab/browser_newtab_bug725996.js index 253ef4bddc08..e0de809c8f86 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug725996.js +++ b/browser/base/content/test/newtab/browser_newtab_bug725996.js @@ -9,7 +9,7 @@ add_task(function* () { yield* checkGrid("0,1,2,3,4,5,6,7,8"); function doDrop(data) { - return ContentTask.spawn(gBrowser.selectedBrowser, { data }, function*(args) { + return ContentTask.spawn(gBrowser.selectedBrowser, { data: data }, function*(args) { let dataTransfer = new content.DataTransfer("dragstart", false); dataTransfer.mozSetDataAt("text/x-moz-url", args.data, 0); let event = content.document.createEvent("DragEvent"); diff --git a/browser/base/content/test/newtab/browser_newtab_bug991210.js b/browser/base/content/test/newtab/browser_newtab_bug991210.js index 6e0d0fe73c12..f51360563964 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug991210.js +++ b/browser/base/content/test/newtab/browser_newtab_bug991210.js @@ -7,10 +7,10 @@ add_task(function* () { // add a test provider that waits for load let afterLoadProvider = { - getLinks(callback) { + getLinks: function(callback) { this.callback = callback; }, - addObserver() {}, + addObserver: function() {}, }; NewTabUtils.links.addProvider(afterLoadProvider); diff --git a/browser/base/content/test/newtab/browser_newtab_drag_drop.js b/browser/base/content/test/newtab/browser_newtab_drag_drop.js index bb38b8e82be3..da9d89de7459 100644 --- a/browser/base/content/test/newtab/browser_newtab_drag_drop.js +++ b/browser/base/content/test/newtab/browser_newtab_drag_drop.js @@ -76,7 +76,7 @@ add_task(function* () { function doDragEvent(sourceIndex, dropIndex) { return ContentTask.spawn(gBrowser.selectedBrowser, - { sourceIndex, dropIndex }, function*(args) { + { sourceIndex: sourceIndex, dropIndex: dropIndex }, function*(args) { let dataTransfer = new content.DataTransfer("dragstart", false); let event = content.document.createEvent("DragEvent"); event.initDragEvent("dragstart", true, true, content, 0, 0, 0, 0, 0, diff --git a/browser/base/content/test/newtab/browser_newtab_search.js b/browser/base/content/test/newtab/browser_newtab_search.js index 06339b52bed6..17f98bb71e3c 100644 --- a/browser/base/content/test/newtab/browser_newtab_search.js +++ b/browser/base/content/test/newtab/browser_newtab_search.js @@ -211,12 +211,12 @@ function promiseNewSearchEngine({name: basename, numLogos}) { let addEnginePromise = new Promise((resolve, reject) => { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess(engine) { + onSuccess: function(engine) { info("Search engine added: " + basename); gNewEngines.push(engine); resolve(engine); }, - onError(errCode) { + onError: function(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/newtab/head.js b/browser/base/content/test/newtab/head.js index 0c0ff02c1a0b..ab72161c5362 100644 --- a/browser/base/content/test/newtab/head.js +++ b/browser/base/content/test/newtab/head.js @@ -220,8 +220,8 @@ function fillHistory(aLinks) { PlacesUtils.asyncHistory.updatePlaces(place, { handleError: () => ok(false, "couldn't add visit to history"), - handleResult() {}, - handleCompletion() { + handleResult: function() {}, + handleCompletion: function() { if (--numLinks == 0) { resolve(); } diff --git a/browser/base/content/test/plugins/blocklist_proxy.js b/browser/base/content/test/plugins/blocklist_proxy.js index 4eb281e03f13..d0aa0e8e48e6 100644 --- a/browser/base/content/test/plugins/blocklist_proxy.js +++ b/browser/base/content/test/plugins/blocklist_proxy.js @@ -19,7 +19,7 @@ var BlocklistProxy = { Ci.nsIBlocklistService, Ci.nsITimerCallback]), - init() { + init: function() { if (!this._uuid) { this._uuid = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator) @@ -30,7 +30,7 @@ var BlocklistProxy = { } }, - uninit() { + uninit: function() { if (this._uuid) { Cm.nsIComponentRegistrar.unregisterFactory(this._uuid, this); Cm.nsIComponentRegistrar.registerFactory(Components.ID(kBlocklistServiceUUID), @@ -41,33 +41,33 @@ var BlocklistProxy = { } }, - notify(aTimer) { + notify: function(aTimer) { }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { }, - isAddonBlocklisted(aAddon, aAppVersion, aToolkitVersion) { + isAddonBlocklisted: function(aAddon, aAppVersion, aToolkitVersion) { return false; }, - getAddonBlocklistState(aAddon, aAppVersion, aToolkitVersion) { + getAddonBlocklistState: function(aAddon, aAppVersion, aToolkitVersion) { return 0; // STATE_NOT_BLOCKED }, - getPluginBlocklistState(aPluginTag, aAppVersion, aToolkitVersion) { + getPluginBlocklistState: function(aPluginTag, aAppVersion, aToolkitVersion) { return 0; // STATE_NOT_BLOCKED }, - getAddonBlocklistURL(aAddon, aAppVersion, aToolkitVersion) { + getAddonBlocklistURL: function(aAddon, aAppVersion, aToolkitVersion) { return ""; }, - getPluginBlocklistURL(aPluginTag) { + getPluginBlocklistURL: function(aPluginTag) { return ""; }, - getPluginInfoURL(aPluginTag) { + getPluginInfoURL: function(aPluginTag) { return ""; }, } diff --git a/browser/base/content/test/plugins/browser_bug797677.js b/browser/base/content/test/plugins/browser_bug797677.js index dd972c91e623..f1bd15b7716f 100644 --- a/browser/base/content/test/plugins/browser_bug797677.js +++ b/browser/base/content/test/plugins/browser_bug797677.js @@ -22,7 +22,7 @@ add_task(function* () { let consoleService = Cc["@mozilla.org/consoleservice;1"] .getService(Ci.nsIConsoleService); let errorListener = { - observe(aMessage) { + observe: function(aMessage) { if (aMessage.message.includes("NS_ERROR_FAILURE")) gConsoleErrors++; } diff --git a/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js b/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js index 31e741eb3205..c834b17215bc 100644 --- a/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js +++ b/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js @@ -68,7 +68,7 @@ function preparePlugin(browser, pluginFallbackState) { // Somehow, I'm able to get away with overriding the getter for // this XPCOM object. Probably because I've got chrome privledges. Object.defineProperty(plugin, "pluginFallbackType", { - get() { + get: function() { return contentPluginFallbackState; } }); @@ -162,7 +162,7 @@ add_task(function* testChromeHearsPluginCrashFirst() { // actually crashing the plugin again. We hack around this by overriding // the pluginFallbackType again. Object.defineProperty(plugin, "pluginFallbackType", { - get() { + get: function() { return Ci.nsIObjectLoadingContent.PLUGIN_CRASHED; }, }); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification.js b/browser/base/content/test/popupNotifications/browser_popupNotification.js index 044a58939f86..860179d68463 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification.js @@ -17,37 +17,37 @@ function test() { var tests = [ { id: "Test#1", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.mainActionClicked, "mainAction was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 0); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.secondaryActionClicked, "secondaryAction was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2b", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions.push({ label: "Extra Secondary Action", @@ -56,18 +56,18 @@ var tests = [ }); showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 1); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.extraSecondaryActionClicked, "extra secondary action was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2c", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions.push({ label: "Extra Secondary Action", @@ -80,26 +80,26 @@ var tests = [ }); showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 2); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.extraSecondaryActionClicked, "extra secondary action was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#3", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -108,7 +108,7 @@ var tests = [ // test opening a notification for a background browser // Note: test 4 to 6 share a tab. { id: "Test#4", - *run() { + run: function* () { let tab = gBrowser.addTab("http://example.com/"); yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); isnot(gBrowser.selectedTab, tab, "new tab isn't selected"); @@ -125,18 +125,18 @@ var tests = [ }, // now select that browser and test to see that the notification appeared { id: "Test#5", - run() { + run: function() { this.oldSelectedTab = gBrowser.selectedTab; gBrowser.selectedTab = gBrowser.tabs[gBrowser.tabs.length - 1]; }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, wrongBrowserNotificationObject); is(PopupNotifications.isPanelOpen, true, "isPanelOpen getter doesn't lie"); // switch back to the old browser gBrowser.selectedTab = this.oldSelectedTab; }, - onHidden(popup) { + onHidden: function(popup) { // actually remove the notification to prevent it from reappearing ok(wrongBrowserNotificationObject.dismissalCallbackTriggered, "dismissal callback triggered due to tab switch"); wrongBrowserNotification.remove(); @@ -146,7 +146,7 @@ var tests = [ }, // test that the removed notification isn't shown on browser re-select { id: "Test#6", - *run() { + run: function* () { let promiseTopic = promiseTopicObserved("PopupNotifications-updateNotShowing"); gBrowser.selectedTab = gBrowser.tabs[gBrowser.tabs.length - 1]; yield promiseTopic; @@ -158,24 +158,24 @@ var tests = [ // Test that two notifications with the same ID result in a single displayed // notification. { id: "Test#7", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); // Show the same notification twice this.notification1 = showNotification(this.notifyObj); this.notification2 = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); this.notification2.remove(); }, - onHidden(popup) { + onHidden: function(popup) { ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, // Test that two notifications with different IDs are displayed { id: "Test#8", - run() { + run: function() { this.testNotif1 = new BasicNotification(this.id); this.testNotif1.message += " 1"; showNotification(this.testNotif1); @@ -184,7 +184,7 @@ var tests = [ this.testNotif2.id += "-2"; showNotification(this.testNotif2); }, - onShown(popup) { + onShown: function(popup) { is(popup.childNodes.length, 2, "two notifications are shown"); // Trigger the main command for the first notification, and the secondary // for the second. Need to do mainCommand first since the secondaryCommand @@ -193,7 +193,7 @@ var tests = [ is(popup.childNodes.length, 1, "only one notification left"); triggerSecondaryCommand(popup, 0); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.testNotif1.mainActionClicked, "main action #1 was clicked"); ok(!this.testNotif1.secondaryActionClicked, "secondary action #1 wasn't clicked"); ok(!this.testNotif1.dismissalCallbackTriggered, "dismissal callback #1 wasn't called"); @@ -206,16 +206,16 @@ var tests = [ // Test notification without mainAction or secondaryActions, it should fall back // to a default button that dismisses the notification in place of the main action. { id: "Test#9", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction = null; this.notifyObj.secondaryActions = null; this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { triggerMainCommand(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -225,17 +225,17 @@ var tests = [ // to a default button that dismisses the notification in place of the main action // and ignore the passed secondaryActions. { id: "Test#10", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction = null; this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { let notification = popup.childNodes[0]; is(notification.getAttribute("secondarybuttonhidden"), "true", "secondary button is hidden"); triggerMainCommand(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -243,7 +243,7 @@ var tests = [ }, // Test two notifications with different anchors { id: "Test#11", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.firstNotification = showNotification(this.notifyObj); this.notifyObj2 = new BasicNotification(this.id); @@ -252,14 +252,14 @@ var tests = [ // Second showNotification() overrides the first this.secondNotification = showNotification(this.notifyObj2); }, - onShown(popup) { + onShown: function(popup) { // This also checks that only one element is shown. checkPopup(popup, this.notifyObj2); is(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor shouldn't be visible"); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { // Remove the notifications this.firstNotification.remove(); this.secondNotification.remove(); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_2.js b/browser/base/content/test/popupNotifications/browser_popupNotification_2.js index 21df05a55c3f..4366d7ed7b37 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_2.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_2.js @@ -14,16 +14,16 @@ function test() { var tests = [ // Test optional params { id: "Test#1", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions = undefined; this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -31,19 +31,19 @@ var tests = [ }, // Test that icons appear { id: "Test#2", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.id = "geolocation"; this.notifyObj.anchorID = "geo-notification-icon"; this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); isnot(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor should be visible"); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { let icon = document.getElementById("geo-notification-icon"); isnot(icon.boxObject.width, 0, "geo anchor should be visible after dismissal"); @@ -55,7 +55,7 @@ var tests = [ // Test that persistence allows the notification to persist across reloads { id: "Test#3", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -64,7 +64,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); @@ -72,7 +72,7 @@ var tests = [ this.complete = true; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.complete, "Should only have hidden the notification after 3 page loads"); ok(this.notifyObj.removedCallbackTriggered, "removal callback triggered"); gBrowser.removeTab(gBrowser.selectedTab); @@ -81,7 +81,7 @@ var tests = [ }, // Test that a timeout allows the notification to persist across reloads { id: "Test#4", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -91,7 +91,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); @@ -100,7 +100,7 @@ var tests = [ this.complete = true; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.complete, "Should only have hidden the notification after the timeout was passed"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -110,7 +110,7 @@ var tests = [ // Test that setting persistWhileVisible allows a visible notification to // persist across location changes { id: "Test#5", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -119,7 +119,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); @@ -128,7 +128,7 @@ var tests = [ this.complete = true; dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.complete, "Should only have hidden the notification after it was dismissed"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -138,7 +138,7 @@ var tests = [ // Test that nested icon nodes correctly activate popups { id: "Test#6", - run() { + run: function() { // Add a temporary box as the anchor with a button this.box = document.createElement("box"); PopupNotifications.iconBox.appendChild(this.box); @@ -160,18 +160,18 @@ var tests = [ // amount. EventUtils.synthesizeMouse(button, 4, 4, {}); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { this.notification.remove(); this.box.parentNode.removeChild(this.box); } }, // Test that popupnotifications without popups have anchor icons shown { id: "Test#7", - *run() { + run: function* () { let notifyObj = new BasicNotification(this.id); notifyObj.anchorID = "geo-notification-icon"; notifyObj.addOptions({neverShow: true}); @@ -185,16 +185,16 @@ var tests = [ }, // Test notification close button { id: "Test#9", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; EventUtils.synthesizeMouseAtCenter(notification.closebutton, {}); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -202,17 +202,17 @@ var tests = [ }, // Test notification when chrome is hidden { id: "Test#10", - run() { + run: function() { window.locationbar.visible = false; this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); is(popup.anchorNode.className, "tabbrowser-tab", "notification anchored to tab"); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js b/browser/base/content/test/popupNotifications/browser_popupNotification_3.js index 74a917afa9fb..9476cc5e60ad 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_3.js @@ -14,25 +14,25 @@ function test() { var tests = [ // Test notification is removed when dismissed if removeOnDismissal is true { id: "Test#1", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.addOptions({ removeOnDismissal: true }); this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, // Test multiple notification icons are shown { id: "Test#2", - run() { + run: function() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -43,7 +43,7 @@ var tests = [ this.notifyObj2.anchorID = "geo-notification-icon"; this.notification2 = showNotification(this.notifyObj2); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj2); // check notifyObj1 anchor icon is showing @@ -55,7 +55,7 @@ var tests = [ dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { this.notification1.remove(); ok(this.notifyObj1.removedCallbackTriggered, "removed callback triggered"); @@ -65,7 +65,7 @@ var tests = [ }, // Test that multiple notification icons are removed when switching tabs { id: "Test#3", - *run() { + run: function* () { // show the notification on old tab. this.notifyObjOld = new BasicNotification(this.id); this.notifyObjOld.anchorID = "default-notification-icon"; @@ -80,7 +80,7 @@ var tests = [ this.notifyObjNew.anchorID = "geo-notification-icon"; this.notificationNew = showNotification(this.notifyObjNew); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObjNew); // check notifyObjOld anchor icon is removed @@ -92,7 +92,7 @@ var tests = [ dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { this.notificationNew.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -102,14 +102,14 @@ var tests = [ }, // test security delay - too early { id: "Test#4", - run() { + run: function() { // Set the security delay to 100s PopupNotifications.buttonDelay = 100000; this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); @@ -119,21 +119,21 @@ var tests = [ }); }, - onHidden(popup) { + onHidden: function(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked because it was too soon"); ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); } }, // test security delay - after delay { id: "Test#5", - run() { + run: function() { // Set the security delay to 10ms PopupNotifications.buttonDelay = 10; this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); // Wait until after the delay to trigger the main action @@ -142,7 +142,7 @@ var tests = [ }, 500); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.mainActionClicked, "mainAction was clicked after the delay"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback was not triggered"); PopupNotifications.buttonDelay = PREF_SECURITY_DELAY_INITIAL; @@ -150,7 +150,7 @@ var tests = [ }, // reload removes notification { id: "Test#6", - *run() { + run: function* () { yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); let notifyObj = new BasicNotification(this.id); notifyObj.options.eventCallback = function(eventName) { @@ -167,7 +167,7 @@ var tests = [ }, // location change in background tab removes notification { id: "Test#7", - *run() { + run: function* () { let oldSelectedTab = gBrowser.selectedTab; let newTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); gBrowser.selectedTab = oldSelectedTab; @@ -192,7 +192,7 @@ var tests = [ }, // Popup notification anchor shouldn't disappear when a notification with the same ID is re-added in a background tab { id: "Test#8", - *run() { + run: function* () { yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); let originalTab = gBrowser.selectedTab; let bgTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -227,7 +227,7 @@ var tests = [ }, // location change in an embedded frame should not remove a notification { id: "Test#9", - *run() { + run: function* () { yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html;charset=utf8,"); this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.eventCallback = function(eventName) { @@ -237,7 +237,7 @@ var tests = [ }; showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { let self = this; let progressListener = { onLocationChange: function onLocationChange() { @@ -259,11 +259,11 @@ var tests = [ content.document.getElementById("iframe") .setAttribute("src", "http://example.org/"); }, - onHidden() {} + onHidden: function() {} }, // Popup Notifications should catch exceptions from callbacks { id: "Test#10", - run() { + run: function() { this.testNotif1 = new BasicNotification(this.id); this.testNotif1.message += " 1"; this.notification1 = showNotification(this.testNotif1); @@ -285,11 +285,11 @@ var tests = [ }; this.notification2 = showNotification(this.testNotif2); }, - onShown(popup) { + onShown: function(popup) { is(popup.childNodes.length, 2, "two notifications are shown"); dismissNotification(popup); }, - onHidden() { + onHidden: function() { this.notification1.remove(); this.notification2.remove(); } diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_4.js b/browser/base/content/test/popupNotifications/browser_popupNotification_4.js index 4780d52afcb3..466670cf1d33 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_4.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_4.js @@ -14,41 +14,41 @@ function test() { var tests = [ // Popup Notifications main actions should catch exceptions from callbacks { id: "Test#1", - run() { + run: function() { this.testNotif = new ErrorNotification(this.id); showNotification(this.testNotif); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.testNotif); triggerMainCommand(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.testNotif.mainActionClicked, "main action has been triggered"); } }, // Popup Notifications secondary actions should catch exceptions from callbacks { id: "Test#2", - run() { + run: function() { this.testNotif = new ErrorNotification(this.id); showNotification(this.testNotif); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.testNotif); triggerSecondaryCommand(popup, 0); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.testNotif.secondaryActionClicked, "secondary action has been triggered"); } }, // Existing popup notification shouldn't disappear when adding a dismissed notification { id: "Test#3", - run() { + run: function() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; this.notification1 = showNotification(this.notifyObj1); }, - onShown(popup) { + onShown: function(popup) { // Now show a dismissed notification, and check that it doesn't clobber // the showing one. this.notifyObj2 = new BasicNotification(this.id); @@ -67,14 +67,14 @@ var tests = [ dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { this.notification1.remove(); this.notification2.remove(); } }, // Showing should be able to modify the popup data { id: "Test#4", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); let normalCallback = this.notifyObj.options.eventCallback; this.notifyObj.options.eventCallback = function(eventName) { @@ -85,18 +85,18 @@ var tests = [ }; showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { // checkPopup checks for the matching label. Note that this assumes that // this.notifyObj.mainAction is the same as notification.mainAction, // which could be a problem if we ever decided to deep-copy. checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden() { } + onHidden: function() { } }, // Moving a tab to a new window should remove non-swappable notifications. { id: "Test#5", - *run() { + run: function* () { yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); let notifyObj = new BasicNotification(this.id); @@ -124,7 +124,7 @@ var tests = [ }, // Moving a tab to a new window should preserve swappable notifications. { id: "Test#6", - *run() { + run: function* () { yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); let notifyObj = new BasicNotification(this.id); let originalCallback = notifyObj.options.eventCallback; @@ -165,16 +165,16 @@ var tests = [ }, // the main action callback can keep the notification. { id: "Test#8", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction.dismiss = true; this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); ok(!this.notifyObj.removedCallbackTriggered, "removed callback wasn't triggered"); this.notification.remove(); @@ -182,16 +182,16 @@ var tests = [ }, // a secondary action callback can keep the notification. { id: "Test#9", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions[0].dismiss = true; this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 0); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); ok(!this.notifyObj.removedCallbackTriggered, "removed callback wasn't triggered"); this.notification.remove(); @@ -199,7 +199,7 @@ var tests = [ }, // returning true in the showing callback should dismiss the notification. { id: "Test#10", - run() { + run: function() { let notifyObj = new BasicNotification(this.id); let originalCallback = notifyObj.options.eventCallback; notifyObj.options.eventCallback = function(eventName) { diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_5.js b/browser/base/content/test/popupNotifications/browser_popupNotification_5.js index 83c0aebe6e02..99cb6b824447 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_5.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_5.js @@ -16,11 +16,11 @@ var gNotification; var tests = [ // panel updates should fire the showing and shown callbacks again. { id: "Test#1", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); this.notifyObj.showingCallbackTriggered = false; @@ -35,11 +35,11 @@ var tests = [ this.notification.remove(); }, - onHidden() { } + onHidden: function() { } }, // A first dismissed notification shouldn't stop _update from showing a second notification { id: "Test#2", - run() { + run: function() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -55,16 +55,16 @@ var tests = [ this.notification2.dismissed = false; PopupNotifications._update(); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj2); this.notification1.remove(); this.notification2.remove(); }, - onHidden(popup) { } + onHidden: function(popup) { } }, // The anchor icon should be shown for notifications in background windows. { id: "Test#3", - *run() { + run: function* () { let notifyObj = new BasicNotification(this.id); notifyObj.options.dismissed = true; @@ -84,7 +84,7 @@ var tests = [ // Test that persistent doesn't allow the notification to persist after // navigation. { id: "Test#4", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -93,7 +93,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); @@ -105,7 +105,7 @@ var tests = [ this.complete = true; triggerSecondaryCommand(popup, 0); }, - onHidden(popup) { + onHidden: function(popup) { ok(!this.complete, "Should have hidden the notification after navigation"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -115,7 +115,7 @@ var tests = [ // Test that persistent allows the notification to persist until explicitly // dismissed. { id: "Test#5", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -124,7 +124,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { this.complete = false; // Notification should persist after attempt to dismiss by clicking on the @@ -136,7 +136,7 @@ var tests = [ this.complete = true; triggerSecondaryCommand(popup, 0); }, - onHidden(popup) { + onHidden: function(popup) { ok(this.complete, "Should have hidden the notification after clicking Not Now"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -146,16 +146,16 @@ var tests = [ // Test that persistent panels are still open after switching to another tab // and back. { id: "Test#6a", - *run() { + run: function* () { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.persistent = true; gNotification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); }, - onHidden(popup) { + onHidden: function(popup) { ok(true, "Should have hidden the notification after tab switch"); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -164,7 +164,7 @@ var tests = [ // Second part of the previous test that compensates for the limitation in // runNextTest that expects a single onShown/onHidden invocation per test. { id: "Test#6b", - *run() { + run: function* () { let id = PopupNotifications.panel.firstChild.getAttribute("popupid"); ok(id.endsWith("Test#6a"), "Should have found the notification from Test6a"); ok(PopupNotifications.isPanelOpen, "Should have shown the popup again after getting back to the tab"); @@ -176,7 +176,7 @@ var tests = [ // Test that persistent panels are still open after switching to another // window and back. { id: "Test#7", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -213,7 +213,7 @@ var tests = [ }, // Test that only the first persistent notification is shown on update { id: "Test#8", - run() { + run: function() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -228,16 +228,16 @@ var tests = [ PopupNotifications._update(); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj1); this.notification1.remove(); this.notification2.remove(); }, - onHidden(popup) { } + onHidden: function(popup) { } }, // Test that persistent notifications are shown stacked by anchor on update { id: "Test#9", - run() { + run: function() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -258,7 +258,7 @@ var tests = [ PopupNotifications._update(); }, - onShown(popup) { + onShown: function(popup) { let notifications = popup.childNodes; is(notifications.length, 2, "two notifications displayed"); let [notification1, notification2] = notifications; @@ -269,6 +269,6 @@ var tests = [ this.notification2.remove(); this.notification3.remove(); }, - onHidden(popup) { } + onHidden: function(popup) { } }, ]; diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js b/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js index 41b55db04b2a..0516164d8236 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js @@ -37,25 +37,25 @@ var gNotification; var tests = [ // Test that passing the checkbox field shows the checkbox. { id: "show_checkbox", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", }; gNotification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; checkCheckbox(notification.checkbox, "This is a checkbox"); triggerMainCommand(popup); }, - onHidden() { } + onHidden: function() { } }, // Test checkbox being checked by default { id: "checkbox_checked", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "Check this", @@ -63,18 +63,18 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; checkCheckbox(notification.checkbox, "Check this", true); triggerMainCommand(popup); }, - onHidden() { } + onHidden: function() { } }, // Test checkbox passing the checkbox state on mainAction { id: "checkbox_passCheckboxChecked_mainAction", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction.callback = ({checkboxChecked}) => this.mainActionChecked = checkboxChecked; this.notifyObj.options.checkbox = { @@ -82,7 +82,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -92,14 +92,14 @@ var tests = [ checkCheckbox(checkbox, "This is a checkbox", true); triggerMainCommand(popup); }, - onHidden() { + onHidden: function() { is(this.mainActionChecked, true, "mainAction callback is passed the correct checkbox value"); } }, // Test checkbox passing the checkbox state on secondaryAction { id: "checkbox_passCheckboxChecked_secondaryAction", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions = [{ label: "Test Secondary", @@ -111,7 +111,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -121,14 +121,14 @@ var tests = [ checkCheckbox(checkbox, "This is a checkbox", true); triggerSecondaryCommand(popup, 0); }, - onHidden() { + onHidden: function() { is(this.secondaryActionChecked, true, "secondaryAction callback is passed the correct checkbox value"); } }, // Test checkbox preserving its state through re-opening the doorhanger { id: "checkbox_reopen", - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", @@ -139,7 +139,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -148,7 +148,7 @@ var tests = [ EventUtils.synthesizeMouseAtCenter(checkbox, {}); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { let icon = document.getElementById("default-notification-icon"); EventUtils.synthesizeMouseAtCenter(icon, {}); let notification = popup.childNodes[0]; @@ -165,11 +165,11 @@ var tests = [ [true, false].forEach(function(checked) { tests.push( { id: `checkbox_disableMainAction_${state}_${checked ? 'checked' : 'unchecked'}`, - run() { + run: function() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", - checked, + checked: checked, [state]: { disableMainAction: true, warningLabel: "Testing disable", @@ -177,7 +177,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -200,7 +200,7 @@ var tests = [ } triggerMainCommand(popup); }, - onHidden() { } + onHidden: function() { } } ); }); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js b/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js index 30ce48bddead..1065ac6aacef 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js @@ -15,7 +15,7 @@ var tests = [ // Test that popupnotifications are anchored to the identity icon on // about:blank, where anchor icons are hidden. { id: "Test#1", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"); @@ -23,7 +23,7 @@ var tests = [ this.notifyObj.anchorID = "geo-notification-icon"; this.notification = showNotification(this.notifyObj); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); is(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor shouldn't be visible"); @@ -31,7 +31,7 @@ var tests = [ "notification anchored to identity icon"); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -40,7 +40,7 @@ var tests = [ // Test that popupnotifications are anchored to the identity icon after // navigation to about:blank. { id: "Test#2", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -51,7 +51,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - *onShown(popup) { + onShown: function* (popup) { yield promiseTabLoadEvent(gBrowser.selectedTab, "about:blank"); checkPopup(popup, this.notifyObj); @@ -61,7 +61,7 @@ var tests = [ "notification anchored to identity icon"); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -70,7 +70,7 @@ var tests = [ // Test that dismissed popupnotifications cannot be opened on about:blank, but // can be opened after navigation. { id: "Test#3", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"); @@ -92,11 +92,11 @@ var tests = [ EventUtils.synthesizeMouse(document.getElementById("geo-notification-icon"), 0, 0, {}); }, - onShown(popup) { + onShown: function(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden(popup) { + onHidden: function(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -106,7 +106,7 @@ var tests = [ // editing the URL in the location bar, and restored to their anchors when the // URL is reverted. { id: "Test#4", - *run() { + run: function* () { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); diff --git a/browser/base/content/test/social/browser_aboutHome_activation.js b/browser/base/content/test/social/browser_aboutHome_activation.js index 5d7dada0f9bc..9b3d599ba0eb 100644 --- a/browser/base/content/test/social/browser_aboutHome_activation.js +++ b/browser/base/content/test/social/browser_aboutHome_activation.js @@ -57,7 +57,7 @@ var gTests = [ { desc: "Test activation with enable panel", - snippet, + snippet: snippet, panel: true }, diff --git a/browser/base/content/test/social/browser_addons.js b/browser/base/content/test/social/browser_addons.js index c5bf44dd6c1b..c57314282013 100644 --- a/browser/base/content/test/social/browser_addons.js +++ b/browser/base/content/test/social/browser_addons.js @@ -57,26 +57,26 @@ function installListener(next, aManifest) { }); return { - onInstalling(addon) { + onInstalling: function(addon) { is(expectEvent, "onInstalling", "install started"); is(addon.manifest.origin, aManifest.origin, "provider about to be installed"); ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs"); expectEvent = "onInstalled"; }, - onInstalled(addon) { + onInstalled: function(addon) { is(addon.manifest.origin, aManifest.origin, "provider installed"); ok(addon.installDate.getTime() > 0, "addon has installDate"); ok(addon.updateDate.getTime() > 0, "addon has updateDate"); ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs"); expectEvent = "onUninstalling"; }, - onUninstalling(addon) { + onUninstalling: function(addon) { is(expectEvent, "onUninstalling", "uninstall started"); is(addon.manifest.origin, aManifest.origin, "provider about to be uninstalled"); ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs"); expectEvent = "onUninstalled"; }, - onUninstalled(addon) { + onUninstalled: function(addon) { is(expectEvent, "onUninstalled", "provider has been uninstalled"); is(addon.manifest.origin, aManifest.origin, "provider uninstalled"); ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs"); @@ -86,25 +86,25 @@ function installListener(next, aManifest) { } var tests = { - testHTTPInstallFailure(next) { + testHTTPInstallFailure: function(next) { let installFrom = "http://example.com"; is(SocialService.getOriginActivationType(installFrom), "foreign", "testing foriegn install"); let data = { origin: installFrom, url: installFrom + "/activate", - manifest, - window + manifest: manifest, + window: window } Social.installProvider(data, function(addonManifest) { ok(!addonManifest, "unable to install provider over http"); next(); }); }, - testAddonEnableToggle(next) { + testAddonEnableToggle: function(next) { let expectEvent; let prefname = getManifestPrefname(manifest); let listener = { - onEnabled(addon) { + onEnabled: function(addon) { is(expectEvent, "onEnabled", "provider onEnabled"); ok(!addon.userDisabled, "provider enabled"); executeSoon(function() { @@ -112,11 +112,11 @@ var tests = { addon.userDisabled = true; }); }, - onEnabling(addon) { + onEnabling: function(addon) { is(expectEvent, "onEnabling", "provider onEnabling"); expectEvent = "onEnabled"; }, - onDisabled(addon) { + onDisabled: function(addon) { is(expectEvent, "onDisabled", "provider onDisabled"); ok(addon.userDisabled, "provider disabled"); AddonManager.removeAddonListener(listener); @@ -124,7 +124,7 @@ var tests = { Services.prefs.clearUserPref(prefname); executeSoon(next); }, - onDisabling(addon) { + onDisabling: function(addon) { is(expectEvent, "onDisabling", "provider onDisabling"); expectEvent = "onDisabled"; } @@ -148,7 +148,7 @@ var tests = { next(); }); }, - testProviderEnableToggle(next) { + testProviderEnableToggle: function(next) { // enable and disabel a provider from the SocialService interface, check // that the addon manager is updated @@ -156,22 +156,22 @@ var tests = { let prefname = getManifestPrefname(manifest); let listener = { - onEnabled(addon) { + onEnabled: function(addon) { is(expectEvent, "onEnabled", "provider onEnabled"); is(addon.manifest.origin, manifest.origin, "provider enabled"); ok(!addon.userDisabled, "provider !userDisabled"); }, - onEnabling(addon) { + onEnabling: function(addon) { is(expectEvent, "onEnabling", "provider onEnabling"); is(addon.manifest.origin, manifest.origin, "provider about to be enabled"); expectEvent = "onEnabled"; }, - onDisabled(addon) { + onDisabled: function(addon) { is(expectEvent, "onDisabled", "provider onDisabled"); is(addon.manifest.origin, manifest.origin, "provider disabled"); ok(addon.userDisabled, "provider userDisabled"); }, - onDisabling(addon) { + onDisabling: function(addon) { is(expectEvent, "onDisabling", "provider onDisabling"); is(addon.manifest.origin, manifest.origin, "provider about to be disabled"); expectEvent = "onDisabled"; @@ -190,7 +190,7 @@ var tests = { }); }); }, - testDirectoryInstall(next) { + testDirectoryInstall: function(next) { AddonManager.addAddonListener(installListener(next, manifest2)); BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown").then(() => { @@ -205,7 +205,7 @@ var tests = { origin: manifest2.origin, url: manifest2.origin + "/directory", manifest: manifest2, - window + window: window } Social.installProvider(data, function(addonManifest) { Services.prefs.clearUserPref("social.directories"); diff --git a/browser/base/content/test/social/browser_blocklist.js b/browser/base/content/test/social/browser_blocklist.js index 9a340b633738..074583498fc6 100644 --- a/browser/base/content/test/social/browser_blocklist.js +++ b/browser/base/content/test/social/browser_blocklist.js @@ -66,7 +66,7 @@ function test() { } var tests = { - testSimpleBlocklist(next) { + testSimpleBlocklist: function(next) { // this really just tests adding and clearing our blocklist for later tests setAndUpdateBlocklist(blocklistURL).then(() => { ok(Services.blocklist.isAddonBlocklisted(SocialService.createWrapper(manifest_bad)), "blocking 'blocked'"); @@ -77,7 +77,7 @@ var tests = { }); }); }, - testAddingNonBlockedProvider(next) { + testAddingNonBlockedProvider: function(next) { function finishTest(isgood) { ok(isgood, "adding non-blocked provider ok"); Services.prefs.clearUserPref("social.manifest.good"); @@ -103,7 +103,7 @@ var tests = { } }); }, - testAddingBlockedProvider(next) { + testAddingBlockedProvider: function(next) { function finishTest(good) { ok(good, "Unable to add blocklisted provider"); Services.prefs.clearUserPref("social.manifest.blocked"); @@ -124,7 +124,7 @@ var tests = { } }); }, - testInstallingBlockedProvider(next) { + testInstallingBlockedProvider: function(next) { function finishTest(good) { ok(good, "Unable to install blocklisted provider"); resetBlocklist().then(next); @@ -138,7 +138,7 @@ var tests = { origin: manifest_bad.origin, url: activationURL, manifest: manifest_bad, - window + window: window } Social.installProvider(data, function(addonManifest) { finishTest(false); @@ -148,10 +148,10 @@ var tests = { } }); }, - testBlockingExistingProvider(next) { + testBlockingExistingProvider: function(next) { let listener = { _window: null, - onOpenWindow(aXULWindow) { + onOpenWindow: function(aXULWindow) { Services.wm.removeListener(this); this._window = aXULWindow; let domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -177,8 +177,8 @@ var tests = { }); }, false); }, - onCloseWindow(aXULWindow) { }, - onWindowTitleChange(aXULWindow, aNewTitle) { } + onCloseWindow: function(aXULWindow) { }, + onWindowTitleChange: function(aXULWindow, aNewTitle) { } }; Services.wm.addListener(listener); diff --git a/browser/base/content/test/social/browser_share.js b/browser/base/content/test/social/browser_share.js index 74414b7dd86e..91de49b16857 100644 --- a/browser/base/content/test/social/browser_share.js +++ b/browser/base/content/test/social/browser_share.js @@ -135,7 +135,7 @@ function hasoptions(testOptions, options) { } var tests = { - testShareDisabledOnActivation(next) { + testShareDisabledOnActivation: function(next) { // starting on about:blank page, share should be visible but disabled when // adding provider is(gBrowser.currentURI.spec, "about:blank"); @@ -157,7 +157,7 @@ var tests = { SocialService.disableProvider(manifest.origin, next); }); }, - testShareEnabledOnActivation(next) { + testShareEnabledOnActivation: function(next) { // starting from *some* page, share should be visible and enabled when // activating provider // initialize the button into the navbar @@ -180,7 +180,7 @@ var tests = { }); }); }, - testSharePage(next) { + testSharePage: function(next) { let testTab; let testIndex = 0; let testData = corpus[testIndex++]; @@ -222,7 +222,7 @@ var tests = { } executeSoon(runOneTest); }, - testShareMicroformats(next) { + testShareMicroformats: function(next) { // initialize the button into the navbar CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR); // ensure correct state @@ -305,7 +305,7 @@ var tests = { }); }); }, - testSharePanelActivation(next) { + testSharePanelActivation: function(next) { let testTab; // cleared in the cleanup function Services.prefs.setCharPref("social.directories", "https://example.com"); @@ -352,7 +352,7 @@ var tests = { SocialShare.sharePage(); }); }, - testSharePanelDialog(next) { + testSharePanelDialog: function(next) { let testTab; // initialize the button into the navbar CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR); diff --git a/browser/base/content/test/social/browser_social_activation.js b/browser/base/content/test/social/browser_social_activation.js index 63b8b938e996..02c9b924f93f 100644 --- a/browser/base/content/test/social/browser_social_activation.js +++ b/browser/base/content/test/social/browser_social_activation.js @@ -186,7 +186,7 @@ function test() { } var tests = { - testActivationWrongOrigin(next) { + testActivationWrongOrigin: function(next) { // At this stage none of our providers exist, so we expect failure. Services.prefs.setBoolPref("social.remote-install.enabled", false); activateProvider(gTestDomains[0], function() { @@ -199,7 +199,7 @@ var tests = { }); }, - testIFrameActivation(next) { + testIFrameActivation: function(next) { activateIFrameProvider(gTestDomains[0], function() { is(SocialUI.enabled, false, "SocialUI is not enabled"); let panel = document.getElementById("servicesInstall-notification"); @@ -209,7 +209,7 @@ var tests = { }); }, - testActivationFirstProvider(next) { + testActivationFirstProvider: function(next) { // first up we add a manifest entry for a single provider. activateOneProvider(gProviders[0], false, function() { // we deactivated leaving no providers left, so Social is disabled. @@ -218,7 +218,7 @@ var tests = { }); }, - testActivationMultipleProvider(next) { + testActivationMultipleProvider: function(next) { // The trick with this test is to make sure that Social.providers[1] is // the current provider when doing the undo - this makes sure that the // Social code doesn't fallback to Social.providers[0], which it will @@ -237,7 +237,7 @@ var tests = { }); }, - testAddonManagerDoubleInstall(next) { + testAddonManagerDoubleInstall: function(next) { // Create a new tab and load about:addons let addonsTab = gBrowser.addTab(); gBrowser.selectedTab = addonsTab; diff --git a/browser/base/content/test/social/social_crash_content_helper.js b/browser/base/content/test/social/social_crash_content_helper.js index 1a876c3d6a14..4698b6957b4f 100644 --- a/browser/base/content/test/social/social_crash_content_helper.js +++ b/browser/base/content/test/social/social_crash_content_helper.js @@ -14,11 +14,11 @@ var crash = function() { // this will crash when called. var TestHelper = { - init() { + init: function() { addMessageListener("social-test:crash", this); }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "social-test:crash": privateNoteIntentionalCrash(); diff --git a/browser/base/content/test/urlbar/Panel.jsm b/browser/base/content/test/urlbar/Panel.jsm index 2e5eccadf5cc..ee1fd2ed93c9 100644 --- a/browser/base/content/test/urlbar/Panel.jsm +++ b/browser/base/content/test/urlbar/Panel.jsm @@ -105,8 +105,8 @@ this.Panel.prototype = { let url = controller.getValueAt(idx); let action = this.urlbar._parseActionUrl(url); this._emit("result", { - url, - action, + url: url, + action: action, image: controller.getImageAt(idx), title: controller.getCommentAt(idx), type: controller.getStyleAt(idx), diff --git a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js b/browser/base/content/test/urlbar/browser_autocomplete_no_title.js index 49e8f4609c9b..8d608550b313 100644 --- a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js +++ b/browser/base/content/test/urlbar/browser_autocomplete_no_title.js @@ -2,7 +2,7 @@ add_task(function*() { let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla"); let uri = NetUtil.newURI("http://bug1060642.example.com/beards/are/pretty/great"); - yield PlacesTestUtils.addVisits([{uri, title: ""}]); + yield PlacesTestUtils.addVisits([{uri: uri, title: ""}]); yield promiseAutocompleteResultPopup("bug1060642"); ok(gURLBar.popup.richlistbox.children.length > 1, "Should get at least 2 results"); diff --git a/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js b/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js index b6440b327bc2..8a69b4b44c54 100644 --- a/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js +++ b/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js @@ -10,7 +10,7 @@ add_task(function*() { PlacesUtils.bookmarks.DEFAULT_INDEX, `test ${tagName}`); PlacesUtils.tagging.tagURI(uri, [tagName]); - yield PlacesTestUtils.addVisits([{uri, title: `Test page with tag ${tagName}`}]); + yield PlacesTestUtils.addVisits([{uri: uri, title: `Test page with tag ${tagName}`}]); } // We use different tags for each part of the test, as otherwise the diff --git a/browser/base/content/test/urlbar/browser_bug556061.js b/browser/base/content/test/urlbar/browser_bug556061.js index d57e92c372d1..4c6ac5bf5230 100644 --- a/browser/base/content/test/urlbar/browser_bug556061.js +++ b/browser/base/content/test/urlbar/browser_bug556061.js @@ -28,7 +28,7 @@ function cleanup() { var tests = [ { expected: testURL, - setup() { + setup: function() { gURLBar.value = testActionURL; gURLBar.valueIsTyped = true; is(gURLBar.value, testActionURL, "gURLBar starts with the correct real value"); @@ -39,37 +39,37 @@ var tests = [ gURLBar.select(); goDoCommand("cmd_copy"); }, - success() { + success: function() { is(gURLBar.value, testActionURL, "gURLBar.value didn't change when copying"); } }, { expected: testURL.substring(0, 10), - setup() { + setup: function() { // Set selectionStart/End manually and make sure it matches the substring gURLBar.selectionStart = 0; gURLBar.selectionEnd = 10; goDoCommand("cmd_copy"); }, - success() { + success: function() { is(gURLBar.value, testActionURL, "gURLBar.value didn't change when copying"); } }, { expected: testURL, - setup() { + setup: function() { // Setup for cut test... // Select all gURLBar.select(); goDoCommand("cmd_cut"); }, - success() { + success: function() { is(gURLBar.value, "", "gURLBar.value is now empty"); } }, { expected: testURL.substring(testURL.length - 10, testURL.length), - setup() { + setup: function() { // Reset urlbar value gURLBar.value = testActionURL; gURLBar.valueIsTyped = true; @@ -82,7 +82,7 @@ var tests = [ gURLBar.selectionEnd = testURL.length; goDoCommand("cmd_cut"); }, - success() { + success: function() { is(gURLBar.value, testURL.substring(0, testURL.length - 10), "gURLBar.value has the correct value"); } } diff --git a/browser/base/content/test/urlbar/browser_bug623155.js b/browser/base/content/test/urlbar/browser_bug623155.js index 1d355395fcec..dd6ff8c85399 100644 --- a/browser/base/content/test/urlbar/browser_bug623155.js +++ b/browser/base/content/test/urlbar/browser_bug623155.js @@ -58,7 +58,7 @@ function test() { } var gWebProgressListener = { - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (aIID.equals(Components.interfaces.nsIWebProgressListener) || aIID.equals(Components.interfaces.nsISupportsWeakReference) || aIID.equals(Components.interfaces.nsISupports)) @@ -75,7 +75,7 @@ var gWebProgressListener = { // onSecurityChange: function() {}, // ---------------------------------------------------------------------------- - onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { if (!aRequest) { // This is bug 673752, or maybe initial "about:blank". return; diff --git a/browser/base/content/test/urlbar/browser_search_favicon.js b/browser/base/content/test/urlbar/browser_search_favicon.js index 4ab7bfd6ec73..a8e6dbbcd957 100644 --- a/browser/base/content/test/urlbar/browser_search_favicon.js +++ b/browser/base/content/test/urlbar/browser_search_favicon.js @@ -23,7 +23,7 @@ add_task(function*() { Services.search.currentEngine = gEngine; let uri = NetUtil.newURI("http://s.example.com/search?q=foo&client=1"); - yield PlacesTestUtils.addVisits({ uri, title: "Foo - SearchEngine Search" }); + yield PlacesTestUtils.addVisits({ uri: uri, title: "Foo - SearchEngine Search" }); yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla"); diff --git a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js b/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js index 5b5fd3e6d1e9..6fde02895311 100644 --- a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js +++ b/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js @@ -171,12 +171,12 @@ function checkAutocompleteResults(aExpected, aCallback) searchParam: "enable-actions", popupOpen: false, minResultsForPopup: 0, - invalidate() {}, + invalidate: function() {}, disableAutoComplete: false, completeDefaultIndex: false, get popup() { return this; }, - onSearchBegin() {}, - onSearchComplete() + onSearchBegin: function() {}, + onSearchComplete: function() { info("Found " + gController.matchCount + " matches."); // Check to see the expected uris and titles match up (in any order) @@ -202,9 +202,9 @@ function checkAutocompleteResults(aExpected, aCallback) executeSoon(aCallback); }, - setSelectedIndex() {}, + setSelectedIndex: function() {}, get searchCount() { return this.searches.length; }, - getSearchAt(aIndex) { return this.searches[aIndex]; }, + getSearchAt: function(aIndex) { return this.searches[aIndex]; }, QueryInterface: XPCOMUtils.generateQI([ Ci.nsIAutoCompleteInput, Ci.nsIAutoCompletePopup, diff --git a/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js b/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js index 102c65efd948..05c54ba251f3 100644 --- a/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js +++ b/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js @@ -184,18 +184,18 @@ function promiseMessage(type, data, numExpectedAcks = 1) { let ackMsgName = "TestMessageAck"; let msgID = gNextMessageID++; gMsgMan.sendAsyncMessage(testMsgName, { - type, + type: type, messageID: msgID, - data, + data: data, }); let ackPromises = []; for (let i = 0; i < numExpectedAcks; i++) { let ackIndex = i; ackPromises.push(new Promise(resolve => { info("Waiting for message ack: " + JSON.stringify({ - type, - msgID, - ackIndex, + type: type, + msgID: msgID, + ackIndex: ackIndex, })); gMsgMan.addMessageListener(ackMsgName, function onMsg(msg) { // Messages have IDs so that an ack can be correctly paired with the @@ -207,9 +207,9 @@ function promiseMessage(type, data, numExpectedAcks = 1) { return; } info("Received message ack: " + JSON.stringify({ - type, + type: type, msgID: msg.data.messageID, - ackIndex, + ackIndex: ackIndex, })); gMsgMan.removeMessageListener(ackMsgName, onMsg); resolve(msg.data.data); diff --git a/browser/base/content/test/urlbar/browser_urlbarCopying.js b/browser/base/content/test/urlbar/browser_urlbarCopying.js index aa7289f4c0c5..8c1d262d6d3b 100644 --- a/browser/base/content/test/urlbar/browser_urlbarCopying.js +++ b/browser/base/content/test/urlbar/browser_urlbarCopying.js @@ -153,7 +153,7 @@ var tests = [ copyExpected: "data:text/html,(%C3%A9 %25P", }, { - setup() { Services.prefs.setBoolPref(decodeURLpref, true); }, + setup: function() { Services.prefs.setBoolPref(decodeURLpref, true); }, loadURL: "http://example.com/%D0%B1%D0%B8%D0%BE%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D1%8F", expectedURL: toUnicode("example.com/биография"), copyExpected: toUnicode("http://example.com/биография") diff --git a/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js b/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js index 485c9ec0db05..8c28401eae0e 100644 --- a/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js +++ b/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js @@ -188,7 +188,7 @@ function getActionAtIndex(index) { } let [, type, paramStr] = mozActionMatch; return { - type, + type: type, params: JSON.parse(paramStr), }; } diff --git a/browser/base/content/test/urlbar/head.js b/browser/base/content/test/urlbar/head.js index cb39ce9262c6..d1288a8db751 100644 --- a/browser/base/content/test/urlbar/head.js +++ b/browser/base/content/test/urlbar/head.js @@ -46,7 +46,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows } let progressListener = { - onStateChange(webProgress, req, flags, status) { + onStateChange: function(webProgress, req, flags, status) { dump("waitForDocLoadAndStopIt: onStateChange " + flags.toString(16) + ": " + req.name + "\n"); if (webProgress.isTopLevel && @@ -190,12 +190,12 @@ function promiseNewSearchEngine(basename) { info("Waiting for engine to be added: " + basename); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess(engine) { + onSuccess: function(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => Services.search.removeEngine(engine)); resolve(engine); }, - onError(errCode) { + onError: function(errCode) { Assert.ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/urlbar/urlbarAddonIframe.js b/browser/base/content/test/urlbar/urlbarAddonIframe.js index 3f8f9a83aa78..d25ab0bc95c4 100644 --- a/browser/base/content/test/urlbar/urlbarAddonIframe.js +++ b/browser/base/content/test/urlbar/urlbarAddonIframe.js @@ -45,7 +45,7 @@ function ack(originalEventDetail, ackData = null, ackIndex = 0) { dispatchEvent(new CustomEvent("TestEventAck", { detail: { messageID: originalEventDetail.messageID, - ackIndex, + ackIndex: ackIndex, data: ackData, }, })); diff --git a/browser/base/content/urlbarBindings.xml b/browser/base/content/urlbarBindings.xml index bdde5bb60f0b..8f40d7129e23 100644 --- a/browser/base/content/urlbarBindings.xml +++ b/browser/base/content/urlbarBindings.xml @@ -825,7 +825,7 @@ file, You can obtain one at http://mozilla.org/MPL/2.0/. @@ -1019,7 +1019,7 @@ file, You can obtain one at http://mozilla.org/MPL/2.0/. let [, type, params] = aUrl.match(MOZ_ACTION_REGEX); let action = { - type, + type: type, }; action.params = JSON.parse(params); @@ -1114,7 +1114,7 @@ file, You can obtain one at http://mozilla.org/MPL/2.0/. // handleEnter, in such a case it won't have been cleared. this.handleEnterInstance = { searchString: this.mController.searchString, - event + event: event }; if (this.popup.selectedIndex != 0 || this.gotResultForCurrentQuery) { diff --git a/browser/base/content/utilityOverlay.js b/browser/base/content/utilityOverlay.js index ab7849e6db5c..a8f5e747b2c8 100644 --- a/browser/base/content/utilityOverlay.js +++ b/browser/base/content/utilityOverlay.js @@ -383,7 +383,7 @@ function openLinkIn(url, where, params) { } targetBrowser.loadURIWithFlags(url, { - flags, + flags: flags, referrerURI: aNoReferrer ? null : aReferrerURI, referrerPolicy: aReferrerPolicy, postData: aPostData, diff --git a/browser/base/content/web-panels.js b/browser/base/content/web-panels.js index 3bf8c726e6fc..ceb0016fdff6 100644 --- a/browser/base/content/web-panels.js +++ b/browser/base/content/web-panels.js @@ -13,12 +13,12 @@ function getPanelBrowser() } var panelProgressListener = { - onProgressChange(aWebProgress, aRequest, + onProgressChange : function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { }, - onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) + onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus) { if (!aRequest) return; @@ -38,17 +38,17 @@ var panelProgressListener = { } , - onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags) { UpdateBackForwardCommands(getPanelBrowser().webNavigation); }, - onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) { }, - onSecurityChange(aWebProgress, aRequest, aState) { + onSecurityChange : function(aWebProgress, aRequest, aState) { }, - QueryInterface(aIID) + QueryInterface : function(aIID) { if (aIID.equals(Ci.nsIWebProgressListener) || aIID.equals(Ci.nsISupportsWeakReference) || diff --git a/browser/base/content/webrtcIndicator.js b/browser/base/content/webrtcIndicator.js index 9b4d78066a44..a8bb64367c48 100644 --- a/browser/base/content/webrtcIndicator.js +++ b/browser/base/content/webrtcIndicator.js @@ -129,7 +129,7 @@ function onFirefoxButtonClick(event) { var PositionHandler = { positionCustomized: false, threshold: 10, - adjustPosition() { + adjustPosition: function() { if (!this.positionCustomized) { // Center the window horizontally on the screen (not the available area). // Until we have moved the window to y=0, 'screen.width' may give a value @@ -150,14 +150,14 @@ var PositionHandler = { this.setXPosition(window.screenX); } }, - setXPosition(desiredX) { + setXPosition: function(desiredX) { // Ensure the indicator isn't moved outside the available area of the screen. desiredX = Math.max(desiredX, screen.availLeft); let maxX = screen.availLeft + screen.availWidth - document.documentElement.clientWidth; window.moveTo(Math.min(desiredX, maxX), screen.availTop); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "mousedown": if (aEvent.button != 0 || aEvent.defaultPrevented) diff --git a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js index 580d29843dc3..310a94166610 100644 --- a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js +++ b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js @@ -98,22 +98,22 @@ function OpenCacheEntry(key, where, flags, lci) CacheListener.prototype = { _appCache: null, - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Components.interfaces.nsICacheEntryOpenCallback) || iid.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_ERROR_NO_INTERFACE; }, - onCacheEntryCheck(entry, appCache) { + onCacheEntryCheck: function(entry, appCache) { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable(entry, isnew, appCache, status) { + onCacheEntryAvailable: function(entry, isnew, appCache, status) { resolve(); }, - run() { + run: function() { let storage = getCacheStorage(where, lci, this._appCache); storage.asyncOpenURI(key, "", flags, this); } diff --git a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js index e874494ec462..9875c8aa1b73 100644 --- a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js +++ b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js @@ -78,7 +78,7 @@ function allRegistered() { function promiseAllRegistered() { return new Promise(function(resolve) { let listener = { - onRegister() { + onRegister: function() { if (allRegistered()) { swm.removeListener(listener); resolve(); @@ -92,11 +92,11 @@ function promiseAllRegistered() { function promiseUnregister(info) { return new Promise(function(resolve) { swm.unregister(info.principal, { - unregisterSucceeded(aState) { + unregisterSucceeded: function(aState) { ok(aState, "ServiceWorkerRegistration exists"); resolve(); }, - unregisterFailed(aState) { + unregisterFailed: function(aState) { ok(false, "unregister should succeed"); } }, info.scope); diff --git a/browser/components/customizableui/CustomizableUI.jsm b/browser/components/customizableui/CustomizableUI.jsm index 81f4da46b2da..a9cef9dd1a34 100644 --- a/browser/components/customizableui/CustomizableUI.jsm +++ b/browser/components/customizableui/CustomizableUI.jsm @@ -170,7 +170,7 @@ XPCOMUtils.defineLazyGetter(this, "log", () => { }); var CustomizableUIInternal = { - initialize() { + initialize: function() { log.debug("Initializing"); this.addListener(this); @@ -323,13 +323,13 @@ var CustomizableUIInternal = { return toolbars; }, - _defineBuiltInWidgets() { + _defineBuiltInWidgets: function() { for (let widgetDefinition of CustomizableWidgets) { this.createBuiltinWidget(widgetDefinition); } }, - _introduceNewBuiltinWidgets() { + _introduceNewBuiltinWidgets: function() { // We should still enter even if gSavedState.currentVersion >= kVersion // because the per-widget pref facility is independent of versioning. if (!gSavedState) { @@ -389,7 +389,7 @@ var CustomizableUIInternal = { * _markObsoleteBuiltinButtonsSeen * when upgrading, ensure obsoleted buttons are in seen state. */ - _markObsoleteBuiltinButtonsSeen() { + _markObsoleteBuiltinButtonsSeen: function() { if (!gSavedState) return; let currentVersion = gSavedState.currentVersion; @@ -405,7 +405,7 @@ var CustomizableUIInternal = { } }, - _placeNewDefaultWidgetsInArea(aArea) { + _placeNewDefaultWidgetsInArea: function(aArea) { let futurePlacedWidgets = gFuturePlacements.get(aArea); let savedPlacements = gSavedState && gSavedState.placements && gSavedState.placements[aArea]; let defaultPlacements = gAreas.get(aArea).get("defaultPlacements"); @@ -459,7 +459,7 @@ var CustomizableUIInternal = { this.saveState(); }, - wrapWidget(aWidgetId) { + wrapWidget: function(aWidgetId) { if (gGroupWrapperCache.has(aWidgetId)) { return gGroupWrapperCache.get(aWidgetId); } @@ -484,7 +484,7 @@ var CustomizableUIInternal = { return wrapper; }, - registerArea(aName, aProperties, aInternalCaller) { + registerArea: function(aName, aProperties, aInternalCaller) { if (typeof aName != "string" || !/^[a-z0-9-_]{1,}$/i.test(aName)) { throw new Error("Invalid area name"); } @@ -563,7 +563,7 @@ var CustomizableUIInternal = { } }, - unregisterArea(aName, aDestroyPlacements) { + unregisterArea: function(aName, aDestroyPlacements) { if (typeof aName != "string" || !/^[a-z0-9-_]{1,}$/i.test(aName)) { throw new Error("Invalid area name"); } @@ -605,7 +605,7 @@ var CustomizableUIInternal = { } }, - registerToolbarNode(aToolbar, aExistingChildren) { + registerToolbarNode: function(aToolbar, aExistingChildren) { let area = aToolbar.id; if (gBuildAreas.has(area) && gBuildAreas.get(area).has(aToolbar)) { return; @@ -677,7 +677,7 @@ var CustomizableUIInternal = { } }, - buildArea(aArea, aPlacements, aAreaNode) { + buildArea: function(aArea, aPlacements, aAreaNode) { let document = aAreaNode.ownerDocument; let window = document.defaultView; let inPrivateWindow = PrivateBrowsingUtils.isWindowPrivate(window); @@ -813,7 +813,7 @@ var CustomizableUIInternal = { } }, - addPanelCloseListeners(aPanel) { + addPanelCloseListeners: function(aPanel) { gELS.addSystemEventListener(aPanel, "click", this, false); gELS.addSystemEventListener(aPanel, "keypress", this, false); let win = aPanel.ownerGlobal; @@ -823,7 +823,7 @@ var CustomizableUIInternal = { gPanelsForWindow.get(win).add(this._getPanelForNode(aPanel)); }, - removePanelCloseListeners(aPanel) { + removePanelCloseListeners: function(aPanel) { gELS.removeSystemEventListener(aPanel, "click", this, false); gELS.removeSystemEventListener(aPanel, "keypress", this, false); let win = aPanel.ownerGlobal; @@ -833,7 +833,7 @@ var CustomizableUIInternal = { } }, - ensureButtonContextMenu(aNode, aAreaNode) { + ensureButtonContextMenu: function(aNode, aAreaNode) { const kPanelItemContextMenu = "customizationPanelItemContextMenu"; let currentContextMenu = aNode.getAttribute("context") || @@ -851,7 +851,7 @@ var CustomizableUIInternal = { } }, - getWidgetProvider(aWidgetId) { + getWidgetProvider: function(aWidgetId) { if (this.isSpecialWidget(aWidgetId)) { return CustomizableUI.PROVIDER_SPECIAL; } @@ -871,7 +871,7 @@ var CustomizableUIInternal = { return CustomizableUI.PROVIDER_XUL; }, - getWidgetNode(aWidgetId, aWindow) { + getWidgetNode: function(aWidgetId, aWindow) { let document = aWindow.document; if (this.isSpecialWidget(aWidgetId)) { @@ -904,7 +904,7 @@ var CustomizableUIInternal = { return [null, null]; }, - registerMenuPanel(aPanelContents) { + registerMenuPanel: function(aPanelContents) { if (gBuildAreas.has(CustomizableUI.AREA_PANEL) && gBuildAreas.get(CustomizableUI.AREA_PANEL).has(aPanelContents)) { return; @@ -935,7 +935,7 @@ var CustomizableUIInternal = { this.registerBuildArea(CustomizableUI.AREA_PANEL, aPanelContents); }, - onWidgetAdded(aWidgetId, aArea, aPosition) { + onWidgetAdded: function(aWidgetId, aArea, aPosition) { this.insertNode(aWidgetId, aArea, aPosition, true); if (!gResetting) { @@ -943,7 +943,7 @@ var CustomizableUIInternal = { } }, - onWidgetRemoved(aWidgetId, aArea) { + onWidgetRemoved: function(aWidgetId, aArea) { let areaNodes = gBuildAreas.get(aArea); if (!areaNodes) { return; @@ -1003,18 +1003,18 @@ var CustomizableUIInternal = { } }, - onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { this.insertNode(aWidgetId, aArea, aNewPosition); if (!gResetting) { this._clearPreviousUIState(); } }, - onCustomizeEnd(aWindow) { + onCustomizeEnd: function(aWindow) { this._clearPreviousUIState(); }, - registerBuildArea(aArea, aNode) { + registerBuildArea: function(aArea, aNode) { // We ensure that the window is registered to have its customization data // cleaned up when unloading. let window = aNode.ownerGlobal; @@ -1039,7 +1039,7 @@ var CustomizableUIInternal = { customizableNode.classList.add("customization-target"); }, - registerBuildWindow(aWindow) { + registerBuildWindow: function(aWindow) { if (!gBuildWindows.has(aWindow)) { gBuildWindows.set(aWindow, new Set()); @@ -1050,7 +1050,7 @@ var CustomizableUIInternal = { } }, - unregisterBuildWindow(aWindow) { + unregisterBuildWindow: function(aWindow) { aWindow.removeEventListener("unload", this); aWindow.removeEventListener("command", this, true); gPanelsForWindow.delete(aWindow); @@ -1093,7 +1093,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWindowClosed", aWindow); }, - setLocationAttributes(aNode, aArea) { + setLocationAttributes: function(aNode, aArea) { let props = gAreas.get(aArea); if (!props) { throw new Error("Expected area " + aArea + " to have a properties Map " + @@ -1109,12 +1109,12 @@ var CustomizableUIInternal = { } }, - removeLocationAttributes(aNode) { + removeLocationAttributes: function(aNode) { aNode.removeAttribute("cui-areatype"); aNode.removeAttribute("cui-anchorid"); }, - insertNode(aWidgetId, aArea, aPosition, isNew) { + insertNode: function(aWidgetId, aArea, aPosition, isNew) { let areaNodes = gBuildAreas.get(aArea); if (!areaNodes) { return; @@ -1134,7 +1134,7 @@ var CustomizableUIInternal = { } }, - insertNodeInWindow(aWidgetId, aAreaNode, isNew) { + insertNodeInWindow: function(aWidgetId, aAreaNode, isNew) { let window = aAreaNode.ownerGlobal; let showInPrivateBrowsing = gPalette.has(aWidgetId) ? gPalette.get(aWidgetId).showInPrivateBrowsing @@ -1166,7 +1166,7 @@ var CustomizableUIInternal = { } }, - findInsertionPoints(aNode, aAreaNode) { + findInsertionPoints: function(aNode, aAreaNode) { let areaId = aAreaNode.id; let props = gAreas.get(areaId); @@ -1191,14 +1191,14 @@ var CustomizableUIInternal = { return [container, null]; }, - insertWidgetBefore(aNode, aNextNode, aContainer, aArea) { + insertWidgetBefore: function(aNode, aNextNode, aContainer, aArea) { this.notifyListeners("onWidgetBeforeDOMChange", aNode, aNextNode, aContainer); this.setLocationAttributes(aNode, aArea); aContainer.insertBefore(aNode, aNextNode); this.notifyListeners("onWidgetAfterDOMChange", aNode, aNextNode, aContainer); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "command": if (!this._originalEventInPanel(aEvent)) { @@ -1216,7 +1216,7 @@ var CustomizableUIInternal = { } }, - _originalEventInPanel(aEvent) { + _originalEventInPanel: function(aEvent) { let e = aEvent.sourceEvent; if (!e) { return false; @@ -1230,14 +1230,14 @@ var CustomizableUIInternal = { return !!panels && panels.has(node); }, - isSpecialWidget(aId) { + isSpecialWidget: function(aId) { return (aId.startsWith(kSpecialWidgetPfx) || aId.startsWith("separator") || aId.startsWith("spring") || aId.startsWith("spacer")); }, - ensureSpecialWidgetId(aId) { + ensureSpecialWidgetId: function(aId) { let nodeType = aId.match(/spring|spacer|separator/)[0]; // If the ID we were passed isn't a generated one, generate one now: if (nodeType == aId) { @@ -1247,7 +1247,7 @@ var CustomizableUIInternal = { return aId; }, - createSpecialWidget(aId, aDocument) { + createSpecialWidget: function(aId, aDocument) { let nodeName = "toolbar" + aId.match(/spring|spacer|separator/)[0]; let node = aDocument.createElementNS(kNSXUL, nodeName); node.id = this.ensureSpecialWidgetId(aId); @@ -1260,7 +1260,7 @@ var CustomizableUIInternal = { /* Find a XUL-provided widget in a window. Don't try to use this * for an API-provided widget or a special widget. */ - findWidgetInWindow(aId, aWindow) { + findWidgetInWindow: function(aId, aWindow) { if (!gBuildWindows.has(aWindow)) { throw new Error("Build window not registered"); } @@ -1322,7 +1322,7 @@ var CustomizableUIInternal = { return null; }, - buildWidget(aDocument, aWidget) { + buildWidget: function(aDocument, aWidget) { if (aDocument.documentURI != kExpectedWindowURL) { throw new Error("buildWidget was called for a non-browser window!"); } @@ -1417,7 +1417,7 @@ var CustomizableUIInternal = { return node; }, - getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef) { + getLocalizedProperty: function(aWidget, aProp, aFormatArgs, aDef) { const kReqStringProps = ["label"]; if (typeof aWidget == "string") { @@ -1456,7 +1456,7 @@ var CustomizableUIInternal = { return def; }, - addShortcut(aShortcutNode, aTargetNode = aShortcutNode) { + addShortcut: function(aShortcutNode, aTargetNode = aShortcutNode) { // Detect if we've already been here before. if (aTargetNode.hasAttribute("shortcut")) return; @@ -1478,7 +1478,7 @@ var CustomizableUIInternal = { aTargetNode.setAttribute("shortcut", ShortcutUtils.prettifyShortcut(shortcut)); }, - handleWidgetCommand(aWidget, aNode, aEvent) { + handleWidgetCommand: function(aWidget, aNode, aEvent) { log.debug("handleWidgetCommand"); if (aWidget.type == "button") { @@ -1509,7 +1509,7 @@ var CustomizableUIInternal = { } }, - handleWidgetClick(aWidget, aNode, aEvent) { + handleWidgetClick: function(aWidget, aNode, aEvent) { log.debug("handleWidgetClick"); if (aWidget.onClick) { try { @@ -1523,7 +1523,7 @@ var CustomizableUIInternal = { } }, - _getPanelForNode(aNode) { + _getPanelForNode: function(aNode) { let panel = aNode; while (panel && panel.localName != "panel") panel = panel.parentNode; @@ -1536,7 +1536,7 @@ var CustomizableUIInternal = { * We also check for being outside of any toolbaritem/toolbarbutton, ie on a blank * part of the menu. */ - _isOnInteractiveElement(aEvent) { + _isOnInteractiveElement: function(aEvent) { function getMenuPopupForDescendant(aNode) { let lastPopup = null; while (aNode && aNode.parentNode && @@ -1652,14 +1652,14 @@ var CustomizableUIInternal = { return inInput || !inItem; }, - hidePanelForNode(aNode) { + hidePanelForNode: function(aNode) { let panel = this._getPanelForNode(aNode); if (panel) { panel.hidePopup(); } }, - maybeAutoHidePanel(aEvent) { + maybeAutoHidePanel: function(aEvent) { if (aEvent.type == "keypress") { if (aEvent.keyCode != aEvent.DOM_VK_RETURN) { return; @@ -1714,7 +1714,7 @@ var CustomizableUIInternal = { this.hidePanelForNode(aEvent.target); }, - getUnusedWidgets(aWindowPalette) { + getUnusedWidgets: function(aWindowPalette) { let window = aWindowPalette.ownerGlobal; let isWindowPrivate = PrivateBrowsingUtils.isWindowPrivate(window); // We use a Set because there can be overlap between the widgets in @@ -1745,7 +1745,7 @@ var CustomizableUIInternal = { return [...widgets]; }, - getPlacementOfWidget(aWidgetId, aOnlyRegistered, aDeadAreas) { + getPlacementOfWidget: function(aWidgetId, aOnlyRegistered, aDeadAreas) { if (aOnlyRegistered && !this.widgetExists(aWidgetId)) { return null; } @@ -1756,14 +1756,14 @@ var CustomizableUIInternal = { } let index = placements.indexOf(aWidgetId); if (index != -1) { - return { area, position: index }; + return { area: area, position: index }; } } return null; }, - widgetExists(aWidgetId) { + widgetExists: function(aWidgetId) { if (gPalette.has(aWidgetId) || this.isSpecialWidget(aWidgetId)) { return true; } @@ -1778,7 +1778,7 @@ var CustomizableUIInternal = { return true; }, - addWidgetToArea(aWidgetId, aArea, aPosition, aInitialAdd) { + addWidgetToArea: function(aWidgetId, aArea, aPosition, aInitialAdd) { if (!gAreas.has(aArea)) { throw new Error("Unknown customization area: " + aArea); } @@ -1852,7 +1852,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetAdded", aWidgetId, aArea, aPosition); }, - removeWidgetFromArea(aWidgetId) { + removeWidgetFromArea: function(aWidgetId) { let oldPlacement = this.getPlacementOfWidget(aWidgetId, false, true); if (!oldPlacement) { return; @@ -1881,7 +1881,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetRemoved", aWidgetId, oldPlacement.area); }, - moveWidgetWithinArea(aWidgetId, aPosition) { + moveWidgetWithinArea: function(aWidgetId, aPosition) { let oldPlacement = this.getPlacementOfWidget(aWidgetId); if (!oldPlacement) { return; @@ -1930,7 +1930,7 @@ var CustomizableUIInternal = { // built lazily - and therefore wouldn't otherwise result in restoring its // state immediately when a browser window opens, which is important for // other consumers of this API. - loadSavedState() { + loadSavedState: function() { let state = null; try { state = Services.prefs.getCharPref(kPrefCustomizationState); @@ -1967,7 +1967,7 @@ var CustomizableUIInternal = { gNewElementCount = gSavedState.newElementCount || 0; }, - restoreStateForArea(aArea, aLegacyState) { + restoreStateForArea: function(aArea, aLegacyState) { let placementsPreexisted = gPlacements.has(aArea); this.beginBatchUpdate(); @@ -2031,7 +2031,7 @@ var CustomizableUIInternal = { } }, - saveState() { + saveState: function() { if (gInBatchStack || !gDirty) { return; } @@ -2061,7 +2061,7 @@ var CustomizableUIInternal = { gDirty = false; }, - serializerHelper(aKey, aValue) { + serializerHelper: function(aKey, aValue) { if (typeof aValue == "object" && aValue.constructor.name == "Map") { let result = {}; for (let [mapKey, mapValue] of aValue) @@ -2076,11 +2076,11 @@ var CustomizableUIInternal = { return aValue; }, - beginBatchUpdate() { + beginBatchUpdate: function() { gInBatchStack++; }, - endBatchUpdate(aForceDirty) { + endBatchUpdate: function(aForceDirty) { gInBatchStack--; if (aForceDirty === true) { gDirty = true; @@ -2092,11 +2092,11 @@ var CustomizableUIInternal = { } }, - addListener(aListener) { + addListener: function(aListener) { gListeners.add(aListener); }, - removeListener(aListener) { + removeListener: function(aListener) { if (aListener == this) { return; } @@ -2104,7 +2104,7 @@ var CustomizableUIInternal = { gListeners.delete(aListener); }, - notifyListeners(aEvent, ...aArgs) { + notifyListeners: function(aEvent, ...aArgs) { if (gRestoring) { return; } @@ -2120,7 +2120,7 @@ var CustomizableUIInternal = { } }, - _dispatchToolboxEventToWindow(aEventType, aDetails, aWindow) { + _dispatchToolboxEventToWindow: function(aEventType, aDetails, aWindow) { let evt = new aWindow.CustomEvent(aEventType, { bubbles: true, cancelable: true, @@ -2129,7 +2129,7 @@ var CustomizableUIInternal = { aWindow.gNavToolbox.dispatchEvent(evt); }, - dispatchToolboxEvent(aEventType, aDetails = {}, aWindow = null) { + dispatchToolboxEvent: function(aEventType, aDetails = {}, aWindow = null) { if (aWindow) { this._dispatchToolboxEventToWindow(aEventType, aDetails, aWindow); return; @@ -2139,7 +2139,7 @@ var CustomizableUIInternal = { } }, - createWidget(aProperties) { + createWidget: function(aProperties) { let widget = this.normalizeWidget(aProperties, CustomizableUI.SOURCE_EXTERNAL); // XXXunf This should probably throw. if (!widget) { @@ -2256,7 +2256,7 @@ var CustomizableUIInternal = { return widget.id; }, - createBuiltinWidget(aData) { + createBuiltinWidget: function(aData) { // This should only ever be called on startup, before any windows are // opened - so we know there's no build areas to handle. Also, builtin // widgets are expected to be (mostly) static, so shouldn't affect the @@ -2291,7 +2291,7 @@ var CustomizableUIInternal = { }, // Returns true if the area will eventually lazily restore (but hasn't yet). - isAreaLazy(aArea) { + isAreaLazy: function(aArea) { if (gPlacements.has(aArea)) { return false; } @@ -2299,7 +2299,7 @@ var CustomizableUIInternal = { }, // XXXunf Log some warnings here, when the data provided isn't up to scratch. - normalizeWidget(aData, aSource) { + normalizeWidget: function(aData, aSource) { let widget = { implementation: aData, source: aSource || CustomizableUI.SOURCE_EXTERNAL, @@ -2400,7 +2400,7 @@ var CustomizableUIInternal = { return widget; }, - wrapWidgetEventHandler(aEventName, aWidget) { + wrapWidgetEventHandler: function(aEventName, aWidget) { if (typeof aWidget.implementation[aEventName] != "function") { aWidget[aEventName] = null; return; @@ -2422,7 +2422,7 @@ var CustomizableUIInternal = { }; }, - destroyWidget(aWidgetId) { + destroyWidget: function(aWidgetId) { let widget = gPalette.get(aWidgetId); if (!widget) { gGroupWrapperCache.delete(aWidgetId); @@ -2489,7 +2489,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetDestroyed", aWidgetId); }, - getCustomizeTargetForArea(aArea, aWindow) { + getCustomizeTargetForArea: function(aArea, aWindow) { let buildAreaNodes = gBuildAreas.get(aArea); if (!buildAreaNodes) { return null; @@ -2504,7 +2504,7 @@ var CustomizableUIInternal = { return null; }, - reset() { + reset: function() { gResetting = true; this._resetUIState(); @@ -2524,7 +2524,7 @@ var CustomizableUIInternal = { gResetting = false; }, - _resetUIState() { + _resetUIState: function() { try { gUIStateBeforeReset.drawInTitlebar = Services.prefs.getBoolPref(kPrefDrawInTitlebar); gUIStateBeforeReset.uiCustomizationState = Services.prefs.getCharPref(kPrefCustomizationState); @@ -2550,7 +2550,7 @@ var CustomizableUIInternal = { } }, - _resetExtraToolbars(aFilter = null) { + _resetExtraToolbars: function(aFilter = null) { let firstWindow = true; // Only need to unregister and persist once for (let [win, ] of gBuildWindows) { let toolbox = win.gNavToolbox; @@ -2572,7 +2572,7 @@ var CustomizableUIInternal = { } }, - _rebuildRegisteredAreas() { + _rebuildRegisteredAreas: function() { for (let [areaId, areaNodes] of gBuildAreas) { let placements = gPlacements.get(areaId); let isFirstChangedToolbar = true; @@ -2595,7 +2595,7 @@ var CustomizableUIInternal = { /** * Undoes a previous reset, restoring the state of the UI to the state prior to the reset. */ - undoReset() { + undoReset: function() { if (gUIStateBeforeReset.uiCustomizationState == null || gUIStateBeforeReset.drawInTitlebar == null) { return; @@ -2627,13 +2627,13 @@ var CustomizableUIInternal = { gUndoResetting = false; }, - _clearPreviousUIState() { + _clearPreviousUIState: function() { Object.getOwnPropertyNames(gUIStateBeforeReset).forEach((prop) => { gUIStateBeforeReset[prop] = null; }); }, - removeExtraToolbar(aToolbarId) { + removeExtraToolbar: function(aToolbarId) { this._resetExtraToolbars(aToolbarId); }, @@ -2641,7 +2641,7 @@ var CustomizableUIInternal = { * @param {String|Node} aWidget - widget ID or a widget node (preferred for performance). * @return {Boolean} whether the widget is removable */ - isWidgetRemovable(aWidget) { + isWidgetRemovable: function(aWidget) { let widgetId; let widgetNode; if (typeof aWidget == "string") { @@ -2684,7 +2684,7 @@ var CustomizableUIInternal = { return true; }, - canWidgetMoveToArea(aWidgetId, aArea) { + canWidgetMoveToArea: function(aWidgetId, aArea) { let placement = this.getPlacementOfWidget(aWidgetId); if (placement && placement.area != aArea) { // Special widgets can't move to the menu panel. @@ -2699,7 +2699,7 @@ var CustomizableUIInternal = { return true; }, - ensureWidgetPlacedInWindow(aWidgetId, aWindow) { + ensureWidgetPlacedInWindow: function(aWidgetId, aWindow) { let placement = this.getPlacementOfWidget(aWidgetId); if (!placement) { return false; @@ -2799,7 +2799,7 @@ var CustomizableUIInternal = { return true; }, - setToolbarVisibility(aToolbarId, aIsVisible) { + setToolbarVisibility: function(aToolbarId, aIsVisible) { // We only persist the attribute the first time. let isFirstChangedToolbar = true; for (let window of CustomizableUI.windows) { @@ -3003,14 +3003,14 @@ this.CustomizableUI = { * or by a window closing. The aReason parameter indicates which of * these is the case. */ - addListener(aListener) { + addListener: function(aListener) { CustomizableUIInternal.addListener(aListener); }, /** * Remove a listener added with addListener * @param aListener the listener object to remove */ - removeListener(aListener) { + removeListener: function(aListener) { CustomizableUIInternal.removeListener(aListener); }, @@ -3036,7 +3036,7 @@ this.CustomizableUI = { * Specify null to ensure that reset/inDefaultArea don't care * about a toolbar's collapsed state */ - registerArea(aName, aProperties) { + registerArea: function(aName, aProperties) { CustomizableUIInternal.registerArea(aName, aProperties); }, /** @@ -3055,7 +3055,7 @@ this.CustomizableUI = { * allow the user to customize it in customize mode, or otherwise deal * with it, until the area has been registered. */ - registerToolbarNode(aToolbar, aExistingChildren) { + registerToolbarNode: function(aToolbar, aExistingChildren) { CustomizableUIInternal.registerToolbarNode(aToolbar, aExistingChildren); }, /** @@ -3063,7 +3063,7 @@ this.CustomizableUI = { * apart from the built-in PanelUI. * @param aPanel the panel DOM node being registered. */ - registerMenuPanel(aPanel) { + registerMenuPanel: function(aPanel) { CustomizableUIInternal.registerMenuPanel(aPanel); }, /** @@ -3087,7 +3087,7 @@ this.CustomizableUI = { * @param aDestroyPlacements whether to destroy the placements information * for the area, too. */ - unregisterArea(aName, aDestroyPlacements) { + unregisterArea: function(aName, aDestroyPlacements) { CustomizableUIInternal.unregisterArea(aName, aDestroyPlacements); }, /** @@ -3112,7 +3112,7 @@ this.CustomizableUI = { * pass a position, the widget will be added to the end * of the area. */ - addWidgetToArea(aWidgetId, aArea, aPosition) { + addWidgetToArea: function(aWidgetId, aArea, aPosition) { CustomizableUIInternal.addWidgetToArea(aWidgetId, aArea, aPosition); }, /** @@ -3124,7 +3124,7 @@ this.CustomizableUI = { * * @param aWidgetId the ID of the widget to remove */ - removeWidgetFromArea(aWidgetId) { + removeWidgetFromArea: function(aWidgetId) { CustomizableUIInternal.removeWidgetFromArea(aWidgetId); }, /** @@ -3142,7 +3142,7 @@ this.CustomizableUI = { * widgets will be interpreted to mean moving the widget to * respectively the first or last position. */ - moveWidgetWithinArea(aWidgetId, aPosition) { + moveWidgetWithinArea: function(aWidgetId, aPosition) { CustomizableUIInternal.moveWidgetWithinArea(aWidgetId, aPosition); }, /** @@ -3161,7 +3161,7 @@ this.CustomizableUI = { * presumably you yourself need to create the widget in all the windows * and need to loop through them anyway. */ - ensureWidgetPlacedInWindow(aWidgetId, aWindow) { + ensureWidgetPlacedInWindow: function(aWidgetId, aWindow) { return CustomizableUIInternal.ensureWidgetPlacedInWindow(aWidgetId, aWindow); }, /** @@ -3176,7 +3176,7 @@ this.CustomizableUI = { * Firefox session, customization state is never saved. Typically, you * would do this using a try...finally block. */ - beginBatchUpdate() { + beginBatchUpdate: function() { CustomizableUIInternal.beginBatchUpdate(); }, /** @@ -3191,7 +3191,7 @@ this.CustomizableUI = { * @param aForceDirty force CustomizableUI to flush to the prefs file when * all batch updates have finished. */ - endBatchUpdate(aForceDirty) { + endBatchUpdate: function(aForceDirty) { CustomizableUIInternal.endBatchUpdate(aForceDirty); }, /** @@ -3267,7 +3267,7 @@ this.CustomizableUI = { * @param aProperties the specifications for the widget. * @return a wrapper around the created widget (see getWidget) */ - createWidget(aProperties) { + createWidget: function(aProperties) { return CustomizableUIInternal.wrapWidget( CustomizableUIInternal.createWidget(aProperties) ); @@ -3283,7 +3283,7 @@ this.CustomizableUI = { * * @param aWidgetId the ID of the widget to destroy */ - destroyWidget(aWidgetId) { + destroyWidget: function(aWidgetId) { CustomizableUIInternal.destroyWidget(aWidgetId); }, /** @@ -3346,7 +3346,7 @@ this.CustomizableUI = { * is no guarantee the widget exists because we cannot know in * advance if a XUL widget exists or not. */ - getWidget(aWidgetId) { + getWidget: function(aWidgetId) { return CustomizableUIInternal.wrapWidget(aWidgetId); }, /** @@ -3363,7 +3363,7 @@ this.CustomizableUI = { * * @return an array of widget wrappers (see getWidget) */ - getUnusedWidgets(aWindowPalette) { + getUnusedWidgets: function(aWindowPalette) { return CustomizableUIInternal.getUnusedWidgets(aWindowPalette).map( CustomizableUIInternal.wrapWidget, CustomizableUIInternal @@ -3380,7 +3380,7 @@ this.CustomizableUI = { * NB: will throw if called too early (before placements have been fetched) * or if the area is not currently known to CustomizableUI. */ - getWidgetIdsInArea(aArea) { + getWidgetIdsInArea: function(aArea) { if (!gAreas.has(aArea)) { throw new Error("Unknown customization area: " + aArea); } @@ -3406,7 +3406,7 @@ this.CustomizableUI = { * NB: will throw if called too early (before placements have been fetched) * or if the area is not currently known to CustomizableUI. */ - getWidgetsInArea(aArea) { + getWidgetsInArea: function(aArea) { return this.getWidgetIdsInArea(aArea).map( CustomizableUIInternal.wrapWidget, CustomizableUIInternal @@ -3430,7 +3430,7 @@ this.CustomizableUI = { * @return TYPE_TOOLBAR or TYPE_MENU_PANEL depending on the area, null if * the area is unknown. */ - getAreaType(aArea) { + getAreaType: function(aArea) { let area = gAreas.get(aArea); return area ? area.get("type") : null; }, @@ -3441,7 +3441,7 @@ this.CustomizableUI = { * @return `true` or `false` depending on the area, null if the area is unknown, * or its collapsed state cannot normally be controlled by the user */ - isToolbarDefaultCollapsed(aArea) { + isToolbarDefaultCollapsed: function(aArea) { let area = gAreas.get(aArea); return area ? area.get("defaultCollapsed") : null; }, @@ -3469,7 +3469,7 @@ this.CustomizableUI = { * @param aWindow the window where you want to fetch the DOM node. * @return the customize target DOM node for aArea in aWindow */ - getCustomizeTargetForArea(aArea, aWindow) { + getCustomizeTargetForArea: function(aArea, aWindow) { return CustomizableUIInternal.getCustomizeTargetForArea(aArea, aWindow); }, /** @@ -3479,7 +3479,7 @@ this.CustomizableUI = { * explicitly requests it. Firefox does this when the user clicks the * "Restore Defaults" button in customize mode. */ - reset() { + reset: function() { CustomizableUIInternal.reset(); }, @@ -3487,7 +3487,7 @@ this.CustomizableUI = { * Undo the previous reset, can only be called immediately after a reset. * @return a promise that will be resolved when the operation is complete. */ - undoReset() { + undoReset: function() { CustomizableUIInternal.undoReset(); }, @@ -3498,7 +3498,7 @@ this.CustomizableUI = { * other consumers. * @param aToolbarId the ID of the toolbar to remove */ - removeExtraToolbar(aToolbarId) { + removeExtraToolbar: function(aToolbarId) { CustomizableUIInternal.removeExtraToolbar(aToolbarId); }, @@ -3532,7 +3532,7 @@ this.CustomizableUI = { * * null // if the widget is not placed anywhere (ie in the palette) */ - getPlacementOfWidget(aWidgetId, aOnlyRegistered = true, aDeadAreas = false) { + getPlacementOfWidget: function(aWidgetId, aOnlyRegistered = true, aDeadAreas = false) { return CustomizableUIInternal.getPlacementOfWidget(aWidgetId, aOnlyRegistered, aDeadAreas); }, /** @@ -3553,7 +3553,7 @@ this.CustomizableUI = { * @return true if the widget can be removed from its area, * false otherwise. */ - isWidgetRemovable(aWidgetId) { + isWidgetRemovable: function(aWidgetId) { return CustomizableUIInternal.isWidgetRemovable(aWidgetId); }, /** @@ -3566,7 +3566,7 @@ this.CustomizableUI = { * @return true if this is possible, false if it is not. The same caveats as * for isWidgetRemovable apply, however, if no windows are open. */ - canWidgetMoveToArea(aWidgetId, aArea) { + canWidgetMoveToArea: function(aWidgetId, aArea) { return CustomizableUIInternal.canWidgetMoveToArea(aWidgetId, aArea); }, /** @@ -3587,7 +3587,7 @@ this.CustomizableUI = { * @param aToolbarId the toolbar whose visibility should be adjusted * @param aIsVisible whether the toolbar should be visible */ - setToolbarVisibility(aToolbarId, aIsVisible) { + setToolbarVisibility: function(aToolbarId, aIsVisible) { CustomizableUIInternal.setToolbarVisibility(aToolbarId, aIsVisible); }, @@ -3614,7 +3614,7 @@ this.CustomizableUI = { * otherwise we'll return the empty string * */ - getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef) { + getLocalizedProperty: function(aWidget, aProp, aFormatArgs, aDef) { return CustomizableUIInternal.getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef); }, @@ -3627,7 +3627,7 @@ this.CustomizableUI = { * attribute will be set. If NULL, the shortcut will be * set on aShortcutNode; */ - addShortcut(aShortcutNode, aTargetNode) { + addShortcut: function(aShortcutNode, aTargetNode) { return CustomizableUIInternal.addShortcut(aShortcutNode, aTargetNode); }, /** @@ -3636,7 +3636,7 @@ this.CustomizableUI = { * * @param aNode a node whose panel should be closed; */ - hidePanelForNode(aNode) { + hidePanelForNode: function(aNode) { CustomizableUIInternal.hidePanelForNode(aNode); }, /** @@ -3645,7 +3645,7 @@ this.CustomizableUI = { * @param aWidgetId the widget ID to check. * @return true if the widget is 'special', false otherwise. */ - isSpecialWidget(aWidgetId) { + isSpecialWidget: function(aWidgetId) { return CustomizableUIInternal.isSpecialWidget(aWidgetId); }, /** @@ -3655,7 +3655,7 @@ this.CustomizableUI = { * * @param aPanel the panel to which listeners should be attached. */ - addPanelCloseListeners(aPanel) { + addPanelCloseListeners: function(aPanel) { CustomizableUIInternal.addPanelCloseListeners(aPanel); }, /** @@ -3665,7 +3665,7 @@ this.CustomizableUI = { * * @param aPanel the panel from which listeners should be removed. */ - removePanelCloseListeners(aPanel) { + removePanelCloseListeners: function(aPanel) { CustomizableUIInternal.removePanelCloseListeners(aPanel); }, /** @@ -3675,7 +3675,7 @@ this.CustomizableUI = { * @param aWidgetId the ID of the widget that is being dragged to an area. * @param aArea the ID of the area to which the widget is being dragged. */ - onWidgetDrag(aWidgetId, aArea) { + onWidgetDrag: function(aWidgetId, aArea) { CustomizableUIInternal.notifyListeners("onWidgetDrag", aWidgetId, aArea); }, /** @@ -3683,7 +3683,7 @@ this.CustomizableUI = { * Customize Mode only, do not use otherwise. * @param aWindow the window entering customize mode */ - notifyStartCustomizing(aWindow) { + notifyStartCustomizing: function(aWindow) { CustomizableUIInternal.notifyListeners("onCustomizeStart", aWindow); }, /** @@ -3691,7 +3691,7 @@ this.CustomizableUI = { * Customize Mode only, do not use otherwise. * @param aWindow the window exiting customize mode */ - notifyEndCustomizing(aWindow) { + notifyEndCustomizing: function(aWindow) { CustomizableUIInternal.notifyListeners("onCustomizeEnd", aWindow); }, @@ -3703,7 +3703,7 @@ this.CustomizableUI = { * @param aDetails optional, the details of the event. * @param aWindow optional, the window in which to send the event. */ - dispatchToolboxEvent(aEvent, aDetails = {}, aWindow = null) { + dispatchToolboxEvent: function(aEvent, aDetails = {}, aWindow = null) { CustomizableUIInternal.dispatchToolboxEvent(aEvent, aDetails, aWindow); }, @@ -3713,7 +3713,7 @@ this.CustomizableUI = { * @param aAreaId the ID of an area to check for overflowable-ness * @return true if the area is overflowable, false otherwise. */ - isAreaOverflowable(aAreaId) { + isAreaOverflowable: function(aAreaId) { let area = gAreas.get(aAreaId); return area ? area.get("type") == this.TYPE_TOOLBAR && area.get("overflowable") : false; @@ -3728,7 +3728,7 @@ this.CustomizableUI = { * menu panel, "palette" if it is in the (visible!) customization * palette, undefined otherwise. */ - getPlaceForItem(aElement) { + getPlaceForItem: function(aElement) { let place; let node = aElement; while (node && !place) { @@ -3748,7 +3748,7 @@ this.CustomizableUI = { * Check if a toolbar is builtin or not. * @param aToolbarId the ID of the toolbar you want to check */ - isBuiltinToolbar(aToolbarId) { + isBuiltinToolbar: function(aToolbarId) { return CustomizableUIInternal._builtinToolbars.has(aToolbarId); }, }; @@ -4038,7 +4038,7 @@ OverflowableToolbar.prototype = { initialized: false, _forceOnOverflow: false, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic == "browser-delayed-startup-finished" && aSubject == this._toolbar.ownerGlobal) { Services.obs.removeObserver(this, "browser-delayed-startup-finished"); @@ -4046,7 +4046,7 @@ OverflowableToolbar.prototype = { } }, - init() { + init: function() { let doc = this._toolbar.ownerDocument; let window = doc.defaultView; window.addEventListener("resize", this); @@ -4075,7 +4075,7 @@ OverflowableToolbar.prototype = { this.initialized = true; }, - uninit() { + uninit: function() { this._toolbar.removeEventListener("overflow", this._toolbar); this._toolbar.removeEventListener("underflow", this._toolbar); this._toolbar.removeAttribute("overflowable"); @@ -4099,7 +4099,7 @@ OverflowableToolbar.prototype = { CustomizableUIInternal.removePanelCloseListeners(this._panel); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "aftercustomization": this._enable(); @@ -4128,7 +4128,7 @@ OverflowableToolbar.prototype = { } }, - show() { + show: function() { if (this._panel.state == "open") { return Promise.resolve(); } @@ -4151,7 +4151,7 @@ OverflowableToolbar.prototype = { }); }, - _onClickChevron(aEvent) { + _onClickChevron: function(aEvent) { if (this._chevron.open) { this._panel.hidePopup(); this._chevron.open = false; @@ -4160,7 +4160,7 @@ OverflowableToolbar.prototype = { } }, - _onPanelHiding(aEvent) { + _onPanelHiding: function(aEvent) { this._chevron.open = false; this._panel.removeEventListener("dragover", this); this._panel.removeEventListener("dragend", this); @@ -4169,7 +4169,7 @@ OverflowableToolbar.prototype = { gELS.removeSystemEventListener(contextMenu, 'command', this, true); }, - onOverflow(aEvent) { + onOverflow: function(aEvent) { // The rangeParent check is here because of bug 1111986 and ensuring that // overflow events from the bookmarks toolbar items or similar things that // manage their own overflow don't trigger an overflow on the entire toolbar @@ -4202,7 +4202,7 @@ OverflowableToolbar.prototype = { win.UpdateUrlbarSearchSplitterState(); }, - _onResize(aEvent) { + _onResize: function(aEvent) { if (!this._lazyResizeHandler) { this._lazyResizeHandler = new DeferredTask(this._onLazyResize.bind(this), LAZY_RESIZE_INTERVAL_MS); @@ -4210,7 +4210,7 @@ OverflowableToolbar.prototype = { this._lazyResizeHandler.arm(); }, - _moveItemsBackToTheirOrigin(shouldMoveAllItems) { + _moveItemsBackToTheirOrigin: function(shouldMoveAllItems) { let placements = gPlacements.get(this._toolbar.id); while (this._list.firstChild) { let child = this._list.firstChild; @@ -4256,7 +4256,7 @@ OverflowableToolbar.prototype = { } }, - _onLazyResize() { + _onLazyResize: function() { if (!this._enabled) return; @@ -4267,7 +4267,7 @@ OverflowableToolbar.prototype = { } }, - _disable() { + _disable: function() { this._enabled = false; this._moveItemsBackToTheirOrigin(true); if (this._lazyResizeHandler) { @@ -4275,12 +4275,12 @@ OverflowableToolbar.prototype = { } }, - _enable() { + _enable: function() { this._enabled = true; this.onOverflow(); }, - onWidgetBeforeDOMChange(aNode, aNextNode, aContainer) { + onWidgetBeforeDOMChange: function(aNode, aNextNode, aContainer) { if (aContainer != this._target && aContainer != this._list) { return; } @@ -4303,7 +4303,7 @@ OverflowableToolbar.prototype = { } }, - onWidgetAfterDOMChange(aNode, aNextNode, aContainer) { + onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer) { if (aContainer != this._target && aContainer != this._list) { return; } @@ -4358,7 +4358,7 @@ OverflowableToolbar.prototype = { } }, - findOverflowedInsertionPoints(aNode) { + findOverflowedInsertionPoints: function(aNode) { let newNodeCanOverflow = aNode.getAttribute("overflows") != "false"; let areaId = this._toolbar.id; let placements = gPlacements.get(areaId); @@ -4391,7 +4391,7 @@ OverflowableToolbar.prototype = { return [containerForAppending, null]; }, - getContainerFor(aNode) { + getContainerFor: function(aNode) { if (aNode.getAttribute("overflowedItem") == "true") { return this._list; } @@ -4399,7 +4399,7 @@ OverflowableToolbar.prototype = { }, _hideTimeoutId: null, - _showWithTimeout() { + _showWithTimeout: function() { this.show().then(function() { let window = this._toolbar.ownerGlobal; if (this._hideTimeoutId) { diff --git a/browser/components/customizableui/CustomizableWidgets.jsm b/browser/components/customizableui/CustomizableWidgets.jsm index 6f30303afb49..6b1dc8ea1af6 100644 --- a/browser/components/customizableui/CustomizableWidgets.jsm +++ b/browser/components/customizableui/CustomizableWidgets.jsm @@ -178,7 +178,7 @@ const CustomizableWidgets = [ shortcutId: "key_gotoHistory", tooltiptext: "history-panelmenu.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onViewShowing(aEvent) { + onViewShowing: function(aEvent) { // Populate our list of history const kMaxResults = 15; let doc = aEvent.target.ownerDocument; @@ -204,7 +204,7 @@ const CustomizableWidgets = [ PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase) .asyncExecuteLegacyQueries([query], 1, options, { - handleResult(aResultSet) { + handleResult: function(aResultSet) { let onItemCommand = function(aItemCommandEvent) { // Only handle the click event for middle clicks, we're using the command // event otherwise. @@ -237,10 +237,10 @@ const CustomizableWidgets = [ } items.appendChild(fragment); }, - handleError(aError) { + handleError: function(aError) { log.debug("History view tried to show but had an error: " + aError); }, - handleCompletion(aReason) { + handleCompletion: function(aReason) { log.debug("History view is being shown!"); }, }); @@ -280,7 +280,7 @@ const CustomizableWidgets = [ } recentlyClosedWindows.appendChild(windowsFragment); }, - onCreated(aNode) { + onCreated: function(aNode) { // Middle clicking recently closed items won't close the panel - cope: let onRecentlyClosedClick = function(aEvent) { if (aEvent.button == 1) { @@ -293,7 +293,7 @@ const CustomizableWidgets = [ recentlyClosedTabs.addEventListener("click", onRecentlyClosedClick); recentlyClosedWindows.addEventListener("click", onRecentlyClosedClick); }, - onViewHiding(aEvent) { + onViewHiding: function(aEvent) { log.debug("History view is being hidden!"); } }, { @@ -466,7 +466,7 @@ const CustomizableWidgets = [ appendTo.appendChild(messageLabel); return messageLabel; }, - _appendClient(client, attachFragment) { + _appendClient: function(client, attachFragment) { let doc = attachFragment.ownerDocument; // Create the element for the remote client. let clientItem = doc.createElementNS(kNSXUL, "label"); @@ -510,7 +510,7 @@ const CustomizableWidgets = [ id: "privatebrowsing-button", shortcutId: "key_privatebrowsing", defaultArea: CustomizableUI.AREA_PANEL, - onCommand(e) { + onCommand: function(e) { let win = e.target.ownerGlobal; win.OpenBrowserWindow({private: true}); } @@ -519,7 +519,7 @@ const CustomizableWidgets = [ shortcutId: "key_savePage", tooltiptext: "save-page-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand(aEvent) { + onCommand: function(aEvent) { let win = aEvent.target.ownerGlobal; win.saveBrowser(win.gBrowser.selectedBrowser); } @@ -528,7 +528,7 @@ const CustomizableWidgets = [ shortcutId: "key_find", tooltiptext: "find-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand(aEvent) { + onCommand: function(aEvent) { let win = aEvent.target.ownerGlobal; if (win.gFindBar) { win.gFindBar.onFindCommand(); @@ -539,7 +539,7 @@ const CustomizableWidgets = [ shortcutId: "openFileKb", tooltiptext: "open-file-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand(aEvent) { + onCommand: function(aEvent) { let win = aEvent.target.ownerGlobal; win.BrowserOpenFileWindow(); } @@ -548,7 +548,7 @@ const CustomizableWidgets = [ type: "view", viewId: "PanelUI-sidebar", tooltiptext: "sidebar-button.tooltiptext2", - onViewShowing(aEvent) { + onViewShowing: function(aEvent) { // Populate the subview with whatever menuitems are in the // sidebar menu. We skip menu elements, because the menu panel has no way // of dealing with those right now. @@ -565,7 +565,7 @@ const CustomizableWidgets = [ id: "social-share-button", // custom build our button so we can attach to the share command type: "custom", - onBuild(aDocument) { + onBuild: function(aDocument) { let node = aDocument.createElementNS(kNSXUL, "toolbarbutton"); node.setAttribute("id", this.id); node.classList.add("toolbarbutton-1"); @@ -607,7 +607,7 @@ const CustomizableWidgets = [ shortcutId: "key_openAddons", tooltiptext: "add-ons-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand(aEvent) { + onCommand: function(aEvent) { let win = aEvent.target.ownerGlobal; win.BrowserOpenAddonsMgr(); } @@ -616,7 +616,7 @@ const CustomizableWidgets = [ type: "custom", tooltiptext: "zoom-controls.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onBuild(aDocument) { + onBuild: function(aDocument) { const kPanelId = "PanelUI-popup"; let areaType = CustomizableUI.getAreaType(this.currentArea); let inPanel = areaType == CustomizableUI.TYPE_MENU_PANEL; @@ -768,13 +768,13 @@ const CustomizableWidgets = [ container.removeEventListener("TabSelect", updateZoomResetButton); }.bind(this), - onCustomizeStart(aWindow) { + onCustomizeStart: function(aWindow) { if (aWindow.document == aDocument) { updateZoomResetButton(); } }, - onCustomizeEnd(aWindow) { + onCustomizeEnd: function(aWindow) { if (aWindow.document == aDocument) { updateZoomResetButton(); } @@ -796,7 +796,7 @@ const CustomizableWidgets = [ type: "custom", tooltiptext: "edit-controls.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onBuild(aDocument) { + onBuild: function(aDocument) { let buttons = [{ id: "cut-button", command: "cmd_cut", @@ -894,7 +894,7 @@ const CustomizableWidgets = [ viewId: "PanelUI-feeds", tooltiptext: "feed-button.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onClick(aEvent) { + onClick: function(aEvent) { let win = aEvent.target.ownerGlobal; let feeds = win.gBrowser.selectedBrowser.feeds; @@ -908,7 +908,7 @@ const CustomizableWidgets = [ CustomizableUI.hidePanelForNode(aEvent.target); } }, - onViewShowing(aEvent) { + onViewShowing: function(aEvent) { let doc = aEvent.target.ownerDocument; let container = doc.getElementById("PanelUI-feeds"); let gotView = doc.defaultView.FeedHandler.buildFeedList(container, true); @@ -920,7 +920,7 @@ const CustomizableWidgets = [ return; } }, - onCreated(node) { + onCreated: function(node) { let win = node.ownerGlobal; let selectedBrowser = win.gBrowser.selectedBrowser; let feeds = selectedBrowser && selectedBrowser.feeds; @@ -935,12 +935,12 @@ const CustomizableWidgets = [ viewId: "PanelUI-characterEncodingView", tooltiptext: "characterencoding-button2.tooltiptext", defaultArea: CustomizableUI.AREA_PANEL, - maybeDisableMenu(aDocument) { + maybeDisableMenu: function(aDocument) { let window = aDocument.defaultView; return !(window.gBrowser && window.gBrowser.selectedBrowser.mayEnableCharacterEncodingMenu); }, - populateList(aDocument, aContainerId, aSection) { + populateList: function(aDocument, aContainerId, aSection) { let containerElem = aDocument.getElementById(aContainerId); containerElem.addEventListener("command", this.onCommand, false); @@ -957,7 +957,7 @@ const CustomizableWidgets = [ containerElem.appendChild(elem); } }, - updateCurrentCharset(aDocument) { + updateCurrentCharset: function(aDocument) { let currentCharset = aDocument.defaultView.gBrowser.selectedBrowser.characterSet; currentCharset = CharsetMenu.foldCharset(currentCharset); @@ -967,7 +967,7 @@ const CustomizableWidgets = [ this._updateElements(elements, currentCharset); }, - updateCurrentDetector(aDocument) { + updateCurrentDetector: function(aDocument) { let detectorContainer = aDocument.getElementById("PanelUI-characterEncodingView-autodetect"); let currentDetector; try { @@ -977,7 +977,7 @@ const CustomizableWidgets = [ this._updateElements(detectorContainer.childNodes, currentDetector); }, - _updateElements(aElements, aCurrentItem) { + _updateElements: function(aElements, aCurrentItem) { if (!aElements.length) { return; } @@ -995,7 +995,7 @@ const CustomizableWidgets = [ } } }, - onViewShowing(aEvent) { + onViewShowing: function(aEvent) { let document = aEvent.target.ownerDocument; let autoDetectLabelId = "PanelUI-characterEncodingView-autodetect-label"; @@ -1016,7 +1016,7 @@ const CustomizableWidgets = [ this.updateCurrentDetector(document); this.updateCurrentCharset(document); }, - onCommand(aEvent) { + onCommand: function(aEvent) { let node = aEvent.target; if (!node.hasAttribute || !node.section) { return; @@ -1044,7 +1044,7 @@ const CustomizableWidgets = [ window.BrowserCharsetReload(); } }, - onCreated(aNode) { + onCreated: function(aNode) { const kPanelId = "PanelUI-popup"; let document = aNode.ownerDocument; @@ -1095,7 +1095,7 @@ const CustomizableWidgets = [ }, { id: "email-link-button", tooltiptext: "email-link-button.tooltiptext3", - onCommand(aEvent) { + onCommand: function(aEvent) { let win = aEvent.view; win.MailIntegration.sendLinkForBrowser(win.gBrowser.selectedBrowser) } @@ -1104,7 +1104,7 @@ const CustomizableWidgets = [ type: "view", viewId: "PanelUI-containers", hasObserver: false, - onCreated(aNode) { + onCreated: function(aNode) { let doc = aNode.ownerDocument; let win = doc.defaultView; let items = doc.getElementById("PanelUI-containersItems"); @@ -1129,7 +1129,7 @@ const CustomizableWidgets = [ this.hasObserver = true; } }, - onViewShowing(aEvent) { + onViewShowing: function(aEvent) { let doc = aEvent.target.ownerDocument; let items = doc.getElementById("PanelUI-containersItems"); @@ -1187,7 +1187,7 @@ const CustomizableWidgets = [ let preferencesButton = { id: "preferences-button", defaultArea: CustomizableUI.AREA_PANEL, - onCommand(aEvent) { + onCommand: function(aEvent) { let win = aEvent.target.ownerGlobal; win.openPreferences(); } @@ -1209,7 +1209,7 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { type: "view", viewId: "PanelUI-panicView", _sanitizer: null, - _ensureSanitizer() { + _ensureSanitizer: function() { if (!this.sanitizer) { let scope = {}; Services.scriptloader.loadSubScript("chrome://browser/content/sanitize.js", @@ -1219,11 +1219,11 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { this._sanitizer.ignoreTimespan = false; } }, - _getSanitizeRange(aDocument) { + _getSanitizeRange: function(aDocument) { let group = aDocument.getElementById("PanelUI-panic-timeSpan"); return this._Sanitizer.getClearRange(+group.value); }, - forgetButtonCalled(aEvent) { + forgetButtonCalled: function(aEvent) { let doc = aEvent.target.ownerDocument; this._ensureSanitizer(); this._sanitizer.range = this._getSanitizeRange(doc); @@ -1249,18 +1249,18 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { } }); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "command": this.forgetButtonCalled(aEvent); break; } }, - onViewShowing(aEvent) { + onViewShowing: function(aEvent) { let forgetButton = aEvent.target.querySelector("#PanelUI-panic-view-button"); forgetButton.addEventListener("command", this); }, - onViewHiding(aEvent) { + onViewHiding: function(aEvent) { let forgetButton = aEvent.target.querySelector("#PanelUI-panic-view-button"); forgetButton.removeEventListener("command", this); }, @@ -1272,12 +1272,12 @@ if (AppConstants.E10S_TESTING_ONLY) { CustomizableWidgets.push({ id: "e10s-button", defaultArea: CustomizableUI.AREA_PANEL, - onBuild(aDocument) { + onBuild: function(aDocument) { let node = aDocument.createElementNS(kNSXUL, "toolbarbutton"); node.setAttribute("label", CustomizableUI.getLocalizedProperty(this, "label")); node.setAttribute("tooltiptext", CustomizableUI.getLocalizedProperty(this, "tooltiptext")); }, - onCommand(aEvent) { + onCommand: function(aEvent) { let win = aEvent.view; win.OpenBrowserWindow({remote: false}); }, diff --git a/browser/components/customizableui/CustomizeMode.jsm b/browser/components/customizableui/CustomizeMode.jsm index 888708ac65ff..655756cfb2f5 100644 --- a/browser/components/customizableui/CustomizeMode.jsm +++ b/browser/components/customizableui/CustomizeMode.jsm @@ -130,13 +130,13 @@ CustomizeMode.prototype = { return this.window.CustomizationHandler; }, - uninit() { + uninit: function() { if (AppConstants.CAN_DRAW_IN_TITLEBAR) { Services.prefs.removeObserver(kDrawInTitlebarPref, this); } }, - toggle() { + toggle: function() { if (this._handler.isEnteringCustomizeMode || this._handler.isExitingCustomizeMode) { this._wantToBeInCustomizeMode = !this._wantToBeInCustomizeMode; return; @@ -148,7 +148,7 @@ CustomizeMode.prototype = { } }, - _updateLWThemeButtonIcon() { + _updateLWThemeButtonIcon: function() { let lwthemeButton = this.document.getElementById("customization-lwtheme-button"); let lwthemeIcon = this.document.getAnonymousElementByAttribute(lwthemeButton, "class", "button-icon"); @@ -156,7 +156,7 @@ CustomizeMode.prototype = { "url(" + LightweightThemeManager.currentTheme.iconURL + ")" : ""; }, - setTab(aTab) { + setTab: function(aTab) { if (gTab == aTab) { return; } @@ -186,7 +186,7 @@ CustomizeMode.prototype = { } }, - enter() { + enter: function() { this._wantToBeInCustomizeMode = true; if (this._customizing || this._handler.isEnteringCustomizeMode) { @@ -380,7 +380,7 @@ CustomizeMode.prototype = { }.bind(this)); }, - exit() { + exit: function() { this._wantToBeInCustomizeMode = false; if (!this._customizing || this._handler.isExitingCustomizeMode) { @@ -557,7 +557,7 @@ CustomizeMode.prototype = { * phases, there is a "customizing" attribute set on the main-window to simplify * excluding certain styles while in any phase of customize mode. */ - _doTransition(aEntering) { + _doTransition: function(aEntering) { let deck = this.document.getElementById("content-deck"); let customizeTransitionEndPromise = new Promise(resolve => { let customizeTransitionEnd = (aEvent) => { @@ -603,7 +603,7 @@ CustomizeMode.prototype = { return customizeTransitionEndPromise; }, - updateLWTStyling(aData) { + updateLWTStyling: function(aData) { let docElement = this.document.documentElement; if (!aData) { let lwt = docElement._lightweightTheme; @@ -654,7 +654,7 @@ CustomizeMode.prototype = { docElement.style.removeProperty("background-color"); }, - removeLWTStyling() { + removeLWTStyling: function() { let affectedNodes = AppConstants.platform == "macosx" ? ["tab-view-deck", "titlebar"] : ["tab-view-deck"]; @@ -671,11 +671,11 @@ CustomizeMode.prototype = { } }, - _getHeaderImageRef(aData) { + _getHeaderImageRef: function(aData) { return "url(\"" + aData.headerURL.replace(/"/g, '\\"') + "\")"; }, - maybeShowTip(aAnchor) { + maybeShowTip: function(aAnchor) { let shown = false; const kShownPref = "browser.customizemode.tip0.shown"; try { @@ -711,11 +711,11 @@ CustomizeMode.prototype = { Services.prefs.setBoolPref(kShownPref, true); }, - hideTip() { + hideTip: function() { this.tipPanel.hidePopup(); }, - _getCustomizableChildForNode(aNode) { + _getCustomizableChildForNode: function(aNode) { // NB: adjusted from _getCustomizableParent to keep that method fast // (it's used during drags), and avoid multiple DOM loops let areas = CustomizableUI.areas; @@ -746,7 +746,7 @@ CustomizeMode.prototype = { return null; }, - addToToolbar(aNode) { + addToToolbar: function(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -757,7 +757,7 @@ CustomizeMode.prototype = { } }, - addToPanel(aNode) { + addToPanel: function(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -768,7 +768,7 @@ CustomizeMode.prototype = { } }, - removeFromArea(aNode) { + removeFromArea: function(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -779,7 +779,7 @@ CustomizeMode.prototype = { } }, - populatePalette() { + populatePalette: function() { let fragment = this.document.createDocumentFragment(); let toolboxPalette = this.window.gNavToolbox.palette; @@ -805,7 +805,7 @@ CustomizeMode.prototype = { // Would ensure no weird interactions/event handling from original node, // and makes it possible to put this in a lazy-loaded iframe/real tab // while still getting rid of the need for overlays. - makePaletteItem(aWidget, aPlace) { + makePaletteItem: function(aWidget, aPlace) { let widgetNode = aWidget.forWindow(this.window).node; if (!widgetNode) { log.error("Widget with id " + aWidget.id + " does not return a valid node"); @@ -821,7 +821,7 @@ CustomizeMode.prototype = { return wrapper; }, - depopulatePalette() { + depopulatePalette: function() { return Task.spawn(function*() { this.visiblePalette.hidden = true; let paletteChild = this.visiblePalette.firstChild; @@ -851,7 +851,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - isCustomizableItem(aNode) { + isCustomizableItem: function(aNode) { return aNode.localName == "toolbarbutton" || aNode.localName == "toolbaritem" || aNode.localName == "toolbarseparator" || @@ -859,11 +859,11 @@ CustomizeMode.prototype = { aNode.localName == "toolbarspacer"; }, - isWrappedToolbarItem(aNode) { + isWrappedToolbarItem: function(aNode) { return aNode.localName == "toolbarpaletteitem"; }, - deferredWrapToolbarItem(aNode, aPlace) { + deferredWrapToolbarItem: function(aNode, aPlace) { return new Promise(resolve => { dispatchFunction(() => { let wrapper = this.wrapToolbarItem(aNode, aPlace); @@ -872,7 +872,7 @@ CustomizeMode.prototype = { }); }, - wrapToolbarItem(aNode, aPlace) { + wrapToolbarItem: function(aNode, aPlace) { if (!this.isCustomizableItem(aNode)) { return aNode; } @@ -890,7 +890,7 @@ CustomizeMode.prototype = { return wrapper; }, - createOrUpdateWrapper(aNode, aPlace, aIsUpdate) { + createOrUpdateWrapper: function(aNode, aPlace, aIsUpdate) { let wrapper; if (aIsUpdate && aNode.parentNode && aNode.parentNode.localName == "toolbarpaletteitem") { wrapper = aNode.parentNode; @@ -980,7 +980,7 @@ CustomizeMode.prototype = { return wrapper; }, - deferredUnwrapToolbarItem(aWrapper) { + deferredUnwrapToolbarItem: function(aWrapper) { return new Promise(resolve => { dispatchFunction(() => { let item = null; @@ -994,7 +994,7 @@ CustomizeMode.prototype = { }); }, - unwrapToolbarItem(aWrapper) { + unwrapToolbarItem: function(aWrapper) { if (aWrapper.nodeName != "toolbarpaletteitem") { return aWrapper; } @@ -1045,7 +1045,7 @@ CustomizeMode.prototype = { return toolbarItem; }, - *_wrapToolbarItem(aArea) { + _wrapToolbarItem: function*(aArea) { let target = CustomizableUI.getCustomizeTargetForArea(aArea, this.window); if (!target || this.areas.has(target)) { return null; @@ -1061,7 +1061,7 @@ CustomizeMode.prototype = { return target; }, - _wrapToolbarItemSync(aArea) { + _wrapToolbarItemSync: function(aArea) { let target = CustomizableUI.getCustomizeTargetForArea(aArea, this.window); if (!target || this.areas.has(target)) { return null; @@ -1082,13 +1082,13 @@ CustomizeMode.prototype = { return target; }, - *_wrapToolbarItems() { + _wrapToolbarItems: function*() { for (let area of CustomizableUI.areas) { yield this._wrapToolbarItem(area); } }, - _addDragHandlers(aTarget) { + _addDragHandlers: function(aTarget) { aTarget.addEventListener("dragstart", this, true); aTarget.addEventListener("dragover", this, true); aTarget.addEventListener("dragexit", this, true); @@ -1096,7 +1096,7 @@ CustomizeMode.prototype = { aTarget.addEventListener("dragend", this, true); }, - _wrapItemsInArea(target) { + _wrapItemsInArea: function(target) { for (let child of target.children) { if (this.isCustomizableItem(child)) { this.wrapToolbarItem(child, CustomizableUI.getPlaceForItem(child)); @@ -1104,7 +1104,7 @@ CustomizeMode.prototype = { } }, - _removeDragHandlers(aTarget) { + _removeDragHandlers: function(aTarget) { aTarget.removeEventListener("dragstart", this, true); aTarget.removeEventListener("dragover", this, true); aTarget.removeEventListener("dragexit", this, true); @@ -1112,7 +1112,7 @@ CustomizeMode.prototype = { aTarget.removeEventListener("dragend", this, true); }, - _unwrapItemsInArea(target) { + _unwrapItemsInArea: function(target) { for (let toolbarItem of target.children) { if (this.isWrappedToolbarItem(toolbarItem)) { this.unwrapToolbarItem(toolbarItem); @@ -1120,7 +1120,7 @@ CustomizeMode.prototype = { } }, - _unwrapToolbarItems() { + _unwrapToolbarItems: function() { return Task.spawn(function*() { for (let target of this.areas) { for (let toolbarItem of target.children) { @@ -1134,7 +1134,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - _removeExtraToolbarsIfEmpty() { + _removeExtraToolbarsIfEmpty: function() { let toolbox = this.window.gNavToolbox; for (let child of toolbox.children) { if (child.hasAttribute("customindex")) { @@ -1146,7 +1146,7 @@ CustomizeMode.prototype = { } }, - persistCurrentSets(aSetBeforePersisting) { + persistCurrentSets: function(aSetBeforePersisting) { let document = this.document; let toolbars = document.querySelectorAll("toolbar[customizable='true'][currentset]"); for (let toolbar of toolbars) { @@ -1159,7 +1159,7 @@ CustomizeMode.prototype = { } }, - reset() { + reset: function() { this.resetting = true; // Disable the reset button temporarily while resetting: let btn = this.document.getElementById("customization-reset-button"); @@ -1190,7 +1190,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - undoReset() { + undoReset: function() { this.resetting = true; return Task.spawn(function*() { @@ -1214,7 +1214,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - _onToolbarVisibilityChange(aEvent) { + _onToolbarVisibilityChange: function(aEvent) { let toolbar = aEvent.target; if (aEvent.detail.visible && toolbar.getAttribute("customizable") == "true") { toolbar.setAttribute("customizing", "true"); @@ -1225,19 +1225,19 @@ CustomizeMode.prototype = { this.updateLWTStyling(); }, - onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { this._onUIChange(); }, - onWidgetAdded(aWidgetId, aArea, aPosition) { + onWidgetAdded: function(aWidgetId, aArea, aPosition) { this._onUIChange(); }, - onWidgetRemoved(aWidgetId, aArea) { + onWidgetRemoved: function(aWidgetId, aArea) { this._onUIChange(); }, - onWidgetBeforeDOMChange(aNodeToChange, aSecondaryNode, aContainer) { + onWidgetBeforeDOMChange: function(aNodeToChange, aSecondaryNode, aContainer) { if (aContainer.ownerGlobal != this.window || this.resetting) { return; } @@ -1254,7 +1254,7 @@ CustomizeMode.prototype = { } }, - onWidgetAfterDOMChange(aNodeToChange, aSecondaryNode, aContainer) { + onWidgetAfterDOMChange: function(aNodeToChange, aSecondaryNode, aContainer) { if (aContainer.ownerGlobal != this.window || this.resetting) { return; } @@ -1284,7 +1284,7 @@ CustomizeMode.prototype = { } }, - onWidgetDestroyed(aWidgetId) { + onWidgetDestroyed: function(aWidgetId) { let wrapper = this.document.getElementById("wrapper-" + aWidgetId); if (wrapper) { let wasInPanel = wrapper.parentNode == this.panelUIContents; @@ -1295,7 +1295,7 @@ CustomizeMode.prototype = { } }, - onWidgetAfterCreation(aWidgetId, aArea) { + onWidgetAfterCreation: function(aWidgetId, aArea) { // If the node was added to an area, we would have gotten an onWidgetAdded notification, // plus associated DOM change notifications, so only do stuff for the palette: if (!aArea) { @@ -1309,7 +1309,7 @@ CustomizeMode.prototype = { } }, - onAreaNodeRegistered(aArea, aContainer) { + onAreaNodeRegistered: function(aArea, aContainer) { if (aContainer.ownerDocument == this.document) { this._wrapItemsInArea(aContainer); this._addDragHandlers(aContainer); @@ -1318,7 +1318,7 @@ CustomizeMode.prototype = { } }, - onAreaNodeUnregistered(aArea, aContainer, aReason) { + onAreaNodeUnregistered: function(aArea, aContainer, aReason) { if (aContainer.ownerDocument == this.document && aReason == CustomizableUI.REASON_AREA_UNREGISTERED) { this._unwrapItemsInArea(aContainer); this._removeDragHandlers(aContainer); @@ -1327,18 +1327,18 @@ CustomizeMode.prototype = { } }, - openAddonsManagerThemes(aEvent) { + openAddonsManagerThemes: function(aEvent) { aEvent.target.parentNode.parentNode.hidePopup(); this.window.BrowserOpenAddonsMgr('addons://list/theme'); }, - getMoreThemes(aEvent) { + getMoreThemes: function(aEvent) { aEvent.target.parentNode.parentNode.hidePopup(); let getMoreURL = Services.urlFormatter.formatURLPref("lightweightThemes.getMoreURL"); this.window.openUILinkIn(getMoreURL, "tab"); }, - onLWThemesMenuShowing(aEvent) { + onLWThemesMenuShowing: function(aEvent) { const DEFAULT_THEME_ID = "{972ce4c6-7e08-4474-a285-3208198ce6fd}"; const RECENT_LWT_COUNT = 5; @@ -1443,7 +1443,7 @@ CustomizeMode.prototype = { }.bind(this)); }, - _clearLWThemesMenu(panel) { + _clearLWThemesMenu: function(panel) { let footer = this.document.getElementById("customization-lwtheme-menu-footer"); let recommendedLabel = this.document.getElementById("customization-lwtheme-menu-recommended"); for (let element of [footer, recommendedLabel]) { @@ -1457,7 +1457,7 @@ CustomizeMode.prototype = { panel.removeAttribute("height"); }, - _onUIChange() { + _onUIChange: function() { this._changed = true; if (!this.resetting) { this._updateResetButton(); @@ -1467,22 +1467,22 @@ CustomizeMode.prototype = { CustomizableUI.dispatchToolboxEvent("customizationchange"); }, - _updateEmptyPaletteNotice() { + _updateEmptyPaletteNotice: function() { let paletteItems = this.visiblePalette.getElementsByTagName("toolbarpaletteitem"); this.paletteEmptyNotice.hidden = !!paletteItems.length; }, - _updateResetButton() { + _updateResetButton: function() { let btn = this.document.getElementById("customization-reset-button"); btn.disabled = CustomizableUI.inDefaultState; }, - _updateUndoResetButton() { + _updateUndoResetButton: function() { let undoResetButton = this.document.getElementById("customization-undo-reset-button"); undoResetButton.hidden = !CustomizableUI.canUndoReset; }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "toolbarvisibilitychange": this._onToolbarVisibilityChange(aEvent); @@ -1525,7 +1525,7 @@ CustomizeMode.prototype = { } }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { switch (aTopic) { case "nsPref:changed": this._updateResetButton(); @@ -1547,7 +1547,7 @@ CustomizeMode.prototype = { } }, - _updateTitlebarButton() { + _updateTitlebarButton: function() { if (!AppConstants.CAN_DRAW_IN_TITLEBAR) { return; } @@ -1564,7 +1564,7 @@ CustomizeMode.prototype = { } }, - toggleTitlebar(aShouldShowTitlebar) { + toggleTitlebar: function(aShouldShowTitlebar) { if (!AppConstants.CAN_DRAW_IN_TITLEBAR) { return; } @@ -1572,7 +1572,7 @@ CustomizeMode.prototype = { Services.prefs.setBoolPref(kDrawInTitlebarPref, !aShouldShowTitlebar); }, - _onDragStart(aEvent) { + _onDragStart: function(aEvent) { __dumpDragData(aEvent); let item = aEvent.target; while (item && item.localName != "toolbarpaletteitem") { @@ -1629,7 +1629,7 @@ CustomizeMode.prototype = { this._dragInitializeTimeout = this.window.setTimeout(this._initializeDragAfterMove, 0); }, - _onDragOver(aEvent) { + _onDragOver: function(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1726,7 +1726,7 @@ CustomizeMode.prototype = { aEvent.stopPropagation(); }, - _onDragDrop(aEvent) { + _onDragDrop: function(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1779,7 +1779,7 @@ CustomizeMode.prototype = { this._showPanelCustomizationPlaceholders(); }, - _applyDrop(aEvent, aTargetArea, aOriginArea, aDraggedItemId, aTargetNode) { + _applyDrop: function(aEvent, aTargetArea, aOriginArea, aDraggedItemId, aTargetNode) { let document = aEvent.target.ownerDocument; let draggedItem = document.getElementById(aDraggedItemId); draggedItem.hidden = false; @@ -1908,7 +1908,7 @@ CustomizeMode.prototype = { } }, - _onDragExit(aEvent) { + _onDragExit: function(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1929,7 +1929,7 @@ CustomizeMode.prototype = { /** * To workaround bug 460801 we manually forward the drop event here when dragend wouldn't be fired. */ - _onDragEnd(aEvent) { + _onDragEnd: function(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1966,7 +1966,7 @@ CustomizeMode.prototype = { DragPositionManager.stop(); }, - _isUnwantedDragDrop(aEvent) { + _isUnwantedDragDrop: function(aEvent) { // The simulated events generated by synthesizeDragStart/synthesizeDrop in // mochitests are used only for testing whether the right data is being put // into the dataTransfer. Neither cause a real drop to occur, so they don't @@ -1985,7 +1985,7 @@ CustomizeMode.prototype = { mozSourceNode.ownerGlobal != this.window; }, - _setDragActive(aItem, aValue, aDraggedItemId, aInToolbar) { + _setDragActive: function(aItem, aValue, aDraggedItemId, aInToolbar) { if (!aItem) { return; } @@ -2033,7 +2033,7 @@ CustomizeMode.prototype = { } } }, - _cancelDragActive(aItem, aNextItem, aNoTransition) { + _cancelDragActive: function(aItem, aNextItem, aNoTransition) { this._updateToolbarCustomizationOutline(aItem.ownerGlobal); let currentArea = this._getCustomizableParent(aItem); if (!currentArea) { @@ -2069,7 +2069,7 @@ CustomizeMode.prototype = { } }, - _setGridDragActive(aDragOverNode, aDraggedItem, aValue) { + _setGridDragActive: function(aDragOverNode, aDraggedItem, aValue) { let targetArea = this._getCustomizableParent(aDragOverNode); let draggedWrapper = this.document.getElementById("wrapper-" + aDraggedItem.id); let originArea = this._getCustomizableParent(draggedWrapper); @@ -2080,7 +2080,7 @@ CustomizeMode.prototype = { originArea == targetArea); }, - _getDragItemSize(aDragOverNode, aDraggedItem) { + _getDragItemSize: function(aDragOverNode, aDraggedItem) { // Cache it good, cache it real good. if (!this._dragSizeMap) this._dragSizeMap = new WeakMap(); @@ -2140,7 +2140,7 @@ CustomizeMode.prototype = { return size; }, - _getCustomizableParent(aElement) { + _getCustomizableParent: function(aElement) { let areas = CustomizableUI.areas; areas.push(kPaletteId); while (aElement) { @@ -2152,7 +2152,7 @@ CustomizeMode.prototype = { return null; }, - _getDragOverNode(aEvent, aAreaElement, aInToolbar, aDraggedItemId) { + _getDragOverNode: function(aEvent, aAreaElement, aInToolbar, aDraggedItemId) { let expectedParent = aAreaElement.customizationTarget || aAreaElement; // Our tests are stupid. Cope: if (!aEvent.clientX && !aEvent.clientY) { @@ -2200,7 +2200,7 @@ CustomizeMode.prototype = { return targetNode || aEvent.target; }, - _onMouseDown(aEvent) { + _onMouseDown: function(aEvent) { log.debug("_onMouseDown"); if (aEvent.button != 0) { return; @@ -2214,7 +2214,7 @@ CustomizeMode.prototype = { } }, - _onMouseUp(aEvent) { + _onMouseUp: function(aEvent) { log.debug("_onMouseUp"); if (aEvent.button != 0) { return; @@ -2227,7 +2227,7 @@ CustomizeMode.prototype = { } }, - _getWrapper(aElement) { + _getWrapper: function(aElement) { while (aElement && aElement.localName != "toolbarpaletteitem") { if (aElement.localName == "toolbar") return null; @@ -2236,7 +2236,7 @@ CustomizeMode.prototype = { return aElement; }, - _showPanelCustomizationPlaceholders() { + _showPanelCustomizationPlaceholders: function() { let doc = this.document; let contents = this.panelUIContents; let narrowItemsAfterWideItem = 0; @@ -2271,7 +2271,7 @@ CustomizeMode.prototype = { } }, - _removePanelCustomizationPlaceholders() { + _removePanelCustomizationPlaceholders: function() { let contents = this.panelUIContents; let oldPlaceholders = contents.getElementsByClassName(kPlaceholderClass); while (oldPlaceholders.length) { @@ -2288,7 +2288,7 @@ CustomizeMode.prototype = { * outline to. If aToolbarArea is falsy, the outline will be * removed from all toolbar areas. */ - _updateToolbarCustomizationOutline(aWindow, aToolbarArea = null) { + _updateToolbarCustomizationOutline: function(aWindow, aToolbarArea = null) { // Remove the attribute from existing customization targets for (let area of CustomizableUI.areas) { if (CustomizableUI.getAreaType(area) != CustomizableUI.TYPE_TOOLBAR) { @@ -2307,7 +2307,7 @@ CustomizeMode.prototype = { } }, - _findVisiblePreviousSiblingNode(aReferenceNode) { + _findVisiblePreviousSiblingNode: function(aReferenceNode) { while (aReferenceNode && aReferenceNode.localName == "toolbarpaletteitem" && aReferenceNode.firstChild.hidden) { diff --git a/browser/components/customizableui/DragPositionManager.jsm b/browser/components/customizableui/DragPositionManager.jsm index 65e2585a5a81..1b4eb59dc15f 100644 --- a/browser/components/customizableui/DragPositionManager.jsm +++ b/browser/components/customizableui/DragPositionManager.jsm @@ -33,7 +33,7 @@ AreaPositionManager.prototype = { _nodePositionStore: null, _wideCache: null, - update(aContainer) { + update: function(aContainer) { this._nodePositionStore = new WeakMap(); this._wideCache = new Set(); let last = null; @@ -73,7 +73,7 @@ AreaPositionManager.prototype = { * where dy is more heavily weighted by a factor corresponding to the * ratio between the container's width and the height of its elements. */ - find(aContainer, aX, aY, aDraggedItemId) { + find: function(aContainer, aX, aY, aDraggedItemId) { let closest = null; let minCartesian = Number.MAX_VALUE; let containerX = this._containerInfo.left; @@ -130,7 +130,7 @@ AreaPositionManager.prototype = { * they would have if we had inserted something before aBefore. We use CSS * transforms for this, which are CSS transitioned. */ - insertPlaceholder(aContainer, aBefore, aWide, aSize, aIsFromThisArea) { + insertPlaceholder: function(aContainer, aBefore, aWide, aSize, aIsFromThisArea) { let isShifted = false; let shiftDown = aWide; for (let child of aContainer.children) { @@ -185,11 +185,11 @@ AreaPositionManager.prototype = { this._lastPlaceholderInsertion = aBefore; }, - isWide(aNode) { + isWide: function(aNode) { return this._wideCache.has(aNode.id); }, - _checkIfWide(aNode) { + _checkIfWide: function(aNode) { return this._inPanel && aNode && aNode.firstChild && aNode.firstChild.classList.contains(CustomizableUI.WIDE_PANEL_CLASS); }, @@ -201,7 +201,7 @@ AreaPositionManager.prototype = { * @param aNoTransition if truthy, adds a notransition attribute to the node * while resetting the transform. */ - clearPlaceholders(aContainer, aNoTransition) { + clearPlaceholders: function(aContainer, aNoTransition) { for (let child of aContainer.children) { if (aNoTransition) { child.setAttribute("notransition", true); @@ -220,7 +220,7 @@ AreaPositionManager.prototype = { } }, - _getNextPos(aNode, aShiftDown, aSize) { + _getNextPos: function(aNode, aShiftDown, aSize) { // Shifting down is easy: if (this._inPanel && aShiftDown) { return "translate(0, " + aSize.height + "px)"; @@ -228,7 +228,7 @@ AreaPositionManager.prototype = { return this._diffWithNext(aNode, aSize); }, - _diffWithNext(aNode, aSize) { + _diffWithNext: function(aNode, aSize) { let xDiff; let yDiff = null; let nodeBounds = this._lazyStoreGet(aNode); @@ -306,7 +306,7 @@ AreaPositionManager.prototype = { * @param aNodeBounds the bounding rect info of this node * @param aFirstNodeInRow the first node in aNode's row */ - _moveNextBasedOnPrevious(aNode, aNodeBounds, aFirstNodeInRow) { + _moveNextBasedOnPrevious: function(aNode, aNodeBounds, aFirstNodeInRow) { let next = this._getVisibleSiblingForDirection(aNode, "previous"); let otherBounds = this._lazyStoreGet(next); let side = this._dir == "ltr" ? "left" : "right"; @@ -328,7 +328,7 @@ AreaPositionManager.prototype = { * @param aNode the node whose position info we want * @return the position info */ - _lazyStoreGet(aNode) { + _lazyStoreGet: function(aNode) { let rect = this._nodePositionStore.get(aNode); if (!rect) { // getBoundingClientRect() returns a DOMRect that is live, meaning that @@ -352,7 +352,7 @@ AreaPositionManager.prototype = { return rect; }, - _firstInRow(aNode) { + _firstInRow: function(aNode) { // XXXmconley: I'm not entirely sure why we need to take the floor of these // values - it looks like, periodically, we're getting fractional pixels back // from lazyStoreGet. I've filed bug 994247 to investigate. @@ -368,7 +368,7 @@ AreaPositionManager.prototype = { return rv; }, - _getVisibleSiblingForDirection(aNode, aDirection) { + _getVisibleSiblingForDirection: function(aNode, aDirection) { let rv = aNode; do { rv = rv[aDirection + "Sibling"]; @@ -378,7 +378,7 @@ AreaPositionManager.prototype = { } var DragPositionManager = { - start(aWindow) { + start: function(aWindow) { let areas = CustomizableUI.areas.filter((area) => CustomizableUI.getAreaType(area) != "toolbar"); areas = areas.map((area) => CustomizableUI.getCustomizeTargetForArea(area, aWindow)); areas.push(aWindow.document.getElementById(kPaletteId)); @@ -392,7 +392,7 @@ var DragPositionManager = { } }, - add(aWindow, aArea, aContainer) { + add: function(aWindow, aArea, aContainer) { if (CustomizableUI.getAreaType(aArea) != "toolbar") { return; } @@ -400,7 +400,7 @@ var DragPositionManager = { gManagers.set(aContainer, new AreaPositionManager(aContainer)); }, - remove(aWindow, aArea, aContainer) { + remove: function(aWindow, aArea, aContainer) { if (CustomizableUI.getAreaType(aArea) != "toolbar") { return; } @@ -408,11 +408,11 @@ var DragPositionManager = { gManagers.delete(aContainer); }, - stop() { + stop: function() { gManagers = new WeakMap(); }, - getManagerForArea(aArea) { + getManagerForArea: function(aArea) { return gManagers.get(aArea); } }; diff --git a/browser/components/customizableui/PanelWideWidgetTracker.jsm b/browser/components/customizableui/PanelWideWidgetTracker.jsm index a9b38c23eb26..768cebbca73e 100644 --- a/browser/components/customizableui/PanelWideWidgetTracker.jsm +++ b/browser/components/customizableui/PanelWideWidgetTracker.jsm @@ -22,33 +22,33 @@ var gSeenWidgets = new Set(); var PanelWideWidgetTracker = { // Listeners used to validate panel contents whenever they change: - onWidgetAdded(aWidgetId, aArea, aPosition) { + onWidgetAdded: function(aWidgetId, aArea, aPosition) { if (aArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); let moveForward = this.shouldMoveForward(aWidgetId, aPosition); this.adjustWidgets(aWidgetId, moveForward); } }, - onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { if (aArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); let moveForward = this.shouldMoveForward(aWidgetId, aNewPosition); this.adjustWidgets(aWidgetId, moveForward); } }, - onWidgetRemoved(aWidgetId, aPrevArea) { + onWidgetRemoved: function(aWidgetId, aPrevArea) { if (aPrevArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); this.adjustWidgets(aWidgetId, false); } }, - onWidgetReset(aWidgetId) { + onWidgetReset: function(aWidgetId) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); }, // Listener to keep abreast of any new nodes. We use the DOM one because // we need access to the actual node's classlist, so we can't use the ones above. // Furthermore, onWidgetCreated only fires for API-based widgets, not for XUL ones. - onWidgetAfterDOMChange(aNode, aNextNode, aContainer) { + onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer) { if (!gSeenWidgets.has(aNode.id)) { if (aNode.classList.contains(CustomizableUI.WIDE_PANEL_CLASS)) { gWideWidgets.add(aNode.id); @@ -57,11 +57,11 @@ var PanelWideWidgetTracker = { } }, // When widgets get destroyed, we remove them from our sets of stuff we care about: - onWidgetDestroyed(aWidgetId) { + onWidgetDestroyed: function(aWidgetId) { gSeenWidgets.delete(aWidgetId); gWideWidgets.delete(aWidgetId); }, - shouldMoveForward(aWidgetId, aPosition) { + shouldMoveForward: function(aWidgetId, aPosition) { let currentWidgetAtPosition = gPanelPlacements[aPosition + 1]; let rv = gWideWidgets.has(currentWidgetAtPosition) && !gWideWidgets.has(aWidgetId); // We might now think we can move forward, but for that we need at least 2 more small @@ -83,7 +83,7 @@ var PanelWideWidgetTracker = { } return rv; }, - adjustWidgets(aWidgetId, aMoveForwards) { + adjustWidgets: function(aWidgetId, aMoveForwards) { if (this.adjusting) { return; } @@ -104,7 +104,7 @@ var PanelWideWidgetTracker = { // This function is called whenever an item gets moved in the menu panel. It // adjusts the position of widgets within the panel to prevent "gaps" between // wide widgets that could be filled up with single column widgets - adjustPosition(aWidgetId, aMoveForwards) { + adjustPosition: function(aWidgetId, aMoveForwards) { // Make sure that there are n % columns = 0 narrow buttons before the widget. let placementIndex = gPanelPlacements.indexOf(aWidgetId); let prevSiblingCount = 0; @@ -144,7 +144,7 @@ var PanelWideWidgetTracker = { * "public-only" if it's not shown in private windows * "real" if it does exist and is shown even in private windows */ - checkWidgetStatus(aWidgetId) { + checkWidgetStatus: function(aWidgetId) { let widgetWrapper = CustomizableUI.getWidget(aWidgetId); // This widget might not actually exist: if (!widgetWrapper) { @@ -164,7 +164,7 @@ var PanelWideWidgetTracker = { return "real"; }, - init() { + init: function() { // Initialize our local placements copy and register the listener gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); CustomizableUI.addListener(this); diff --git a/browser/components/customizableui/ScrollbarSampler.jsm b/browser/components/customizableui/ScrollbarSampler.jsm index 5a2bfd3e07d7..44736e4c4e08 100644 --- a/browser/components/customizableui/ScrollbarSampler.jsm +++ b/browser/components/customizableui/ScrollbarSampler.jsm @@ -14,7 +14,7 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm"); var gSystemScrollbarWidth = null; this.ScrollbarSampler = { - getSystemScrollbarWidth() { + getSystemScrollbarWidth: function() { if (gSystemScrollbarWidth !== null) { return Promise.resolve(gSystemScrollbarWidth); } @@ -27,11 +27,11 @@ this.ScrollbarSampler = { }); }, - resetSystemScrollbarWidth() { + resetSystemScrollbarWidth: function() { gSystemScrollbarWidth = null; }, - _sampleSystemScrollbarWidth() { + _sampleSystemScrollbarWidth: function() { let hwin = Services.appShell.hiddenDOMWindow; let hdoc = hwin.document.documentElement; let iframe = hwin.document.createElementNS("http://www.w3.org/1999/xhtml", diff --git a/browser/components/customizableui/content/panelUI.js b/browser/components/customizableui/content/panelUI.js index 173f788b0011..112e2e72f935 100644 --- a/browser/components/customizableui/content/panelUI.js +++ b/browser/components/customizableui/content/panelUI.js @@ -37,7 +37,7 @@ const PanelUI = { }, _initialized: false, - init() { + init: function() { for (let [k, v] of Object.entries(this.kElements)) { // Need to do fresh let-bindings per iteration let getKey = k; @@ -57,13 +57,13 @@ const PanelUI = { }, _eventListenersAdded: false, - _ensureEventListenersAdded() { + _ensureEventListenersAdded: function() { if (this._eventListenersAdded) return; this._addEventListeners(); }, - _addEventListeners() { + _addEventListeners: function() { for (let event of this.kEvents) { this.panel.addEventListener(event, this); } @@ -72,7 +72,7 @@ const PanelUI = { this._eventListenersAdded = true; }, - uninit() { + uninit: function() { for (let event of this.kEvents) { this.panel.removeEventListener(event, this); } @@ -92,7 +92,7 @@ const PanelUI = { * @param aMainView * The mainView node to put back into place. */ - setMainView(aMainView) { + setMainView: function(aMainView) { this._ensureEventListenersAdded(); this.multiView.setMainView(aMainView); }, @@ -103,7 +103,7 @@ const PanelUI = { * * @param aEvent the event that triggers the toggle. */ - toggle(aEvent) { + toggle: function(aEvent) { // Don't show the panel if the window is in customization mode, // since this button doubles as an exit path for the user in this case. if (document.documentElement.hasAttribute("customizing")) { @@ -124,7 +124,7 @@ const PanelUI = { * * @param aEvent the event (if any) that triggers showing the menu. */ - show(aEvent) { + show: function(aEvent) { return new Promise(resolve => { this.ensureReady().then(() => { if (this.panel.state == "open" || @@ -170,7 +170,7 @@ const PanelUI = { /** * If the menu panel is being shown, hide it. */ - hide() { + hide: function() { if (document.documentElement.hasAttribute("customizing")) { return; } @@ -178,7 +178,7 @@ const PanelUI = { this.panel.hidePopup(); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { // Ignore context menus and menu button menus showing and hiding: if (aEvent.type.startsWith("popup") && aEvent.target != this.panel) { @@ -221,7 +221,7 @@ const PanelUI = { * * @return a Promise that resolves once the panel is ready to roll. */ - ensureReady(aCustomizing = false) { + ensureReady: function(aCustomizing = false) { if (this._readyPromise) { return this._readyPromise; } @@ -282,7 +282,7 @@ const PanelUI = { * Switch the panel to the main view if it's not already * in that view. */ - showMainView() { + showMainView: function() { this._ensureEventListenersAdded(); this.multiView.showMainView(); }, @@ -291,7 +291,7 @@ const PanelUI = { * Switch the panel to the help view if it's not already * in that view. */ - showHelpView(aAnchor) { + showHelpView: function(aAnchor) { this._ensureEventListenersAdded(); this.multiView.showSubView("PanelUI-helpView", aAnchor); }, @@ -410,15 +410,15 @@ const PanelUI = { * affect the hiding/showing animations of single-subview panels (tempPanel * in the showSubView method). */ - disableSingleSubviewPanelAnimations() { + disableSingleSubviewPanelAnimations: function() { this._disableAnimations = true; }, - enableSingleSubviewPanelAnimations() { + enableSingleSubviewPanelAnimations: function() { this._disableAnimations = false; }, - onWidgetAfterDOMChange(aNode, aNextNode, aContainer, aWasRemoval) { + onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer, aWasRemoval) { if (aContainer != this.contents) { return; } @@ -427,7 +427,7 @@ const PanelUI = { } }, - onWidgetBeforeDOMChange(aNode, aNextNode, aContainer, aIsRemoval) { + onWidgetBeforeDOMChange: function(aNode, aNextNode, aContainer, aIsRemoval) { if (aContainer != this.contents) { return; } @@ -442,7 +442,7 @@ const PanelUI = { * Signal that we're about to make a lot of changes to the contents of the * panels all at once. For performance, we ignore the mutations. */ - beginBatchUpdate() { + beginBatchUpdate: function() { this._ensureEventListenersAdded(); this.multiView.ignoreMutations = true; }, @@ -452,12 +452,12 @@ const PanelUI = { * attention to mutations. This automatically synchronizes the multiview * container with whichever view is displayed if the panel is open. */ - endBatchUpdate(aReason) { + endBatchUpdate: function(aReason) { this._ensureEventListenersAdded(); this.multiView.ignoreMutations = false; }, - _adjustLabelsForAutoHyphens(aNode) { + _adjustLabelsForAutoHyphens: function(aNode) { let toolbarButtons = aNode ? [aNode] : this.contents.querySelectorAll(".toolbarbutton-1"); for (let node of toolbarButtons) { @@ -477,12 +477,12 @@ const PanelUI = { * Sets the anchor node into the open or closed state, depending * on the state of the panel. */ - _updatePanelButton() { + _updatePanelButton: function() { this.menuButton.open = this.panel.state == "open" || this.panel.state == "showing"; }, - _onHelpViewShow(aEvent) { + _onHelpViewShow: function(aEvent) { // Call global menu setup function buildHelpMenu(); @@ -515,7 +515,7 @@ const PanelUI = { items.appendChild(fragment); }, - _updateQuitTooltip() { + _updateQuitTooltip: function() { if (AppConstants.platform == "win") { return; } @@ -535,7 +535,7 @@ const PanelUI = { }, _overlayScrollListenerBoundFn: null, - _overlayScrollListener(aMQL) { + _overlayScrollListener: function(aMQL) { ScrollbarSampler.resetSystemScrollbarWidth(); this._scrollWidth = null; }, diff --git a/browser/components/customizableui/content/toolbar.xml b/browser/components/customizableui/content/toolbar.xml index 8b8d631ca987..299c7865fb16 100644 --- a/browser/components/customizableui/content/toolbar.xml +++ b/browser/components/customizableui/content/toolbar.xml @@ -293,7 +293,7 @@ return !!this.contextMenu; }, - init(event) { + init: function(event) { let node = event.target; while (node != this.toolbar) { if (node.localName == "menupopup") @@ -313,7 +313,7 @@ this.contextMenu.addEventListener("popuphiding", this, false); this.toolbar.addEventListener("mousemove", this, false); }, - handleEvent(event) { + handleEvent: function(event) { switch (event.type) { case "popupshown": this.toolbar.removeEventListener("mousemove", this, false); diff --git a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js b/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js index 5545c3fd0e9c..22fbb5c0c227 100644 --- a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js +++ b/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js @@ -12,7 +12,7 @@ function simulateItemDragAndEnd(aToDrag, aTarget) { var [result, dataTransfer] = EventUtils.synthesizeDragOver(aToDrag.parentNode, aTarget); EventUtils.synthesizeDropAfterDragOver(result, dataTransfer, aTarget); // Send dragend to move dragging item back to initial place. - EventUtils.sendDragEvent({ type: "dragend", dataTransfer }, + EventUtils.sendDragEvent({ type: "dragend", dataTransfer: dataTransfer }, aToDrag.parentNode); } finally { ds.endDragSession(true); diff --git a/browser/components/customizableui/test/browser_877006_missing_view.js b/browser/components/customizableui/test/browser_877006_missing_view.js index b16775d5bb17..a1495c1feda4 100644 --- a/browser/components/customizableui/test/browser_877006_missing_view.js +++ b/browser/components/customizableui/test/browser_877006_missing_view.js @@ -12,7 +12,7 @@ add_task(function testAddbrokenViewWidget() { type: 'view', viewId: 'idontexist', /* Empty handler so we try to attach it maybe? */ - onViewShowing() { + onViewShowing: function() { } }; diff --git a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js index d19eed775e60..61adac9826f3 100644 --- a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js +++ b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js @@ -15,7 +15,7 @@ add_task(function*() { for (let i = 0; i < kTestWidgetCount; i++) { let id = kTestWidgetPfx + i; widgetIds.push(id); - let spec = {id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i}; + let spec = {id: id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } for (let i = kTestWidgetCount; i < kTestWidgetCount * 2; i++) { diff --git a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js b/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js index 45b90d9e7a0a..c2006bef048d 100644 --- a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js +++ b/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js @@ -14,7 +14,7 @@ add_task(function*() { let privateWindow = null; let observerWindowOpened = { - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { privateWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow); privateWindow.addEventListener("load", function newWindowHandler() { diff --git a/browser/components/customizableui/test/browser_947914_button_newWindow.js b/browser/components/customizableui/test/browser_947914_button_newWindow.js index 9c3f08c93abe..47162ee86147 100644 --- a/browser/components/customizableui/test/browser_947914_button_newWindow.js +++ b/browser/components/customizableui/test/browser_947914_button_newWindow.js @@ -13,7 +13,7 @@ add_task(function*() { let newWindow = null; let observerWindowOpened = { - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { newWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow); newWindow.addEventListener("load", function newWindowHandler() { diff --git a/browser/components/customizableui/test/browser_973641_button_addon.js b/browser/components/customizableui/test/browser_973641_button_addon.js index 8d7198dc1646..796bf3d0ecad 100755 --- a/browser/components/customizableui/test/browser_973641_button_addon.js +++ b/browser/components/customizableui/test/browser_973641_button_addon.js @@ -14,7 +14,7 @@ add_task(function*() { let widgetSpec = { id: kButton, type: 'button', - onClick() { + onClick: function() { gBrowser.selectedTab = gBrowser.addTab("about:addons"); } }; diff --git a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js b/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js index d6ed3c205278..3bfa8c25d57f 100644 --- a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js +++ b/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js @@ -20,7 +20,7 @@ add_task(function*() { let id = kTestWidgetPrefix + i; widgetIds.push(id); if (testWidgetExists[i]) { - let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; + let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } } @@ -57,7 +57,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -106,7 +106,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -156,7 +156,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -207,7 +207,7 @@ add_task(function*() { for (let i = 5; i >= 0; i--) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar", 0); } @@ -215,7 +215,7 @@ add_task(function*() { for (let i = 10; i < 15; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -269,8 +269,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated(node) { + let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated: function(node) { node.style.minWidth = "200px"; if (id == (kTestWidgetPrefix + nonOverflowableId)) { node.setAttribute("overflows", false); @@ -325,8 +325,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated(node) { node.style.minWidth = "100px"; }}; + let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated: function(node) { node.style.minWidth = "100px"; }}; info("Creating: " + id); CustomizableUI.createWidget(spec); } @@ -374,8 +374,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated(node) { node.style.minWidth = "200px"; }}; + let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated: function(node) { node.style.minWidth = "200px"; }}; info("Creating: " + id); CustomizableUI.createWidget(spec); } diff --git a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js b/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js index fafbc93592c1..15197ac86f12 100644 --- a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js +++ b/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js @@ -14,7 +14,7 @@ add_task(function* addOverflowingToolbar() { for (let i = 0; i < 10; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; + let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } diff --git a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js index 1f27e604ae3d..9a7227a47b6b 100644 --- a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js +++ b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js @@ -13,7 +13,7 @@ add_task(function* testAddOnBeforeCreatedWidget() { id: kWidgetId, type: 'view', viewId: kWidgetId + 'idontexistyet', - onBeforeCreated(doc) { + onBeforeCreated: function(doc) { let view = doc.createElement("panelview"); view.id = kWidgetId + 'idontexistyet'; let label = doc.createElement("label"); @@ -23,7 +23,7 @@ add_task(function* testAddOnBeforeCreatedWidget() { document.getElementById("PanelUI-multiView").appendChild(view); onBeforeCreatedCalled = true; }, - onViewShowing() { + onViewShowing: function() { viewShownDeferred.resolve(); } }; diff --git a/browser/components/customizableui/test/browser_987492_window_api.js b/browser/components/customizableui/test/browser_987492_window_api.js index 2fccd1b5b82f..104a14ba6d98 100644 --- a/browser/components/customizableui/test/browser_987492_window_api.js +++ b/browser/components/customizableui/test/browser_987492_window_api.js @@ -16,7 +16,7 @@ add_task(function* testOneWindow() { add_task(function* testOpenCloseWindow() { let newWindow = null; let openListener = { - onWindowOpened(window) { + onWindowOpened: function(window) { newWindow = window; } } @@ -39,7 +39,7 @@ add_task(function* testOpenCloseWindow() { let closedWindow = null; let closeListener = { - onWindowClosed(window) { + onWindowClosed: function(window) { closedWindow = window; } } diff --git a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js b/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js index a8790f539869..4d292a929c67 100644 --- a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js +++ b/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js @@ -65,7 +65,7 @@ add_task(function*() { otherTB.setAttribute("customizable", "true"); let wasInformedCorrectlyOfAreaAppearing = false; let listener = { - onAreaNodeRegistered(aArea, aNode) { + onAreaNodeRegistered: function(aArea, aNode) { if (aNode == otherTB) { wasInformedCorrectlyOfAreaAppearing = true; } @@ -99,14 +99,14 @@ add_task(function*() { // (and therefore onAreaNodeRegistered) one, causing the test to fail. let windowCloseDeferred = Promise.defer(); listener = { - onAreaNodeUnregistered(aArea, aNode, aReason) { + onAreaNodeUnregistered: function(aArea, aNode, aReason) { if (aArea == TOOLBARID) { is(aNode, otherTB, "Should be informed about other toolbar"); is(aReason, CustomizableUI.REASON_WINDOW_CLOSED, "Reason should be correct."); wasInformedCorrectlyOfAreaDisappearing = (aReason === CustomizableUI.REASON_WINDOW_CLOSED); } }, - onWindowClosed(aWindow) { + onWindowClosed: function(aWindow) { if (aWindow == otherWin) { windowCloseDeferred.resolve(aWindow); } else { @@ -133,7 +133,7 @@ add_task(function*() { CustomizableUI.removeListener(listener); wasInformedCorrectlyOfAreaDisappearing = false; listener = { - onAreaNodeUnregistered(aArea, aNode, aReason) { + onAreaNodeUnregistered: function(aArea, aNode, aReason) { if (aArea == TOOLBARID) { is(aNode, toolbar, "Should be informed about this window's toolbar"); is(aReason, CustomizableUI.REASON_AREA_UNREGISTERED, "Reason for final removal should be correct."); diff --git a/browser/components/migration/360seProfileMigrator.js b/browser/components/migration/360seProfileMigrator.js index 83e2880b132b..42347d542a68 100644 --- a/browser/components/migration/360seProfileMigrator.js +++ b/browser/components/migration/360seProfileMigrator.js @@ -209,7 +209,7 @@ function Qihoo360seProfileMigrator() { Qihoo360seProfileMigrator.prototype = Object.create(MigratorPrototype); Object.defineProperty(Qihoo360seProfileMigrator.prototype, "sourceProfiles", { - get() { + get: function() { if ("__sourceProfiles" in this) return this.__sourceProfiles; diff --git a/browser/components/migration/ChromeProfileMigrator.js b/browser/components/migration/ChromeProfileMigrator.js index ee99db3ca626..2446f713ca20 100644 --- a/browser/components/migration/ChromeProfileMigrator.js +++ b/browser/components/migration/ChromeProfileMigrator.js @@ -246,7 +246,7 @@ function GetBookmarksResource(aProfileFolder) { return { type: MigrationUtils.resourceTypes.BOOKMARKS, - migrate(aCallback) { + migrate: function(aCallback) { return Task.spawn(function* () { let gotErrors = false; let errorGatherer = function() { gotErrors = true }; @@ -341,12 +341,12 @@ function GetHistoryResource(aProfileFolder) { yield new Promise((resolve, reject) => { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult() { + handleResult: function() { // Importing any entry is considered a successful import. this._success = true; }, - handleError() {}, - handleCompletion() { + handleError: function() {}, + handleCompletion: function() { if (this._success) { resolve(); } else { diff --git a/browser/components/migration/ESEDBReader.jsm b/browser/components/migration/ESEDBReader.jsm index ad842356b338..a01bee53f73b 100644 --- a/browser/components/migration/ESEDBReader.jsm +++ b/browser/components/migration/ESEDBReader.jsm @@ -354,7 +354,7 @@ ESEDB.prototype = { return true; }, - *tableItems(tableName, columns) { + tableItems: function*(tableName, columns) { if (!this._opened) { throw new Error("The database was closed!"); } diff --git a/browser/components/migration/EdgeProfileMigrator.js b/browser/components/migration/EdgeProfileMigrator.js index f2d83d433348..189932bed8aa 100644 --- a/browser/components/migration/EdgeProfileMigrator.js +++ b/browser/components/migration/EdgeProfileMigrator.js @@ -107,7 +107,7 @@ EdgeTypedURLMigrator.prototype = { return this._typedURLs.size > 0; }, - migrate(aCallback) { + migrate: function(aCallback) { let typedURLs = this._typedURLs; let places = []; for (let [urlString, time] of typedURLs) { @@ -140,12 +140,12 @@ EdgeTypedURLMigrator.prototype = { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult() { + handleResult: function() { // Importing any entry is considered a successful import. this._success = true; }, - handleError() {}, - handleCompletion() { + handleError: function() {}, + handleCompletion: function() { aCallback(this._success); } }); diff --git a/browser/components/migration/FirefoxProfileMigrator.js b/browser/components/migration/FirefoxProfileMigrator.js index 485719ae90bf..526c82938f6d 100644 --- a/browser/components/migration/FirefoxProfileMigrator.js +++ b/browser/components/migration/FirefoxProfileMigrator.js @@ -62,7 +62,7 @@ function sorter(a, b) { } Object.defineProperty(FirefoxProfileMigrator.prototype, "sourceProfiles", { - get() { + get: function() { return [...this._getAllProfiles().keys()].map(x => ({id: x, name: x})).sort(sorter); } }); @@ -117,7 +117,7 @@ FirefoxProfileMigrator.prototype._getResourcesInternal = function(sourceProfileD } return { type: aMigrationType, - migrate(aCallback) { + migrate: function(aCallback) { for (let file of files) { file.copyTo(currentProfileDir, ""); } @@ -143,7 +143,7 @@ FirefoxProfileMigrator.prototype._getResourcesInternal = function(sourceProfileD if (sessionFile) { session = { type: types.SESSION, - migrate(aCallback) { + migrate: function(aCallback) { sessionCheckpoints.copyTo(currentProfileDir, "sessionCheckpoints.json"); let newSessionFile = currentProfileDir.clone(); newSessionFile.append("sessionstore.js"); diff --git a/browser/components/migration/IEProfileMigrator.js b/browser/components/migration/IEProfileMigrator.js index 97582208358a..b1ff92a69f65 100644 --- a/browser/components/migration/IEProfileMigrator.js +++ b/browser/components/migration/IEProfileMigrator.js @@ -76,9 +76,9 @@ History.prototype = { let lastVisitTime = entry.get("time") || (Date.now() * 1000); places.push( - { uri, - title, - visits: [{ transitionType, + { uri: uri, + title: title, + visits: [{ transitionType: transitionType, visitDate: lastVisitTime }] } ); @@ -92,12 +92,12 @@ History.prototype = { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult() { + handleResult: function() { // Importing any entry is considered a successful import. this._success = true; }, - handleError() {}, - handleCompletion() { + handleError: function() {}, + handleCompletion: function() { aCallback(this._success); } }); @@ -320,8 +320,8 @@ IE7FormPasswords.prototype = { fileTimeToSecondsSinceEpoch(currentLoginItem.hiDateTime, currentLoginItem.loDateTime) * 1000; let currentResult = { - creation, - url, + creation: creation, + url: url, }; // The username is UTF-16 and null-terminated. currentResult.username = diff --git a/browser/components/migration/MSMigrationUtils.jsm b/browser/components/migration/MSMigrationUtils.jsm index 989e6bb541be..c36ef21bffdb 100644 --- a/browser/components/migration/MSMigrationUtils.jsm +++ b/browser/components/migration/MSMigrationUtils.jsm @@ -874,7 +874,7 @@ WindowsVaultFormPasswords.prototype = { var MSMigrationUtils = { MIGRATION_TYPE_IE: 1, MIGRATION_TYPE_EDGE: 2, - CtypesKernelHelpers, + CtypesKernelHelpers: CtypesKernelHelpers, getBookmarksMigrator(migrationType = this.MIGRATION_TYPE_IE) { return new Bookmarks(migrationType); }, diff --git a/browser/components/migration/MigrationUtils.jsm b/browser/components/migration/MigrationUtils.jsm index 01f607f646a4..8a966960634f 100644 --- a/browser/components/migration/MigrationUtils.jsm +++ b/browser/components/migration/MigrationUtils.jsm @@ -295,6 +295,7 @@ this.MigratorPrototype = { } notify("Migration:Started"); for (let [migrationType, itemResources] of resourcesGroupedByItems) { + notify("Migration:ItemBeforeMigrate", migrationType); let itemSuccess = false; diff --git a/browser/components/migration/SafariProfileMigrator.js b/browser/components/migration/SafariProfileMigrator.js index 2d782d5a448d..664eb13beca8 100644 --- a/browser/components/migration/SafariProfileMigrator.js +++ b/browser/components/migration/SafariProfileMigrator.js @@ -220,7 +220,7 @@ History.prototype = { places.push({ uri: NetUtil.newURI(entry.get("")), title: entry.get("title"), visits: [{ transitionType: transType, - visitDate }] }); + visitDate: visitDate }] }); } catch (ex) { // Safari's History file may contain malformed URIs which @@ -232,12 +232,12 @@ History.prototype = { if (places.length > 0) { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult() { + handleResult: function() { // Importing any entry is considered a successful import. this._success = true; }, - handleError() {}, - handleCompletion() { + handleError: function() {}, + handleCompletion: function() { aCallback(this._success); } }); diff --git a/browser/components/migration/content/migration.js b/browser/components/migration/content/migration.js index 908c9b965482..3691232069da 100644 --- a/browser/components/migration/content/migration.js +++ b/browser/components/migration/content/migration.js @@ -22,7 +22,7 @@ var MigrationWizard = { /* exported MigrationWizard */ _migrator: null, _autoMigrate: null, - init() + init: function() { let os = Services.obs; os.addObserver(this, "Migration:Started", false); @@ -58,7 +58,7 @@ var MigrationWizard = { /* exported MigrationWizard */ this.onImportSourcePageShow(); }, - uninit() + uninit: function() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); @@ -71,7 +71,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 1 - Import Source - onImportSourcePageShow() + onImportSourcePageShow: function() { // Show warning message to close the selected browser when needed function toggleCloseBrowserWarning() { @@ -137,7 +137,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportSourcePageAdvanced() + onImportSourcePageAdvanced: function() { var newSource = document.getElementById("importSourceGroup").selectedItem.id; @@ -183,7 +183,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 2 - [Profile Selection] - onSelectProfilePageShow() + onSelectProfilePageShow: function() { // Disabling this for now, since we ask about import sources in automigration // too and don't want to disable the back button @@ -210,7 +210,7 @@ var MigrationWizard = { /* exported MigrationWizard */ profiles.selectedItem = this._selectedProfile ? document.getElementById(this._selectedProfile.id) : profiles.firstChild; }, - onSelectProfilePageRewound() + onSelectProfilePageRewound: function() { var profiles = document.getElementById("profiles"); this._selectedProfile = this._migrator.sourceProfiles.find( @@ -218,7 +218,7 @@ var MigrationWizard = { /* exported MigrationWizard */ ) || null; }, - onSelectProfilePageAdvanced() + onSelectProfilePageAdvanced: function() { var profiles = document.getElementById("profiles"); this._selectedProfile = this._migrator.sourceProfiles.find( @@ -231,7 +231,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 3 - ImportItems - onImportItemsPageShow() + onImportItemsPageShow: function() { var dataSources = document.getElementById("dataSources"); while (dataSources.hasChildNodes()) @@ -252,13 +252,13 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportItemsPageRewound() + onImportItemsPageRewound: function() { this._wiz.canAdvance = true; this.onImportItemsPageAdvanced(); }, - onImportItemsPageAdvanced() + onImportItemsPageAdvanced: function() { var dataSources = document.getElementById("dataSources"); this._itemsFlags = 0; @@ -269,7 +269,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportItemCommand() + onImportItemCommand: function() { var items = document.getElementById("dataSources"); var checkboxes = items.getElementsByTagName("checkbox"); @@ -286,7 +286,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 4 - Home Page Selection - onHomePageMigrationPageShow() + onHomePageMigrationPageShow: function() { // only want this on the first run if (!this._autoMigrate) { @@ -338,7 +338,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onHomePageMigrationPageAdvanced() + onHomePageMigrationPageAdvanced: function() { // we might not have a selectedItem if we're in fallback mode try { @@ -349,7 +349,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 5 - Migrating - onMigratingPageShow() + onMigratingPageShow: function() { this._wiz.getButton("cancel").disabled = true; this._wiz.canRewind = false; @@ -363,7 +363,7 @@ var MigrationWizard = { /* exported MigrationWizard */ setTimeout(() => this.onMigratingMigrate(), 0); }, - onMigratingMigrate() + onMigratingMigrate: function() { this._migrator.migrate(this._itemsFlags, this._autoMigrate, this._selectedProfile); @@ -383,7 +383,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - _listItems(aID) + _listItems: function(aID) { var items = document.getElementById(aID); while (items.hasChildNodes()) @@ -409,7 +409,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - observe(aSubject, aTopic, aData) + observe: function(aSubject, aTopic, aData) { var label; switch (aTopic) { @@ -514,7 +514,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onDonePageShow() + onDonePageShow: function() { this._wiz.getButton("cancel").disabled = true; this._wiz.canRewind = false; diff --git a/browser/components/migration/tests/unit/test_automigration.js b/browser/components/migration/tests/unit/test_automigration.js index 3a19dcbc3f62..34e90d00d900 100644 --- a/browser/components/migration/tests/unit/test_automigration.js +++ b/browser/components/migration/tests/unit/test_automigration.js @@ -215,7 +215,7 @@ add_task(function* checkUndoRemoval() { let frecencyUpdatePromise = new Promise(resolve => { let expectedChanges = 2; let observer = { - onFrecencyChanged() { + onFrecencyChanged: function() { if (!--expectedChanges) { PlacesUtils.history.removeObserver(observer); resolve(); @@ -561,31 +561,31 @@ add_task(function* checkUndoVisitsState() { ]); let wrongMethodDeferred = PromiseUtils.defer(); let observer = { - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onVisit(uri) { + onBeginUpdateBatch: function() {}, + onEndUpdateBatch: function() {}, + onVisit: function(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onVisit " + uri.spec)); }, - onTitleChanged(uri) { + onTitleChanged: function(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onTitleChanged " + uri.spec)); }, - onClearHistory() { + onClearHistory: function() { wrongMethodDeferred.reject("Unexpected call to onClearHistory"); }, - onPageChanged(uri) { + onPageChanged: function(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onPageChanged " + uri.spec)); }, - onFrecencyChanged(aURI) { + onFrecencyChanged: function(aURI) { do_print("frecency change"); Assert.ok(frecencyChangesExpected.has(aURI.spec), "Should be expecting frecency change for " + aURI.spec); frecencyChangesExpected.get(aURI.spec).resolve(); }, - onManyFrecenciesChanged() { + onManyFrecenciesChanged: function() { do_print("Many frecencies changed"); wrongMethodDeferred.reject(new Error("This test can't deal with onManyFrecenciesChanged to be called")); }, - onDeleteURI(aURI) { + onDeleteURI: function(aURI) { do_print("delete uri"); Assert.ok(uriDeletedExpected.has(aURI.spec), "Should be expecting uri deletion for " + aURI.spec); diff --git a/browser/components/newtab/NewTabURL.jsm b/browser/components/newtab/NewTabURL.jsm index 9c8b78dd571a..5000eae2e9ae 100644 --- a/browser/components/newtab/NewTabURL.jsm +++ b/browser/components/newtab/NewTabURL.jsm @@ -18,7 +18,7 @@ XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", this.NewTabURL = { - get() { + get: function() { return aboutNewTabService.newTabURL; }, @@ -26,11 +26,11 @@ this.NewTabURL = { return aboutNewTabService.overridden; }, - override(newURL) { + override: function(newURL) { aboutNewTabService.newTabURL = newURL; }, - reset() { + reset: function() { aboutNewTabService.resetNewTabURL(); } }; diff --git a/browser/components/newtab/NewTabWebChannel.jsm b/browser/components/newtab/NewTabWebChannel.jsm index 8a6973f9e603..28614ebb7883 100644 --- a/browser/components/newtab/NewTabWebChannel.jsm +++ b/browser/components/newtab/NewTabWebChannel.jsm @@ -188,7 +188,7 @@ NewTabWebChannelImpl.prototype = { try { let msg = JSON.parse(message); - this.emit(msg.type, {data: msg.data, target}); + this.emit(msg.type, {data: msg.data, target: target}); } catch (err) { Cu.reportError(err); } diff --git a/browser/components/newtab/PlacesProvider.jsm b/browser/components/newtab/PlacesProvider.jsm index 63e17b88deee..2e26729c6435 100644 --- a/browser/components/newtab/PlacesProvider.jsm +++ b/browser/components/newtab/PlacesProvider.jsm @@ -248,6 +248,6 @@ Links.prototype = { const gLinks = new Links(); // jshint ignore:line let PlacesProvider = { - LinkChecker, + LinkChecker: LinkChecker, links: gLinks, }; diff --git a/browser/components/newtab/tests/browser/newtabwebchannel_basic.html b/browser/components/newtab/tests/browser/newtabwebchannel_basic.html index 5e26d5b755fb..75656b7167db 100644 --- a/browser/components/newtab/tests/browser/newtabwebchannel_basic.html +++ b/browser/components/newtab/tests/browser/newtabwebchannel_basic.html @@ -25,7 +25,7 @@ detail = JSON.stringify(detail); } let reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail + detail: detail }); window.dispatchEvent(reply); } diff --git a/browser/components/nsBrowserGlue.js b/browser/components/nsBrowserGlue.js index 255b39c279e1..f06528712477 100644 --- a/browser/components/nsBrowserGlue.js +++ b/browser/components/nsBrowserGlue.js @@ -543,7 +543,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getFormattedString("addonwatch.disable.label", [addon.name]), accessKey: "", // workaround for bug 1192901 - callback() { + callback: function() { done(STATE_USER_PICKED_DISABLE); addon.userDisabled = true; if (addon.pendingOperations == addon.PENDING_NONE) { @@ -554,7 +554,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getFormattedString("addonwatch.restart.label", [brandShortName]), accessKey: win.gNavigatorBundle.getString("addonwatch.restart.accesskey"), - callback() { + callback: function() { let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"] .getService(Ci.nsIAppStartup); appStartup.quit(appStartup.eForceQuit | appStartup.eRestart); @@ -569,7 +569,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("addonwatch.ignoreSession.label"), accessKey: win.gNavigatorBundle.getString("addonwatch.ignoreSession.accesskey"), - callback() { + callback: function() { done(STATE_USER_PICKED_IGNORE_FOR_NOW); AddonWatcher.ignoreAddonForSession(addonId); } @@ -577,7 +577,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("addonwatch.ignorePerm.label"), accessKey: win.gNavigatorBundle.getString("addonwatch.ignorePerm.accesskey"), - callback() { + callback: function() { done(STATE_USER_PICKED_IGNORE_FOREVER); AddonWatcher.ignoreAddonPermanently(addonId); } @@ -672,7 +672,7 @@ BrowserGlue.prototype = { Services.obs.notifyObservers(null, "browser-ui-startup-complete", ""); }, - _checkForOldBuildUpdates() { + _checkForOldBuildUpdates: function() { // check for update if our build is old if (AppConstants.MOZ_UPDATER && Services.prefs.getBoolPref("app.update.enabled") && @@ -724,7 +724,7 @@ BrowserGlue.prototype = { } }, - _trackSlowStartup() { + _trackSlowStartup: function() { if (Services.startup.interrupted || Services.prefs.getBoolPref("browser.slowStartup.notificationDisabled")) return; @@ -767,7 +767,7 @@ BrowserGlue.prototype = { return (Date.now() - profileDate) / ONE_DAY; }), - _showSlowStartupNotification(profileAge) { + _showSlowStartupNotification: function(profileAge) { if (profileAge < 90) // 3 months return; @@ -782,14 +782,14 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("slowStartup.helpButton.label"), accessKey: win.gNavigatorBundle.getString("slowStartup.helpButton.accesskey"), - callback() { + callback: function() { win.openUILinkIn("https://support.mozilla.org/kb/reset-firefox-easily-fix-most-problems", "tab"); } }, { label: win.gNavigatorBundle.getString("slowStartup.disableNotificationButton.label"), accessKey: win.gNavigatorBundle.getString("slowStartup.disableNotificationButton.accesskey"), - callback() { + callback: function() { Services.prefs.setBoolPref("browser.slowStartup.notificationDisabled", true); } } @@ -808,7 +808,7 @@ BrowserGlue.prototype = { * String of either "unused" or "uninstall", specifying the reason * why a profile reset is offered. */ - _resetProfileNotification(reason) { + _resetProfileNotification: function(reason) { let win = RecentWindow.getMostRecentBrowserWindow(); if (!win) return; @@ -833,7 +833,7 @@ BrowserGlue.prototype = { { label: resetBundle.formatStringFromName("refreshProfile.resetButton.label", [productName], 1), accessKey: resetBundle.GetStringFromName("refreshProfile.resetButton.accesskey"), - callback() { + callback: function() { ResetProfile.openConfirmationDialog(win); } }, @@ -845,7 +845,7 @@ BrowserGlue.prototype = { nb.PRIORITY_INFO_LOW, buttons); }, - _notifyUnsignedAddonsDisabled() { + _notifyUnsignedAddonsDisabled: function() { let win = RecentWindow.getMostRecentBrowserWindow(); if (!win) return; @@ -855,7 +855,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("unsignedAddonsDisabled.learnMore.label"), accessKey: win.gNavigatorBundle.getString("unsignedAddonsDisabled.learnMore.accesskey"), - callback() { + callback: function() { win.BrowserOpenAddonsMgr("addons://list/extension?unsigned=true"); } }, @@ -866,7 +866,7 @@ BrowserGlue.prototype = { nb.PRIORITY_WARNING_MEDIUM, buttons); }, - _firstWindowTelemetry(aWindow) { + _firstWindowTelemetry: function(aWindow) { let SCALING_PROBE_NAME = ""; switch (AppConstants.platform) { case "win": @@ -979,7 +979,7 @@ BrowserGlue.prototype = { /** * Application shutdown handler. */ - _onQuitApplicationGranted() { + _onQuitApplicationGranted: function() { // This pref must be set here because SessionStore will use its value // on quit-application. this._setPrefToSaveSession(); @@ -1008,14 +1008,14 @@ BrowserGlue.prototype = { } }, - _initServiceDiscovery() { + _initServiceDiscovery: function() { if (!Services.prefs.getBoolPref("browser.casting.enabled")) { return; } var rokuDevice = { id: "roku:ecp", target: "roku:ecp", - factory(aService) { + factory: function(aService) { Cu.import("resource://gre/modules/RokuApp.jsm"); return new RokuApp(aService); }, @@ -1171,7 +1171,7 @@ BrowserGlue.prototype = { E10SAccessibilityCheck.onWindowsRestored(); }, - _createExtraDefaultProfile() { + _createExtraDefaultProfile: function() { if (!AppConstants.MOZ_DEV_EDITION) { return; } @@ -1391,10 +1391,10 @@ BrowserGlue.prototype = { let buttons = [ { - label, + label: label, accessKey: key, popup: null, - callback(aNotificationBar, aButton) { + callback: function(aNotificationBar, aButton) { win.openUILinkIn(url, "tab"); } } @@ -1694,9 +1694,9 @@ BrowserGlue.prototype = { var buttons = [ { label: buttonText, - accessKey, + accessKey: accessKey, popup: null, - callback(aNotificationBar, aButton) { + callback: function(aNotificationBar, aButton) { win.openUILinkIn(url, "tab"); } } @@ -1709,7 +1709,7 @@ BrowserGlue.prototype = { notification.persistence = -1; // Until user closes it }, - _showSyncStartedDoorhanger() { + _showSyncStartedDoorhanger: function() { let bundle = Services.strings.createBundle("chrome://browser/locale/accounts.properties"); let productName = gBrandBundle.GetStringFromName("brandShortName"); let title = bundle.GetStringFromName("syncStartNotification.title"); @@ -2098,7 +2098,7 @@ BrowserGlue.prototype = { true, url, clickCallback); }), - _hasSystemAlertsService() { + _hasSystemAlertsService: function() { try { return !!Cc["@mozilla.org/system-alerts-service;1"].getService( Ci.nsIAlertsService); @@ -2356,7 +2356,7 @@ BrowserGlue.prototype = { AlertsService.showAlertNotification(null, title, body, true, null, clickCallback); }, - _handleFlashHang() { + _handleFlashHang: function() { ++this._flashHangCount; if (this._flashHangCount < 2) { return; @@ -2388,7 +2388,7 @@ BrowserGlue.prototype = { let buttons = [{ label: win.gNavigatorBundle.getString("flashHang.helpButton.label"), accessKey: win.gNavigatorBundle.getString("flashHang.helpButton.accesskey"), - callback() { + callback: function() { win.openUILinkIn("https://support.mozilla.org/kb/flash-protected-mode-autodisabled", "tab"); } }]; @@ -2509,13 +2509,13 @@ var DefaultBrowserCheck = { _setAsDefaultTimer: null, _setAsDefaultButtonClickStartTime: 0, - closePrompt(aNode) { + closePrompt: function(aNode) { if (this._notification) { this._notification.close(); } }, - setAsDefault() { + setAsDefault: function() { let claimAllTypes = true; let setAsDefaultError = false; if (AppConstants.platform == "win") { @@ -2571,7 +2571,7 @@ var DefaultBrowserCheck = { .add(setAsDefaultError); }, - _createPopup(win, notNowStrings, neverStrings) { + _createPopup: function(win, notNowStrings, neverStrings) { let doc = win.document; let popup = doc.createElement("menupopup"); popup.id = this.OPTIONPOPUP; @@ -2594,7 +2594,7 @@ var DefaultBrowserCheck = { popupset.appendChild(popup); }, - handleEvent(event) { + handleEvent: function(event) { if (event.type == "command") { if (event.target.id == "defaultBrowserNever") { ShellService.shouldCheckDefaultBrowser = false; @@ -2603,7 +2603,7 @@ var DefaultBrowserCheck = { } }, - prompt(win) { + prompt: function(win) { let useNotificationBar = Services.prefs.getBoolPref("browser.defaultbrowser.notificationbar"); let brandBundle = win.document.getElementById("bundle_brand"); @@ -2689,7 +2689,7 @@ var DefaultBrowserCheck = { } }, - _onNotificationEvent(eventType) { + _onNotificationEvent: function(eventType) { if (eventType == "removed") { let doc = this._notification.ownerDocument; let popup = doc.getElementById(this.OPTIONPOPUP); @@ -2705,7 +2705,7 @@ var E10SAccessibilityCheck = { // first window being opening. _wantsPrompt: false, - init() { + init: function() { Services.obs.addObserver(this, "a11y-init-or-shutdown", true); Services.obs.addObserver(this, "quit-application-granted", true); }, @@ -2719,7 +2719,7 @@ var E10SAccessibilityCheck = { return false; }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case "quit-application-granted": // Tag the profile with a11y load state. We use this in nsAppRunner @@ -2737,7 +2737,7 @@ var E10SAccessibilityCheck = { } }, - onWindowsRestored() { + onWindowsRestored: function() { if (this._wantsPrompt) { this._wantsPrompt = false; this._showE10sAccessibilityWarning(); @@ -2746,7 +2746,7 @@ var E10SAccessibilityCheck = { _warnedAboutAccessibility: false, - _showE10sAccessibilityWarning() { + _showE10sAccessibilityWarning: function() { // We don't prompt about a11y incompat if e10s is off. if (!Services.appinfo.browserTabsRemoteAutostart) { return; @@ -2794,7 +2794,7 @@ var E10SAccessibilityCheck = { let mainAction = { label: win.gNavigatorBundle.getString("e10s.accessibilityNotice.acceptButton.label"), accessKey: win.gNavigatorBundle.getString("e10s.accessibilityNotice.acceptButton.accesskey"), - callback() { + callback: function() { // If the user invoked the button option remove the notification, // otherwise keep the alert icon around in the address bar. notification.remove(); diff --git a/browser/components/originattributes/test/browser/browser_cache.js b/browser/components/originattributes/test/browser/browser_cache.js index f1f80d5ccf6a..87a0aadd1b42 100644 --- a/browser/components/originattributes/test/browser/browser_cache.js +++ b/browser/components/originattributes/test/browser/browser_cache.js @@ -42,8 +42,8 @@ function cacheDataForContext(loadContextInfo) { let cacheVisitor = { onCacheStorageInfo(num, consumption) {}, onCacheEntryInfo(uri, idEnhance) { - cacheEntries.push({ uri, - idEnhance }); + cacheEntries.push({ uri: uri, + idEnhance: idEnhance }); }, onCacheEntryVisitCompleted() { resolve(cacheEntries); @@ -73,7 +73,7 @@ function observeChannels(onChannel) { // We use a dummy proxy filter to catch all channels, even those that do not // generate an "http-on-modify-request" notification, such as link preconnects. let proxyFilter = { - applyFilter(aProxyService, aChannel, aProxy) { + applyFilter : function(aProxyService, aChannel, aProxy) { // We have the channel; provide it to the callback. onChannel(aChannel); // Pass on aProxy unmodified. @@ -141,7 +141,7 @@ function* doInit(aMode) { function* doTest(aBrowser) { let argObj = { - randomSuffix, + randomSuffix: randomSuffix, urlPrefix: TEST_DOMAIN + TEST_PATH, }; diff --git a/browser/components/places/PlacesUIUtils.jsm b/browser/components/places/PlacesUIUtils.jsm index 7ab2f9f0391e..45f3226e6ca4 100644 --- a/browser/components/places/PlacesUIUtils.jsm +++ b/browser/components/places/PlacesUIUtils.jsm @@ -584,7 +584,7 @@ this.PlacesUIUtils = { * @return a Places Transaction that can be transacted for performing the * move/insert command. */ - getTransactionForData(aData, aType, aNewParentGuid, aIndex, aCopy) { + getTransactionForData: function(aData, aType, aNewParentGuid, aIndex, aCopy) { if (!this.SUPPORTED_FLAVORS.includes(aData.type)) throw new Error(`Unsupported '${aData.type}' data type`); @@ -617,7 +617,7 @@ this.PlacesUIUtils = { let title = aData.type != PlacesUtils.TYPE_UNICODE ? aData.title : aData.uri; return PlacesTransactions.NewBookmark({ uri: NetUtil.newURI(aData.uri) - , title + , title: title , parentGuid: aNewParentGuid , index: aIndex }); }, @@ -797,7 +797,7 @@ this.PlacesUIUtils = { * a node, except the root node of a query. * @return true if the aNode represents a removable entry, false otherwise. */ - canUserRemove(aNode) { + canUserRemove: function(aNode) { let parentNode = aNode.parent; if (!parentNode) { // canUserRemove doesn't accept root nodes. @@ -845,7 +845,7 @@ this.PlacesUIUtils = { * @note livemark "folders" are considered read-only (but see bug 1072833). * @return true if aItemId points to a read-only folder, false otherwise. */ - isContentsReadOnly(aNodeOrItemId) { + isContentsReadOnly: function(aNodeOrItemId) { let itemId; if (typeof(aNodeOrItemId) == "number") { itemId = aNodeOrItemId; @@ -1408,7 +1408,7 @@ this.PlacesUIUtils = { return queryName; }, - shouldShowTabsFromOtherComputersMenuitem() { + shouldShowTabsFromOtherComputersMenuitem: function() { let weaveOK = Weave.Status.checkSetup() != Weave.CLIENT_NOT_CONFIGURED && Weave.Svc.Prefs.get("firstSync", "") != "notReady"; return weaveOK; @@ -1691,7 +1691,7 @@ XPCOMUtils.defineLazyGetter(PlacesUIUtils, "ptm", function() { * boolean value. * @return nsITransaction object. */ - setLoadInSidebar(aItemId, aLoadInSidebar) + setLoadInSidebar: function(aItemId, aLoadInSidebar) { let annoObj = { name: PlacesUIUtils.LOAD_IN_SIDEBAR_ANNO, type: Ci.nsIAnnotationService.TYPE_INT32, @@ -1710,7 +1710,7 @@ XPCOMUtils.defineLazyGetter(PlacesUIUtils, "ptm", function() { * new description. * @return nsITransaction object. */ - editItemDescription(aItemId, aDescription) + editItemDescription: function(aItemId, aDescription) { let annoObj = { name: PlacesUIUtils.DESCRIPTION_ANNO, type: Ci.nsIAnnotationService.TYPE_STRING, diff --git a/browser/components/places/content/bookmarkProperties.js b/browser/components/places/content/bookmarkProperties.js index 42d825ea460d..f1695ffd5af7 100644 --- a/browser/components/places/content/bookmarkProperties.js +++ b/browser/components/places/content/bookmarkProperties.js @@ -614,7 +614,7 @@ var BookmarkPropertiesPanel = { let folderGuid = yield PlacesUtils.promiseItemGuid(container); let bm = yield PlacesUtils.bookmarks.fetch({ parentGuid: folderGuid, - index + index: index }); this._itemId = yield PlacesUtils.promiseItemId(bm.guid); diff --git a/browser/components/places/content/browserPlacesViews.js b/browser/components/places/content/browserPlacesViews.js index d5170fa7e1c3..3cdb7135ae30 100644 --- a/browser/components/places/content/browserPlacesViews.js +++ b/browser/components/places/content/browserPlacesViews.js @@ -135,8 +135,8 @@ PlacesViewBase.prototype = { get selType() { return "single"; }, - selectItems() { }, - selectAll() { }, + selectItems: function() { }, + selectAll: function() { }, get selectedNode() { if (this._contextMenuShown) { @@ -619,12 +619,12 @@ PlacesViewBase.prototype = { } }, - nodeTagsChanged() { }, - nodeDateAddedChanged() { }, - nodeLastModifiedChanged() { }, - nodeKeywordChanged() { }, - sortingChanged() { }, - batching() { }, + nodeTagsChanged: function() { }, + nodeDateAddedChanged: function() { }, + nodeLastModifiedChanged: function() { }, + nodeKeywordChanged: function() { }, + sortingChanged: function() { }, + batching: function() { }, nodeInserted: function PVB_nodeInserted(aParentPlacesNode, aPlacesNode, aIndex) { @@ -1180,7 +1180,7 @@ PlacesToolbar.prototype = { } }, - updateOverflowStatus() { + updateOverflowStatus: function() { if (this._rootElt.scrollLeftMin != this._rootElt.scrollLeftMax) { this._onOverflow(); } else { diff --git a/browser/components/places/content/controller.js b/browser/components/places/content/controller.js index 061ba02e82ee..d0e1fab83c32 100644 --- a/browser/components/places/content/controller.js +++ b/browser/components/places/content/controller.js @@ -59,7 +59,7 @@ InsertionPoint.prototype = { return this._index = val; }, - promiseGuid() { + promiseGuid: function() { return PlacesUtils.promiseItemGuid(this.itemId); }, @@ -867,7 +867,7 @@ PlacesController.prototype = { let tag = node.parent.title; if (!tag) tag = PlacesUtils.bookmarks.getItemTitle(tagItemId); - transactions.push(PlacesTransactions.Untag({ uri, tag })); + transactions.push(PlacesTransactions.Untag({ uri: uri, tag: tag })); } else { let txn = new PlacesUntagURITransaction(uri, [tagItemId]); @@ -885,7 +885,7 @@ PlacesController.prototype = { let tag = node.title; let URIs = PlacesUtils.tagging.getURIsForTag(tag); if (PlacesUIUtils.useAsyncTransactions) { - transactions.push(PlacesTransactions.Untag({ tag, uris: URIs })); + transactions.push(PlacesTransactions.Untag({ tag: tag, uris: URIs })); } else { for (var j = 0; j < URIs.length; j++) { @@ -1308,7 +1308,7 @@ PlacesController.prototype = { if (PlacesUIUtils.useAsyncTransactions) { if (ip.isTag) { let uris = items.filter(item => "uri" in item).map(item => NetUtil.newURI(item.uri)); - yield PlacesTransactions.Tag({ uris, tag: ip.tagName }).transact(); + yield PlacesTransactions.Tag({ uris: uris, tag: ip.tagName }).transact(); } else { yield PlacesTransactions.batch(function* () { @@ -1548,7 +1548,7 @@ var PlacesControllerDragHelper = { * A node unwrapped by PlacesUtils.unwrapNodes(). * @return True if the node can be moved, false otherwise. */ - canMoveUnwrappedNode(aUnwrappedNode) { + canMoveUnwrappedNode: function(aUnwrappedNode) { return aUnwrappedNode.id > 0 && !PlacesUtils.isRootItem(aUnwrappedNode.id) && (!aUnwrappedNode.parent || !PlacesUIUtils.isContentsReadOnly(aUnwrappedNode.parent)) && @@ -1637,7 +1637,7 @@ var PlacesControllerDragHelper = { let uri = NetUtil.newURI(unwrapped.uri); let tagItemId = insertionPoint.itemId; if (PlacesUIUtils.useAsyncTransactions) - transactions.push(PlacesTransactions.Tag({ uri, tag: tagName })); + transactions.push(PlacesTransactions.Tag({ uri: uri, tag: tagName })); else transactions.push(new PlacesTagURITransaction(uri, [tagItemId])); } @@ -1679,7 +1679,7 @@ var PlacesControllerDragHelper = { * @param aContainer * The container were we are want to drop */ - disallowInsertion(aContainer) { + disallowInsertion: function(aContainer) { NS_ASSERT(aContainer, "empty container"); // Allow dropping into Tag containers and editable folders. return !PlacesUtils.nodeIsTagQuery(aContainer) && diff --git a/browser/components/places/content/editBookmarkOverlay.js b/browser/components/places/content/editBookmarkOverlay.js index 8df6511d9a73..f08b6b36c91d 100644 --- a/browser/components/places/content/editBookmarkOverlay.js +++ b/browser/components/places/content/editBookmarkOverlay.js @@ -393,7 +393,7 @@ var gEditItemOverlay = { this._recentFolders = []; for (let i = 0; i < folderIds.length; i++) { var lastUsed = annos.getItemAnnotation(folderIds[i], LAST_USED_ANNO); - this._recentFolders.push({ folderId: folderIds[i], lastUsed }); + this._recentFolders.push({ folderId: folderIds[i], lastUsed: lastUsed }); } this._recentFolders.sort(function(a, b) { if (b.lastUsed < a.lastUsed) diff --git a/browser/components/places/content/moveBookmarks.js b/browser/components/places/content/moveBookmarks.js index 5f4bf0cfc050..626b2b904e40 100644 --- a/browser/components/places/content/moveBookmarks.js +++ b/browser/components/places/content/moveBookmarks.js @@ -14,7 +14,7 @@ var gMoveBookmarksDialog = { return this._foldersTree; }, - init() { + init: function() { this._nodes = window.arguments[0]; this.foldersTree.place = diff --git a/browser/components/places/content/places.js b/browser/components/places/content/places.js index 50ebfaf839fa..7a141354d172 100644 --- a/browser/components/places/content/places.js +++ b/browser/components/places/content/places.js @@ -32,7 +32,7 @@ var PlacesOrganizer = { "editBMPanel_keywordRow", ], - _initFolderTree() { + _initFolderTree: function() { var leftPaneRoot = PlacesUIUtils.leftPaneFolderId; this._places.place = "place:excludeItems=1&expandQueries=0&folder=" + leftPaneRoot; }, @@ -1250,7 +1250,7 @@ var ContentArea = { let { view, options } = this._specialViews.get(aQueryString); if (typeof view == "function") { view = view(); - this._specialViews.set(aQueryString, { view, options }); + this._specialViews.set(aQueryString, { view: view, options: options }); } return view; } @@ -1356,7 +1356,7 @@ var ContentArea = { return viewOptions; }, - focus() { + focus: function() { this._deck.selectedPanel.focus(); } }; diff --git a/browser/components/places/content/treeView.js b/browser/components/places/content/treeView.js index 81180a7d0b01..ece93fd4ff99 100644 --- a/browser/components/places/content/treeView.js +++ b/browser/components/places/content/treeView.js @@ -1135,7 +1135,7 @@ PlacesTreeView.prototype = { this._selection = val; }, - getRowProperties() { return ""; }, + getRowProperties: function() { return ""; }, getCellProperties: function PTV_getCellProperties(aRow, aColumn) { @@ -1217,7 +1217,7 @@ PlacesTreeView.prototype = { return props + " " + properties; }, - getColumnProperties(aColumn) { return ""; }, + getColumnProperties: function(aColumn) { return ""; }, isContainer: function PTV_isContainer(aRow) { // Only leaf nodes aren't listed in the rows array. @@ -1414,7 +1414,7 @@ PlacesTreeView.prototype = { return false; }, - getLevel(aRow) { + getLevel: function(aRow) { return this._getNodeForRow(aRow).indentLevel; }, @@ -1427,8 +1427,8 @@ PlacesTreeView.prototype = { return node.icon; }, - getProgressMode(aRow, aColumn) { }, - getCellValue(aRow, aColumn) { }, + getProgressMode: function(aRow, aColumn) { }, + getCellValue: function(aRow, aColumn) { }, getCellText: function PTV_getCellText(aRow, aColumn) { let node = this._getNodeForRow(aRow); @@ -1717,10 +1717,10 @@ PlacesTreeView.prototype = { } }, - selectionChanged() { }, - cycleCell(aRow, aColumn) { }, - isSelectable(aRow, aColumn) { return false; }, - performAction(aAction) { }, - performActionOnRow(aAction, aRow) { }, - performActionOnCell(aAction, aRow, aColumn) { } + selectionChanged: function() { }, + cycleCell: function(aRow, aColumn) { }, + isSelectable: function(aRow, aColumn) { return false; }, + performAction: function(aAction) { }, + performActionOnRow: function(aAction, aRow) { }, + performActionOnCell: function(aAction, aRow, aColumn) { } }; diff --git a/browser/components/places/tests/browser/browser_423515.js b/browser/components/places/tests/browser/browser_423515.js index 2eb129cb7783..8a67f050cdd5 100644 --- a/browser/components/places/tests/browser/browser_423515.js +++ b/browser/components/places/tests/browser/browser_423515.js @@ -20,11 +20,11 @@ function test() { // add a regular folder, should be moveable tests.push({ - populate() { + populate: function() { this.id = PlacesUtils.bookmarks.createFolder(rootId, "", IDX); }, - validate() { + validate: function() { is(rootNode.childCount, 1, "populate added data to the test root"); is(PlacesControllerDragHelper.canMoveNode(rootNode.getChild(0)), @@ -34,13 +34,13 @@ function test() { // add a regular folder shortcut, should be moveable tests.push({ - populate() { + populate: function() { this.folderId = PlacesUtils.bookmarks.createFolder(rootId, "foo", IDX); this.shortcutId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder=" + this.folderId), IDX, "bar"); }, - validate() { + validate: function() { is(rootNode.childCount, 2, "populated data to the test root"); @@ -62,13 +62,13 @@ function test() { // add a regular query, should be moveable tests.push({ - populate() { + populate: function() { this.bookmarkId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("http://foo.com"), IDX, "foo"); this.queryId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:terms=foo"), IDX, "bar"); }, - validate() { + validate: function() { is(rootNode.childCount, 2, "populated data to the test root"); @@ -90,14 +90,14 @@ function test() { PlacesUtils.tagsFolderId, PlacesUtils.unfiledBookmarksFolderId, PlacesUtils.toolbarFolderId], shortcuts: {}, - populate() { + populate: function() { for (var i = 0; i < this.folders.length; i++) { var id = this.folders[i]; this.shortcuts[id] = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder=" + id), IDX, ""); } }, - validate() { + validate: function() { // test toolbar shortcut node is(rootNode.childCount, this.folders.length, "populated data to the test root"); @@ -138,13 +138,13 @@ function test() { // test that a tag container cannot be moved tests.push({ - populate() { + populate: function() { // tag a uri this.uri = makeURI("http://foo.com"); PlacesUtils.tagging.tagURI(this.uri, ["bar"]); registerCleanupFunction(() => PlacesUtils.tagging.untagURI(this.uri, ["bar"])); }, - validate() { + validate: function() { // get tag root var query = PlacesUtils.history.getNewQuery(); var options = PlacesUtils.history.getNewQueryOptions(); diff --git a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js index aaece0b9f5ed..78d667e5f169 100644 --- a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js +++ b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js @@ -6,9 +6,9 @@ function makeBookmarkFor(url, keyword) { return Promise.all([ PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid, title: "bookmarklet", - url }), - PlacesUtils.keywords.insert({url, - keyword}) + url: url }), + PlacesUtils.keywords.insert({url: url, + keyword: keyword}) ]); } diff --git a/browser/components/places/tests/browser/browser_bookmarksProperties.js b/browser/components/places/tests/browser/browser_bookmarksProperties.js index 63d1c4f874e0..7f7d635afe01 100644 --- a/browser/components/places/tests/browser/browser_bookmarksProperties.js +++ b/browser/components/places/tests/browser/browser_bookmarksProperties.js @@ -63,7 +63,7 @@ gTests.push({ _itemId: null, _cleanShutdown: false, - setup(aCallback) { + setup: function(aCallback) { // Add a bookmark in unsorted bookmarks folder. this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL)); ok(this._itemId > 0, "Correctly added a bookmark"); @@ -75,14 +75,14 @@ gTests.push({ aCallback(); }, - selectNode(tree) { + selectNode: function(tree) { tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]); PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; tree.selectItems([this._itemId]); is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected"); }, - run() { + run: function() { // open tags autocomplete and press enter var tagsField = this.window.document.getElementById("editBMPanel_tagsField"); var self = this; @@ -97,7 +97,7 @@ gTests.push({ }, true); var popupListener = { - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "popuphidden": // Everything worked fine, we can stop observing the window. @@ -137,12 +137,12 @@ gTests.push({ }); }, - finish() { + finish: function() { SidebarUI.hide(); runNextTest(); }, - cleanup() { + cleanup: function() { // Check tags have not changed. var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); is(tags[0], "testTag", "Tag on node has not changed"); @@ -165,7 +165,7 @@ gTests.push({ _itemId: null, _cleanShutdown: false, - setup(aCallback) { + setup: function(aCallback) { // Add a bookmark in unsorted bookmarks folder. this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL)); ok(this._itemId > 0, "Correctly added a bookmark"); @@ -177,14 +177,14 @@ gTests.push({ aCallback(); }, - selectNode(tree) { + selectNode: function(tree) { tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]); PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; tree.selectItems([this._itemId]); is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected"); }, - run() { + run: function() { // open tags autocomplete and press enter var tagsField = this.window.document.getElementById("editBMPanel_tagsField"); var self = this; @@ -199,7 +199,7 @@ gTests.push({ }, true); var popupListener = { - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "popuphidden": // Everything worked fine. @@ -237,12 +237,12 @@ gTests.push({ EventUtils.synthesizeKey("t", {}, this.window); }, - finish() { + finish: function() { SidebarUI.hide(); runNextTest(); }, - cleanup() { + cleanup: function() { // Check tags have not changed. var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); is(tags[0], "testTag", "Tag on node has not changed"); @@ -264,7 +264,7 @@ gTests.push({ historyView: SIDEBAR_HISTORY_BYLASTVISITED_VIEW, window: null, - setup(aCallback) { + setup: function(aCallback) { // Add a visit. PlacesTestUtils.addVisits( {uri: PlacesUtils._uri(TEST_URL), @@ -272,14 +272,14 @@ gTests.push({ ).then(aCallback); }, - selectNode(tree) { + selectNode: function(tree) { var visitNode = tree.view.nodeForTreeIndex(0); tree.selectNode(visitNode); is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected"); is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked"); }, - run() { + run: function() { // Open folder selector. var foldersExpander = this.window.document.getElementById("editBMPanel_foldersExpander"); var folderTree = this.window.document.getElementById("editBMPanel_folderTree"); @@ -315,12 +315,12 @@ gTests.push({ foldersExpander.doCommand(); }, - finish() { + finish: function() { SidebarUI.hide(); runNextTest(); }, - cleanup() { + cleanup: function() { return PlacesTestUtils.clearHistory(); } }); diff --git a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js b/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js index 95aa6f620946..fbc0b02b6387 100644 --- a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js +++ b/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js @@ -144,7 +144,7 @@ var gTests = [ { desc: "Drag a folder on toolbar", - run() { + run: function() { // Create a test folder to be dragged. var folderId = PlacesUtils.bookmarks .createFolder(PlacesUtils.toolbarFolderId, @@ -185,7 +185,7 @@ var gTests = [ { desc: "Drag a bookmark on toolbar", - run() { + run: function() { // Create a test bookmark to be dragged. var itemId = PlacesUtils.bookmarks .insertBookmark(PlacesUtils.toolbarFolderId, diff --git a/browser/components/places/tests/browser/browser_library_batch_delete.js b/browser/components/places/tests/browser/browser_library_batch_delete.js index 37f843b6a21b..531ad9139b48 100644 --- a/browser/components/places/tests/browser/browser_library_batch_delete.js +++ b/browser/components/places/tests/browser/browser_library_batch_delete.js @@ -14,10 +14,10 @@ var gLibrary; gTests.push({ desc: "Create and batch remove bookmarks", - run() { + run: function() { let testURI = makeURI(TEST_URL); PlacesUtils.history.runInBatchMode({ - runBatched(aUserData) { + runBatched: function(aUserData) { // Create a folder in unserted and populate it with bookmarks. let folder = PlacesUtils.bookmarks.createFolder( PlacesUtils.unfiledBookmarksFolderId, "deleteme", @@ -67,7 +67,7 @@ gTests.push({ gTests.push({ desc: "Ensure correct selection and functionality in Library", - run() { + run: function() { let PO = gLibrary.PlacesOrganizer; let ContentTree = gLibrary.ContentTree; // Move selection forth and back. diff --git a/browser/components/places/tests/browser/browser_library_downloads.js b/browser/components/places/tests/browser/browser_library_downloads.js index 3578b8f2b7cf..77005b6fc6b2 100644 --- a/browser/components/places/tests/browser/browser_library_downloads.js +++ b/browser/components/places/tests/browser/browser_library_downloads.js @@ -32,11 +32,11 @@ function test() { }, ] PlacesUtils.asyncHistory.updatePlaces(places, { - handleResult() {}, - handleError() { + handleResult: function() {}, + handleError: function() { ok(false, "gHistory.updatePlaces() failed"); }, - handleCompletion() { + handleCompletion: function() { // Make sure Downloads is present. isnot(win.PlacesOrganizer._places.selectedNode, null, "Downloads is present and selected"); diff --git a/browser/components/places/tests/browser/browser_library_infoBox.js b/browser/components/places/tests/browser/browser_library_infoBox.js index 644e216cdc7c..8189438f3c2e 100644 --- a/browser/components/places/tests/browser/browser_library_infoBox.js +++ b/browser/components/places/tests/browser/browser_library_infoBox.js @@ -16,7 +16,7 @@ var gLibrary; gTests.push({ desc: "Bug 430148 - Remove or hide the more/less button in details pane...", - run() { + run: function() { var PO = gLibrary.PlacesOrganizer; let ContentTree = gLibrary.ContentTree; var infoBoxExpanderWrapper = getAndCheckElmtById("infoBoxExpanderWrapper"); diff --git a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js b/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js index 2c739c04fc34..7cea38f20ce8 100644 --- a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js +++ b/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js @@ -64,7 +64,7 @@ function test() { .getItemAnnotation(items[i], PlacesUIUtils.ORGANIZER_QUERY_ANNO); var query = { name: queryName, - itemId, + itemId: itemId, correctTitle: PlacesUtils.bookmarks.getItemTitle(itemId) } switch (queryName) { case "BookmarksToolbar": diff --git a/browser/components/places/tests/browser/browser_library_middleclick.js b/browser/components/places/tests/browser/browser_library_middleclick.js index bc1605ce5d84..0bde80bc0165 100644 --- a/browser/components/places/tests/browser/browser_library_middleclick.js +++ b/browser/components/places/tests/browser/browser_library_middleclick.js @@ -18,7 +18,7 @@ var gTabsListener = { _loadedURIs: [], _openTabsCount: 0, - handleEvent(aEvent) { + handleEvent: function(aEvent) { if (aEvent.type != "TabOpen") return; @@ -32,7 +32,7 @@ var gTabsListener = { "Tab has been opened in current browser window"); }, - onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, + onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) { var spec = aLocationURI.spec; ok(true, spec); @@ -76,7 +76,7 @@ gTests.push({ URIs: ["about:buildconfig"], _itemId: -1, - setup() { + setup: function() { var bs = PlacesUtils.bookmarks; // Add a new unsorted bookmark. this._itemId = bs.insertBookmark(bs.unfiledBookmarksFolder, @@ -92,11 +92,11 @@ gTests.push({ is(bookmarkNode.uri, this.URIs[0], "Found bookmark in the right pane"); }, - finish() { + finish: function() { setTimeout(runNextTest, 0); }, - cleanup() { + cleanup: function() { PlacesUtils.bookmarks.removeItem(this._itemId); } }); @@ -109,7 +109,7 @@ gTests.push({ URIs: ["about:buildconfig", "about:"], _folderId: -1, - setup() { + setup: function() { var bs = PlacesUtils.bookmarks; // Create a new folder. var folderId = bs.createFolder(bs.unfiledBookmarksFolder, @@ -134,11 +134,11 @@ gTests.push({ is(folderNode.title, "Folder", "Found folder in the right pane"); }, - finish() { + finish: function() { setTimeout(runNextTest, 0); }, - cleanup() { + cleanup: function() { PlacesUtils.bookmarks.removeItem(this._folderId); } }); @@ -152,7 +152,7 @@ gTests.push({ _folderId: -1, _queryId: -1, - setup() { + setup: function() { var bs = PlacesUtils.bookmarks; // Create a new folder. var folderId = bs.createFolder(bs.unfiledBookmarksFolder, @@ -191,11 +191,11 @@ gTests.push({ is(folderNode.title, "Query", "Found query in the right pane"); }, - finish() { + finish: function() { setTimeout(runNextTest, 0); }, - cleanup() { + cleanup: function() { PlacesUtils.bookmarks.removeItem(this._folderId); PlacesUtils.bookmarks.removeItem(this._queryId); } diff --git a/browser/components/places/tests/browser/browser_library_views_liveupdate.js b/browser/components/places/tests/browser/browser_library_views_liveupdate.js index d84c587bb83d..a70e4ef45806 100644 --- a/browser/components/places/tests/browser/browser_library_views_liveupdate.js +++ b/browser/components/places/tests/browser/browser_library_views_liveupdate.js @@ -154,10 +154,10 @@ var bookmarksObserver = { ]), // nsIAnnotationObserver - onItemAnnotationSet() {}, - onItemAnnotationRemoved() {}, - onPageAnnotationSet() {}, - onPageAnnotationRemoved() {}, + onItemAnnotationSet: function() {}, + onItemAnnotationRemoved: function() {}, + onPageAnnotationSet: function() {}, + onPageAnnotationRemoved: function() {}, // nsINavBookmarkObserver onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, aItemType, @@ -191,7 +191,7 @@ var bookmarksObserver = { is(node, null, "Places node not found in left pane"); }, - onItemMoved(aItemId, + onItemMoved: function(aItemId, aOldFolderId, aOldIndex, aNewFolderId, aNewIndex, aItemType) { var node = null; @@ -219,7 +219,7 @@ var bookmarksObserver = { onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {}, onEndUpdateBatch: function PSB_onEndUpdateBatch() {}, - onItemVisited() {}, + onItemVisited: function() {}, onItemChanged: function PSB_onItemChanged(aItemId, aProperty, aIsAnnotationProperty, aNewValue) { if (aProperty == "title") { diff --git a/browser/components/places/tests/browser/browser_sidebarpanels_click.js b/browser/components/places/tests/browser/browser_sidebarpanels_click.js index 48c7fd4e5ef9..b1db4e78a02f 100644 --- a/browser/components/places/tests/browser/browser_sidebarpanels_click.js +++ b/browser/components/places/tests/browser/browser_sidebarpanels_click.js @@ -27,7 +27,7 @@ function test() { tests.push({ _itemID: null, - init(aCallback) { + init: function(aCallback) { // Add a bookmark to the Unfiled Bookmarks folder. this._itemID = PlacesUtils.bookmarks.insertBookmark( PlacesUtils.unfiledBookmarksFolderId, PlacesUtils._uri(TEST_URL), @@ -35,12 +35,12 @@ function test() { ); aCallback(); }, - prepare() { + prepare: function() { }, - selectNode(tree) { + selectNode: function(tree) { tree.selectItems([this._itemID]); }, - cleanup(aCallback) { + cleanup: function(aCallback) { PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId); executeSoon(aCallback); }, @@ -50,23 +50,23 @@ function test() { }); tests.push({ - init(aCallback) { + init: function(aCallback) { // Add a history entry. let uri = PlacesUtils._uri(TEST_URL); PlacesTestUtils.addVisits({ - uri, visitDate: Date.now() * 1000, + uri: uri, visitDate: Date.now() * 1000, transition: PlacesUtils.history.TRANSITION_TYPED }).then(aCallback); }, - prepare() { + prepare: function() { sidebar.contentDocument.getElementById("byvisited").doCommand(); }, - selectNode(tree) { + selectNode: function(tree) { tree.selectNode(tree.view.nodeForTreeIndex(0)); is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected"); is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked"); }, - cleanup(aCallback) { + cleanup: function(aCallback) { PlacesTestUtils.clearHistory().then(aCallback); }, sidebarName: HISTORY_SIDEBAR_ID, diff --git a/browser/components/places/tests/browser/browser_views_liveupdate.js b/browser/components/places/tests/browser/browser_views_liveupdate.js index a3d8d2ecaba2..add7984a82d8 100644 --- a/browser/components/places/tests/browser/browser_views_liveupdate.js +++ b/browser/components/places/tests/browser/browser_views_liveupdate.js @@ -192,10 +192,10 @@ var bookmarksObserver = { ]), // nsIAnnotationObserver - onItemAnnotationSet() {}, - onItemAnnotationRemoved() {}, - onPageAnnotationSet() {}, - onPageAnnotationRemoved() {}, + onItemAnnotationSet: function() {}, + onItemAnnotationRemoved: function() {}, + onPageAnnotationSet: function() {}, + onPageAnnotationRemoved: function() {}, // nsINavBookmarkObserver onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, @@ -223,7 +223,7 @@ var bookmarksObserver = { } }, - onItemMoved(aItemId, + onItemMoved: function(aItemId, aOldFolderId, aOldIndex, aNewFolderId, aNewIndex, aItemType) { @@ -242,7 +242,7 @@ var bookmarksObserver = { onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {}, onEndUpdateBatch: function PSB_onEndUpdateBatch() {}, - onItemVisited() {}, + onItemVisited: function() {}, onItemChanged: function PSB_onItemChanged(aItemId, aProperty, aIsAnnotationProperty, aNewValue, diff --git a/browser/components/places/tests/browser/head.js b/browser/components/places/tests/browser/head.js index 1bfd71cb59c9..c6190db4c17c 100644 --- a/browser/components/places/tests/browser/head.js +++ b/browser/components/places/tests/browser/head.js @@ -116,9 +116,9 @@ function waitForAsyncUpdates(aCallback, aScope, aArguments) let commit = db.createAsyncStatement("COMMIT"); commit.executeAsync({ - handleResult() {}, - handleError() {}, - handleCompletion(aReason) + handleResult: function() {}, + handleError: function() {}, + handleCompletion: function(aReason) { aCallback.apply(scope, args); } diff --git a/browser/components/places/tests/unit/test_421483.js b/browser/components/places/tests/unit/test_421483.js index ac086a2e3362..a0d1383728e2 100644 --- a/browser/components/places/tests/unit/test_421483.js +++ b/browser/components/places/tests/unit/test_421483.js @@ -79,7 +79,7 @@ add_task(function* move_smart_bookmark_rename_and_restore() { // change title and move into new subfolder yield PlacesUtils.bookmarks.update({ - guid, + guid: guid, parentGuid: subfolder.guid, index: PlacesUtils.bookmarks.DEFAULT_INDEX, title: "new title" diff --git a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js b/browser/components/places/tests/unit/test_PUIU_makeTransaction.js index dcc3645b9119..da8191b0fc23 100644 --- a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js +++ b/browser/components/places/tests/unit/test_PUIU_makeTransaction.js @@ -4,7 +4,7 @@ function waitForBookmarkNotification(aNotification, aCallback, aProperty) { PlacesUtils.bookmarks.addObserver({ - validate(aMethodName, aData) + validate: function(aMethodName, aData) { if (aMethodName == aNotification && (!aProperty || aProperty == aData.property)) { diff --git a/browser/components/places/tests/unit/test_clearHistory_shutdown.js b/browser/components/places/tests/unit/test_clearHistory_shutdown.js index c020bdbd99fb..4bf88b04aa8a 100644 --- a/browser/components/places/tests/unit/test_clearHistory_shutdown.js +++ b/browser/components/places/tests/unit/test_clearHistory_shutdown.js @@ -133,11 +133,11 @@ function storeCache(aURL, aContent) { return new Promise(resolve => { let storeCacheListener = { - onCacheEntryCheck(entry, appcache) { + onCacheEntryCheck: function(entry, appcache) { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable(entry, isnew, appcache, status) { + onCacheEntryAvailable: function(entry, isnew, appcache, status) { do_check_eq(status, Cr.NS_OK); entry.setMetaDataElement("servertype", "0"); @@ -168,7 +168,7 @@ function checkCache(aURL) { return new Promise(resolve => { let checkCacheListener = { - onCacheEntryAvailable(entry, isnew, appcache, status) { + onCacheEntryAvailable: function(entry, isnew, appcache, status) { do_check_eq(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND); resolve(); } diff --git a/browser/components/preferences/SiteDataManager.jsm b/browser/components/preferences/SiteDataManager.jsm index 6107f2361096..8d2be6cb1ed9 100644 --- a/browser/components/preferences/SiteDataManager.jsm +++ b/browser/components/preferences/SiteDataManager.jsm @@ -54,8 +54,8 @@ this.SiteDataManager = { if (status === Ci.nsIPermissionManager.ALLOW_ACTION || status === Ci.nsIPermissionManager.DENY_ACTION) { this._sites.set(perm.principal.origin, { - perm, - status, + perm: perm, + status: status, quotaUsage: 0, appCacheList: [], diskCacheList: [] @@ -79,7 +79,7 @@ this.SiteDataManager = { for (let site of this._sites.values()) { promises.push(new Promise(resolve => { let callback = { - onUsageResult(request) { + onUsageResult: function(request) { site.quotaUsage = request.usage; resolve(); } @@ -121,7 +121,7 @@ this.SiteDataManager = { if (this._sites.size) { let sites = this._sites; let visitor = { - onCacheEntryInfo(uri, idEnhance, dataSize) { + onCacheEntryInfo: function(uri, idEnhance, dataSize) { for (let site of sites.values()) { if (site.perm.matchesURI(uri, true)) { site.diskCacheList.push({ @@ -132,7 +132,7 @@ this.SiteDataManager = { } } }, - onCacheEntryVisitCompleted() { + onCacheEntryVisitCompleted: function() { resolve(); } }; diff --git a/browser/components/preferences/blocklists.js b/browser/components/preferences/blocklists.js index 70ea7f1c43ba..208a329d5f82 100644 --- a/browser/components/preferences/blocklists.js +++ b/browser/components/preferences/blocklists.js @@ -22,7 +22,7 @@ var gBlocklistManager = { get rowCount() { return this._rowCount; }, - getCellText(row, column) { + getCellText: function(row, column) { if (column.id == "listCol") { let list = gBlocklistManager._blockLists[row]; let desc = list.description ? list.description : ""; @@ -33,21 +33,21 @@ var gBlocklistManager = { return ""; }, - isSeparator(index) { return false; }, - isSorted() { return false; }, - isContainer(index) { return false; }, - setTree(tree) {}, - getImageSrc(row, column) {}, - getProgressMode(row, column) {}, - getCellValue(row, column) { + isSeparator: function(index) { return false; }, + isSorted: function() { return false; }, + isContainer: function(index) { return false; }, + setTree: function(tree) {}, + getImageSrc: function(row, column) {}, + getProgressMode: function(row, column) {}, + getCellValue: function(row, column) { if (column.id == "selectionCol") return gBlocklistManager._blockLists[row].selected; return undefined; }, - cycleHeader(column) {}, - getRowProperties(row) { return ""; }, - getColumnProperties(column) { return ""; }, - getCellProperties(row, column) { + cycleHeader: function(column) {}, + getRowProperties: function(row) { return ""; }, + getColumnProperties: function(column) { return ""; }, + getCellProperties: function(row, column) { if (column.id == "selectionCol") { return "checkmark"; } @@ -56,7 +56,7 @@ var gBlocklistManager = { } }, - onWindowKeyPress(event) { + onWindowKeyPress: function(event) { if (event.keyCode == KeyEvent.DOM_VK_ESCAPE) { window.close(); } else if (event.keyCode == KeyEvent.DOM_VK_RETURN) { @@ -64,13 +64,13 @@ var gBlocklistManager = { } }, - onLoad() { + onLoad: function() { this._bundle = document.getElementById("bundlePreferences"); let params = window.arguments[0]; this.init(params); }, - init(params) { + init: function(params) { if (this._type) { // reusing an open dialog, clear the old observer this.uninit(); @@ -97,9 +97,9 @@ var gBlocklistManager = { this._loadBlockLists(); }, - uninit() {}, + uninit: function() {}, - onListSelected() { + onListSelected: function() { for (let list of this._blockLists) { list.selected = false; } @@ -108,7 +108,7 @@ var gBlocklistManager = { this._updateTree(); }, - onApplyChanges() { + onApplyChanges: function() { let activeList = this._getActiveList(); let selected = null; for (let list of this._blockLists) { @@ -153,7 +153,7 @@ var gBlocklistManager = { window.close(); }, - _loadBlockLists() { + _loadBlockLists: function() { this._blockLists = []; // Load blocklists into a table. @@ -171,7 +171,7 @@ var gBlocklistManager = { this._updateTree(); }, - _createOrUpdateBlockList(itemName) { + _createOrUpdateBlockList: function(itemName) { let branch = Services.prefs.getBranch(LISTS_PREF_BRANCH); let key = branch.getCharPref(itemName); let value = this._bundle.getString(key); @@ -192,13 +192,13 @@ var gBlocklistManager = { return list; }, - _updateTree() { + _updateTree: function() { this._tree = document.getElementById("blocklistsTree"); this._view._rowCount = this._blockLists.length; this._tree.view = this._view; }, - _getActiveList() { + _getActiveList: function() { let trackingTable = Services.prefs.getCharPref(TRACKING_TABLE_PREF); return trackingTable.includes(CONTENT_LIST_ID) ? CONTENT_LIST_ID : BASE_LIST_ID; } diff --git a/browser/components/preferences/connection.js b/browser/components/preferences/connection.js index 128c9caa8549..9997a1a7490c 100644 --- a/browser/components/preferences/connection.js +++ b/browser/components/preferences/connection.js @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gConnectionsDialog = { - beforeAccept() + beforeAccept: function() { var proxyTypePref = document.getElementById("network.proxy.type"); if (proxyTypePref.value == 2) { @@ -52,13 +52,13 @@ var gConnectionsDialog = { return true; }, - checkForSystemProxy() + checkForSystemProxy: function() { if ("@mozilla.org/system-proxy-settings;1" in Components.classes) document.getElementById("systemPref").removeAttribute("hidden"); }, - proxyTypeChanged() + proxyTypeChanged: function() { var proxyTypePref = document.getElementById("network.proxy.type"); @@ -84,7 +84,7 @@ var gConnectionsDialog = { this.updateReloadButton(); }, - updateDNSPref() + updateDNSPref: function() { var socksVersionPref = document.getElementById("network.proxy.socks_version"); var socksDNSPref = document.getElementById("network.proxy.socks_remote_dns"); @@ -94,7 +94,7 @@ var gConnectionsDialog = { return undefined; }, - updateReloadButton() + updateReloadButton: function() { // Disable the "Reload PAC" button if the selected proxy type is not PAC or // if the current value of the PAC textbox does not match the value stored @@ -116,13 +116,13 @@ var gConnectionsDialog = { (proxyTypeCur != 2 || proxyType != 2 || typedURL != pacURL); }, - readProxyType() + readProxyType: function() { this.proxyTypeChanged(); return undefined; }, - updateProtocolPrefs() + updateProtocolPrefs: function() { var proxyTypePref = document.getElementById("network.proxy.type"); var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); @@ -156,7 +156,7 @@ var gConnectionsDialog = { return undefined; }, - readProxyProtocolPref(aProtocol, aIsPort) + readProxyProtocolPref: function(aProtocol, aIsPort) { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) { @@ -168,13 +168,13 @@ var gConnectionsDialog = { return backupPref.hasUserValue ? backupPref.value : undefined; }, - reloadPAC() + reloadPAC: function() { Components.classes["@mozilla.org/network/protocol-proxy-service;1"]. getService().reloadPAC(); }, - doAutoconfigURLFixup() + doAutoconfigURLFixup: function() { var autoURL = document.getElementById("networkProxyAutoconfigURL"); var autoURLPref = document.getElementById("network.proxy.autoconfig_url"); @@ -185,7 +185,7 @@ var gConnectionsDialog = { } catch (ex) {} }, - sanitizeNoProxiesPref() + sanitizeNoProxiesPref: function() { var noProxiesPref = document.getElementById("network.proxy.no_proxies_on"); // replace substrings of ; and \n with commas if they're neither immediately @@ -195,7 +195,7 @@ var gConnectionsDialog = { noProxiesPref.value = noProxiesPref.value.replace(/[;\n]/g, ''); }, - readHTTPProxyServer() + readHTTPProxyServer: function() { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) @@ -203,7 +203,7 @@ var gConnectionsDialog = { return undefined; }, - readHTTPProxyPort() + readHTTPProxyPort: function() { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) diff --git a/browser/components/preferences/cookies.js b/browser/components/preferences/cookies.js index 55b8e6cbb26b..82abbebb00ef 100644 --- a/browser/components/preferences/cookies.js +++ b/browser/components/preferences/cookies.js @@ -21,7 +21,7 @@ var gCookiesWindow = { _tree : null, _bundle : null, - init() { + init: function() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); os.addObserver(this, "cookie-changed", false); @@ -39,14 +39,14 @@ var gCookiesWindow = { } }, - uninit() { + uninit: function() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); os.removeObserver(this, "cookie-changed"); os.removeObserver(this, "perm-changed"); }, - _populateList(aInitialLoad) { + _populateList: function(aInitialLoad) { this._loadCookies(); this._tree.view = this._view; if (aInitialLoad) @@ -69,7 +69,7 @@ var gCookiesWindow = { this._saveState(); }, - _cookieEquals(aCookieA, aCookieB, aStrippedHost) { + _cookieEquals: function(aCookieA, aCookieB, aStrippedHost) { return aCookieA.rawHost == aStrippedHost && aCookieA.name == aCookieB.name && aCookieA.path == aCookieB.path && @@ -77,7 +77,7 @@ var gCookiesWindow = { aCookieB.originAttributes); }, - _isPrivateCookie(aCookie) { + _isPrivateCookie: function(aCookie) { let { userContextId } = aCookie.originAttributes; if (!userContextId) { // Default identity is public. @@ -86,7 +86,7 @@ var gCookiesWindow = { return !ContextualIdentityService.getIdentityFromId(userContextId).public; }, - observe(aCookie, aTopic, aData) { + observe: function(aCookie, aTopic, aData) { if (aTopic != "cookie-changed") return; @@ -123,7 +123,7 @@ var gCookiesWindow = { // and is rather complicated as selection tracking is difficult }, - _handleCookieChanged(changedCookie, strippedHost) { + _handleCookieChanged: function(changedCookie, strippedHost) { var rowIndex = 0; var cookieItem = null; if (!this._view._filtered) { @@ -172,7 +172,7 @@ var gCookiesWindow = { this._updateCookieData(cookieItem); }, - _handleCookieAdded(changedCookie, strippedHost) { + _handleCookieAdded: function(changedCookie, strippedHost) { var rowCountImpact = 0; var addedHost = { value: 0 }; this._addCookie(strippedHost, changedCookie, addedHost); @@ -212,7 +212,7 @@ var gCookiesWindow = { return this._rowCount; }, - _getItemAtIndex(aIndex) { + _getItemAtIndex: function(aIndex) { if (this._filtered) return this._filterSet[aIndex]; @@ -267,7 +267,7 @@ var gCookiesWindow = { return null; }, - _removeItemAtIndex(aIndex, aCount) { + _removeItemAtIndex: function(aIndex, aCount) { let removeCount = aCount === undefined ? 1 : aCount; if (this._filtered) { // remove the cookies from the unfiltered set so that they @@ -306,11 +306,11 @@ var gCookiesWindow = { } }, - _invalidateCache(aIndex) { + _invalidateCache: function(aIndex) { this._cacheValid = Math.min(this._cacheValid, aIndex); }, - getCellText(aIndex, aColumn) { + getCellText: function(aIndex, aColumn) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) @@ -331,10 +331,10 @@ var gCookiesWindow = { _selection: null, get selection() { return this._selection; }, set selection(val) { this._selection = val; return val; }, - getRowProperties(aIndex) { return ""; }, - getCellProperties(aIndex, aColumn) { return ""; }, - getColumnProperties(aColumn) { return ""; }, - isContainer(aIndex) { + getRowProperties: function(aIndex) { return ""; }, + getCellProperties: function(aIndex, aColumn) { return ""; }, + getColumnProperties: function(aColumn) { return ""; }, + isContainer: function(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -342,7 +342,7 @@ var gCookiesWindow = { } return false; }, - isContainerOpen(aIndex) { + isContainerOpen: function(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -350,7 +350,7 @@ var gCookiesWindow = { } return false; }, - isContainerEmpty(aIndex) { + isContainerEmpty: function(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -358,11 +358,11 @@ var gCookiesWindow = { } return false; }, - isSeparator(aIndex) { return false; }, - isSorted(aIndex) { return false; }, - canDrop(aIndex, aOrientation) { return false; }, - drop(aIndex, aOrientation) {}, - getParentIndex(aIndex) { + isSeparator: function(aIndex) { return false; }, + isSorted: function(aIndex) { return false; }, + canDrop: function(aIndex, aOrientation) { return false; }, + drop: function(aIndex, aOrientation) {}, + getParentIndex: function(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); // If an item has no parent index (i.e. it is at the top level) this @@ -374,7 +374,7 @@ var gCookiesWindow = { } return -1; }, - hasNextSibling(aParentIndex, aIndex) { + hasNextSibling: function(aParentIndex, aIndex) { if (!this._filtered) { // |aParentIndex| appears to be bogus, but we can get the real // parent index by getting the entry for |aIndex| and reading the @@ -399,7 +399,7 @@ var gCookiesWindow = { } return aIndex < this.rowCount - 1; }, - hasPreviousSibling(aIndex) { + hasPreviousSibling: function(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -409,7 +409,7 @@ var gCookiesWindow = { } return aIndex > 0; }, - getLevel(aIndex) { + getLevel: function(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return 0; @@ -417,11 +417,11 @@ var gCookiesWindow = { } return 0; }, - getImageSrc(aIndex, aColumn) {}, - getProgressMode(aIndex, aColumn) {}, - getCellValue(aIndex, aColumn) {}, - setTree(aTree) {}, - toggleOpenState(aIndex) { + getImageSrc: function(aIndex, aColumn) {}, + getProgressMode: function(aIndex, aColumn) {}, + getCellValue: function(aIndex, aColumn) {}, + setTree: function(aTree) {}, + toggleOpenState: function(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return; @@ -434,28 +434,28 @@ var gCookiesWindow = { gCookiesWindow._tree.treeBoxObject.invalidateRow(aIndex); } }, - cycleHeader(aColumn) {}, - selectionChanged() {}, - cycleCell(aIndex, aColumn) {}, - isEditable(aIndex, aColumn) { + cycleHeader: function(aColumn) {}, + selectionChanged: function() {}, + cycleCell: function(aIndex, aColumn) {}, + isEditable: function(aIndex, aColumn) { return false; }, - isSelectable(aIndex, aColumn) { + isSelectable: function(aIndex, aColumn) { return false; }, - setCellValue(aIndex, aColumn, aValue) {}, - setCellText(aIndex, aColumn, aValue) {}, - performAction(aAction) {}, - performActionOnRow(aAction, aIndex) {}, - performActionOnCell(aAction, aindex, aColumn) {} + setCellValue: function(aIndex, aColumn, aValue) {}, + setCellText: function(aIndex, aColumn, aValue) {}, + performAction: function(aAction) {}, + performActionOnRow: function(aAction, aIndex) {}, + performActionOnCell: function(aAction, aindex, aColumn) {} }, - _makeStrippedHost(aHost) { + _makeStrippedHost: function(aHost) { var formattedHost = aHost.charAt(0) == "." ? aHost.substring(1, aHost.length) : aHost; return formattedHost.substring(0, 4) == "www." ? formattedHost.substring(4, formattedHost.length) : formattedHost; }, - _addCookie(aStrippedHost, aCookie, aHostCount) { + _addCookie: function(aStrippedHost, aCookie, aHostCount) { if (!(aStrippedHost in this._hosts) || !this._hosts[aStrippedHost]) { this._hosts[aStrippedHost] = { cookies : [], rawHost : aStrippedHost, @@ -470,7 +470,7 @@ var gCookiesWindow = { this._hosts[aStrippedHost].cookies.push(c); }, - _makeCookieObject(aStrippedHost, aCookie) { + _makeCookieObject: function(aStrippedHost, aCookie) { var c = { name : aCookie.name, value : aCookie.value, isDomain : aCookie.isDomain, @@ -485,7 +485,7 @@ var gCookiesWindow = { return c; }, - _loadCookies() { + _loadCookies: function() { var e = this._cm.enumerator; var hostCount = { value: 0 }; this._hosts = {}; @@ -506,7 +506,7 @@ var gCookiesWindow = { this._view._rowCount = hostCount.value; }, - formatExpiresString(aExpires) { + formatExpiresString: function(aExpires) { if (aExpires) { var date = new Date(1000 * aExpires); const locale = Components.classes["@mozilla.org/chrome/chrome-registry;1"] @@ -519,7 +519,7 @@ var gCookiesWindow = { return this._bundle.getString("expireAtEndOfSession"); }, - _getUserContextString(aUserContextId) { + _getUserContextString: function(aUserContextId) { if (parseInt(aUserContextId) == 0) { return this._bundle.getString("defaultUserContextLabel"); } @@ -527,7 +527,7 @@ var gCookiesWindow = { return ContextualIdentityService.getUserContextLabel(aUserContextId); }, - _updateCookieData(aItem) { + _updateCookieData: function(aItem) { var seln = this._view.selection; var ids = ["name", "value", "host", "path", "isSecure", "expires", "userContext"]; var properties; @@ -557,7 +557,7 @@ var gCookiesWindow = { document.getElementById(property).value = properties[property]; }, - onCookieSelected() { + onCookieSelected: function() { var item; var seln = this._tree.view.selection; if (!this._view._filtered) @@ -602,7 +602,7 @@ var gCookiesWindow = { } }, - deleteCookie() { + deleteCookie: function() { // Selection Notes // - Selection always moves to *NEXT* adjacent item unless item // is last child at a given level in which case it moves to *PREVIOUS* @@ -728,7 +728,7 @@ var gCookiesWindow = { } }, - deleteAllCookies() { + deleteAllCookies: function() { if (this._view._filtered) { var rowCount = this._view.rowCount; var deleteItems = []; @@ -747,7 +747,7 @@ var gCookiesWindow = { this.focusFilterBox(); }, - onCookieKeyPress(aEvent) { + onCookieKeyPress: function(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) { this.deleteCookie(); } else if (AppConstants.platform == "macosx" && @@ -758,7 +758,7 @@ var gCookiesWindow = { _lastSortProperty : "", _lastSortAscending: false, - sort(aProperty) { + sort: function(aProperty) { var ascending = (aProperty == this._lastSortProperty) ? !this._lastSortAscending : true; // Sort the Non-Filtered Host Collections if (aProperty == "rawHost") { @@ -809,7 +809,7 @@ var gCookiesWindow = { this._lastSortProperty = aProperty; }, - clearFilter() { + clearFilter: function() { // Revert to single-select in the tree this._tree.setAttribute("seltype", "single"); @@ -851,13 +851,13 @@ var gCookiesWindow = { this._updateRemoveAllButton(); }, - _cookieMatchesFilter(aCookie) { + _cookieMatchesFilter: function(aCookie) { return aCookie.rawHost.indexOf(this._view._filterValue) != -1 || aCookie.name.indexOf(this._view._filterValue) != -1 || aCookie.value.indexOf(this._view._filterValue) != -1; }, - _filterCookies(aFilterValue) { + _filterCookies: function(aFilterValue) { this._view._filterValue = aFilterValue; var cookies = []; for (let i = 0; i < gCookiesWindow._hostOrder.length; ++i) { // var host in gCookiesWindow._hosts) { @@ -873,7 +873,7 @@ var gCookiesWindow = { _lastSelectedRanges: [], _openIndices: [], - _saveState() { + _saveState: function() { // Save selection var seln = this._view.selection; this._lastSelectedRanges = []; @@ -897,7 +897,7 @@ var gCookiesWindow = { document.getElementById("removeAllCookies").disabled = this._view._rowCount == 0; }, - filter() { + filter: function() { var filter = document.getElementById("filter").value; if (filter == "") { gCookiesWindow.clearFilter(); @@ -930,18 +930,18 @@ var gCookiesWindow = { this._updateRemoveAllButton(); }, - setFilter(aFilterString) { + setFilter: function(aFilterString) { document.getElementById("filter").value = aFilterString; this.filter(); }, - focusFilterBox() { + focusFilterBox: function() { var filter = document.getElementById("filter"); filter.focus(); filter.select(); }, - onWindowKeyPress(aEvent) { + onWindowKeyPress: function(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); } diff --git a/browser/components/preferences/fonts.js b/browser/components/preferences/fonts.js index ac66044a2b80..e6b2a0acd73d 100644 --- a/browser/components/preferences/fonts.js +++ b/browser/components/preferences/fonts.js @@ -19,7 +19,7 @@ const kFontSizeFmtFixed = "font.size.fixed.%LANG%"; const kFontMinSizeFmt = "font.minimum-size.%LANG%"; var gFontsDialog = { - _selectLanguageGroup(aLanguageGroup) + _selectLanguageGroup: function(aLanguageGroup) { var prefs = [{ format: kDefaultFontType, type: "string", element: "defaultFontType", fonttype: null}, { format: kFontNameFmtSerif, type: "fontname", element: "serif", fonttype: "serif" }, @@ -58,26 +58,26 @@ var gFontsDialog = { } }, - readFontLanguageGroup() + readFontLanguageGroup: function() { var languagePref = document.getElementById("font.language.group"); this._selectLanguageGroup(languagePref.value); return undefined; }, - readUseDocumentFonts() + readUseDocumentFonts: function() { var preference = document.getElementById("browser.display.use_document_fonts"); return preference.value == 1; }, - writeUseDocumentFonts() + writeUseDocumentFonts: function() { var useDocumentFonts = document.getElementById("useDocumentFonts"); return useDocumentFonts.checked ? 1 : 0; }, - onBeforeAccept() + onBeforeAccept: function() { let preferences = document.querySelectorAll("preference[id*='font.minimum-size']"); // It would be good if we could avoid touching languages the pref pages won't use, but diff --git a/browser/components/preferences/in-content/advanced.js b/browser/components/preferences/in-content/advanced.js index 68cef05b8d60..992b805ce103 100644 --- a/browser/components/preferences/in-content/advanced.js +++ b/browser/components/preferences/in-content/advanced.js @@ -18,7 +18,7 @@ var gAdvancedPane = { /** * Brings the appropriate tab to the front and initializes various bits of UI. */ - init() + init: function() { function setEventListener(aId, aEventType, aCallback) { @@ -120,7 +120,7 @@ var gAdvancedPane = { * Stores the identity of the current tab in preferences so that the selected * tab can be persisted between openings of the preferences window. */ - tabSelectionChanged() + tabSelectionChanged: function() { if (!this._inited) return; @@ -182,7 +182,7 @@ var gAdvancedPane = { * the current value to enable proper pref restoration if the checkbox is * never changed. */ - readCheckSpelling() + readCheckSpelling: function() { var pref = document.getElementById("layout.spellcheckDefault"); this._storedSpellCheck = pref.value; @@ -195,7 +195,7 @@ var gAdvancedPane = { * preserving the preference's "hidden" value if the preference is * unchanged and represents a value not strictly allowed in UI. */ - writeCheckSpelling() + writeCheckSpelling: function() { var checkbox = document.getElementById("checkSpelling"); if (checkbox.checked) { @@ -211,7 +211,7 @@ var gAdvancedPane = { * security.OCSP.enabled is an integer value for legacy reasons. * A value of 1 means OCSP is enabled. Any other value means it is disabled. */ - readEnableOCSP() + readEnableOCSP: function() { var preference = document.getElementById("security.OCSP.enabled"); // This is the case if the preference is the default value. @@ -224,7 +224,7 @@ var gAdvancedPane = { /** * See documentation for readEnableOCSP. */ - writeEnableOCSP() + writeEnableOCSP: function() { var checkbox = document.getElementById("enableOCSP"); return checkbox.checked ? 1 : 0; @@ -234,7 +234,7 @@ var gAdvancedPane = { * When the user toggles the layers.acceleration.disabled pref, * sync its new value to the gfx.direct2d.disabled pref too. */ - updateHardwareAcceleration() + updateHardwareAcceleration: function() { if (AppConstants.platform = "win") { var fromPref = document.getElementById("layers.acceleration.disabled"); @@ -248,7 +248,7 @@ var gAdvancedPane = { /** * Set up or hide the Learn More links for various data collection options */ - _setupLearnMoreLink(pref, element) { + _setupLearnMoreLink: function(pref, element) { // set up the Learn More link with the correct URL let url = Services.prefs.getCharPref(pref); let el = document.getElementById(element); @@ -263,7 +263,7 @@ var gAdvancedPane = { /** * */ - initSubmitCrashes() + initSubmitCrashes: function() { this._setupLearnMoreLink("toolkit.crashreporter.infoURL", "crashReporterLearnMore"); @@ -274,7 +274,7 @@ var gAdvancedPane = { * * In all cases, set up the Learn More link sanely. */ - initTelemetry() + initTelemetry: function() { if (AppConstants.MOZ_TELEMETRY_REPORTING) { this._setupLearnMoreLink("toolkit.telemetry.infoURL", "telemetryLearnMore"); @@ -285,7 +285,7 @@ var gAdvancedPane = { * Set the status of the telemetry controls based on the input argument. * @param {Boolean} aEnabled False disables the controls, true enables them. */ - setTelemetrySectionEnabled(aEnabled) + setTelemetrySectionEnabled: function(aEnabled) { if (AppConstants.MOZ_TELEMETRY_REPORTING) { // If FHR is disabled, additional data sharing should be disabled as well. @@ -302,7 +302,7 @@ var gAdvancedPane = { /** * Initialize the health report service reference and checkbox. */ - initSubmitHealthReport() { + initSubmitHealthReport: function() { if (AppConstants.MOZ_TELEMETRY_REPORTING) { this._setupLearnMoreLink("datareporting.healthreport.infoURL", "FHRLearnMore"); @@ -321,7 +321,7 @@ var gAdvancedPane = { /** * Update the health report preference with state from checkbox. */ - updateSubmitHealthReport() { + updateSubmitHealthReport: function() { if (AppConstants.MOZ_TELEMETRY_REPORTING) { let checkbox = document.getElementById("submitHealthReportBox"); Services.prefs.setBoolPref(PREF_UPLOAD_ENABLED, checkbox.checked); @@ -351,16 +351,16 @@ var gAdvancedPane = { /** * Displays a dialog in which proxy settings may be changed. */ - showConnections() + showConnections: function() { gSubDialog.open("chrome://browser/content/preferences/connection.xul"); }, - showSiteDataSettings() { + showSiteDataSettings: function() { gSubDialog.open("chrome://browser/content/preferences/siteDataSettings.xul"); }, - updateTotalSiteDataSize() { + updateTotalSiteDataSize: function() { SiteDataManager.getTotalUsage() .then(usage => { let size = DownloadUtils.convertByteUnits(usage); @@ -373,14 +373,14 @@ var gAdvancedPane = { }, // Retrieves the amount of space currently used by disk cache - updateActualCacheSize() + updateActualCacheSize: function() { var actualSizeLabel = document.getElementById("actualDiskCacheSize"); var prefStrBundle = document.getElementById("bundlePreferences"); // Needs to root the observer since cache service keeps only a weak reference. this.observer = { - onNetworkCacheDiskConsumption(consumption) { + onNetworkCacheDiskConsumption: function(consumption) { var size = DownloadUtils.convertByteUnits(consumption); // The XBL binding for the string bundle may have been destroyed if // the page was closed before this callback was executed. @@ -407,10 +407,10 @@ var gAdvancedPane = { }, // Retrieves the amount of space currently used by offline cache - updateActualAppCacheSize() + updateActualAppCacheSize: function() { var visitor = { - onCacheStorageInfo(aEntryCount, aConsumption, aCapacity, aDiskDirectory) + onCacheStorageInfo: function(aEntryCount, aConsumption, aCapacity, aDiskDirectory) { var actualSizeLabel = document.getElementById("actualAppCacheSize"); var sizeStrings = DownloadUtils.convertByteUnits(aConsumption); @@ -434,14 +434,14 @@ var gAdvancedPane = { } catch (e) {} }, - updateCacheSizeUI(smartSizeEnabled) + updateCacheSizeUI: function(smartSizeEnabled) { document.getElementById("useCacheBefore").disabled = smartSizeEnabled; document.getElementById("cacheSize").disabled = smartSizeEnabled; document.getElementById("useCacheAfter").disabled = smartSizeEnabled; }, - readSmartSizeEnabled() + readSmartSizeEnabled: function() { // The smart_size.enabled preference element is inverted="true", so its // value is the opposite of the actual pref value @@ -480,7 +480,7 @@ var gAdvancedPane = { /** * Clears the cache. */ - clearCache() + clearCache: function() { try { var cache = Components.classes["@mozilla.org/netwerk/cache-storage-service;1"] @@ -493,7 +493,7 @@ var gAdvancedPane = { /** * Clears the application cache. */ - clearOfflineAppCache() + clearOfflineAppCache: function() { Components.utils.import("resource:///modules/offlineAppCache.jsm"); OfflineAppCacheHelper.clear(); @@ -502,7 +502,7 @@ var gAdvancedPane = { this.updateOfflineApps(); }, - clearSiteData() { + clearSiteData: function() { let flags = Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_0 + Services.prompt.BUTTON_TITLE_CANCEL * Services.prompt.BUTTON_POS_1 + @@ -519,7 +519,7 @@ var gAdvancedPane = { } }, - readOfflineNotify() + readOfflineNotify: function() { var pref = document.getElementById("browser.offline-apps.notify"); var button = document.getElementById("offlineNotifyExceptions"); @@ -527,7 +527,7 @@ var gAdvancedPane = { return pref.value; }, - showOfflineExceptions() + showOfflineExceptions: function() { var bundlePreferences = document.getElementById("bundlePreferences"); var params = { blockVisible : false, @@ -569,7 +569,7 @@ var gAdvancedPane = { /** * Updates the list of offline applications */ - updateOfflineApps() + updateOfflineApps: function() { var pm = Components.classes["@mozilla.org/permissionmanager;1"] .getService(Components.interfaces.nsIPermissionManager); @@ -610,7 +610,7 @@ var gAdvancedPane = { } }, - offlineAppSelected() + offlineAppSelected: function() { var removeButton = document.getElementById("offlineAppsListRemove"); var list = document.getElementById("offlineAppsList"); @@ -621,7 +621,7 @@ var gAdvancedPane = { } }, - removeOfflineApp() + removeOfflineApp: function() { var list = document.getElementById("offlineAppsList"); var item = list.selectedItem; @@ -702,7 +702,7 @@ var gAdvancedPane = { * ii t/f f false * ii t/f *t* *true* */ - updateReadPrefs() + updateReadPrefs: function() { if (AppConstants.MOZ_UPDATER) { var enabledPref = document.getElementById("app.update.enabled"); @@ -748,7 +748,7 @@ var gAdvancedPane = { /** * Sets the pref values based on the selected item of the radiogroup. */ - updateWritePrefs() + updateWritePrefs: function() { if (AppConstants.MOZ_UPDATER) { var enabledPref = document.getElementById("app.update.enabled"); @@ -773,7 +773,7 @@ var gAdvancedPane = { /** * Displays the history of installed updates. */ - showUpdates() + showUpdates: function() { gSubDialog.open("chrome://mozapps/content/update/history.xul"); }, @@ -795,7 +795,7 @@ var gAdvancedPane = { /** * Displays the user's certificates and associated options. */ - showCertificates() + showCertificates: function() { gSubDialog.open("chrome://pippki/content/certManager.xul"); }, @@ -803,12 +803,12 @@ var gAdvancedPane = { /** * Displays a dialog from which the user can manage his security devices. */ - showSecurityDevices() + showSecurityDevices: function() { gSubDialog.open("chrome://pippki/content/device_manager.xul"); }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (AppConstants.MOZ_UPDATER) { switch (aTopic) { case "nsPref:changed": diff --git a/browser/components/preferences/in-content/applications.js b/browser/components/preferences/in-content/applications.js index 67879b025e44..30d87dacf96e 100644 --- a/browser/components/preferences/in-content/applications.js +++ b/browser/components/preferences/in-content/applications.js @@ -119,11 +119,11 @@ function ArrayEnumerator(aItems) { ArrayEnumerator.prototype = { _index: 0, - hasMoreElements() { + hasMoreElements: function() { return this._index < this._contents.length; }, - getNext() { + getNext: function() { return this._contents[this._index++]; } }; @@ -172,7 +172,7 @@ HandlerInfoWrapper.prototype = { _categoryMgr: Cc["@mozilla.org/categorymanager;1"]. getService(Ci.nsICategoryManager), - element(aID) { + element: function(aID) { return document.getElementById(aID); }, @@ -214,7 +214,7 @@ HandlerInfoWrapper.prototype = { return this.wrappedHandlerInfo.possibleApplicationHandlers; }, - addPossibleApplicationHandler(aNewHandler) { + addPossibleApplicationHandler: function(aNewHandler) { var possibleApps = this.possibleApplicationHandlers.enumerate(); while (possibleApps.hasMoreElements()) { if (possibleApps.getNext().equals(aNewHandler)) @@ -223,7 +223,7 @@ HandlerInfoWrapper.prototype = { this.possibleApplicationHandlers.appendElement(aNewHandler, false); }, - removePossibleApplicationHandler(aHandler) { + removePossibleApplicationHandler: function(aHandler) { var defaultApp = this.preferredApplicationHandler; if (defaultApp && aHandler.equals(defaultApp)) { // If the app we remove was the default app, we must make sure @@ -362,7 +362,7 @@ HandlerInfoWrapper.prototype = { return this._getDisabledPluginTypes().indexOf(this.type) != -1; }, - _getDisabledPluginTypes() { + _getDisabledPluginTypes: function() { var types = ""; if (this._prefSvc.prefHasUserValue(PREF_DISABLED_PLUGIN_TYPES)) @@ -376,7 +376,7 @@ HandlerInfoWrapper.prototype = { return []; }, - disablePluginType() { + disablePluginType: function() { var disabledPluginTypes = this._getDisabledPluginTypes(); if (disabledPluginTypes.indexOf(this.type) == -1) @@ -391,7 +391,7 @@ HandlerInfoWrapper.prototype = { false); }, - enablePluginType() { + enablePluginType: function() { var disabledPluginTypes = this._getDisabledPluginTypes(); var type = this.type; @@ -412,7 +412,7 @@ HandlerInfoWrapper.prototype = { // Storage - store() { + store: function() { this._handlerSvc.store(this.wrappedHandlerInfo); }, @@ -423,7 +423,7 @@ HandlerInfoWrapper.prototype = { return this._getIcon(16); }, - _getIcon(aSize) { + _getIcon: function(aSize) { if (this.primaryExtension) return "moz-icon://goat." + this.primaryExtension + "?size=" + aSize; @@ -529,7 +529,7 @@ FeedHandlerInfo.prototype = { _inner: [], _removed: [], - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (aIID.equals(Ci.nsIMutableArray) || aIID.equals(Ci.nsIArray) || aIID.equals(Ci.nsISupports)) @@ -542,20 +542,20 @@ FeedHandlerInfo.prototype = { return this._inner.length; }, - enumerate() { + enumerate: function() { return new ArrayEnumerator(this._inner); }, - appendElement(aHandlerApp, aWeak) { + appendElement: function(aHandlerApp, aWeak) { this._inner.push(aHandlerApp); }, - removeElementAt(aIndex) { + removeElementAt: function(aIndex) { this._removed.push(this._inner[aIndex]); this._inner.splice(aIndex, 1); }, - queryElementAt(aIndex, aInterface) { + queryElementAt: function(aIndex, aInterface) { return this._inner[aIndex].QueryInterface(aInterface); } }; @@ -725,7 +725,7 @@ FeedHandlerInfo.prototype = { // so we when the controller calls store() after modifying the handlers, // the only thing we need to store is the removal of possible handlers // XXX Should we hold off on making the changes until this method gets called? - store() { + store: function() { for (let app of this._possibleApplicationHandlers._removed) { if (app instanceof Ci.nsILocalHandlerApp) { let pref = this.element(PREF_FEED_SELECTED_APP); @@ -800,7 +800,7 @@ InternalHandlerInfoWrapper.prototype = { // Override store so we so we can notify any code listening for registration // or unregistration of this handler. - store() { + store: function() { HandlerInfoWrapper.prototype.store.call(this); Services.obs.notifyObservers(null, this._handlerChanged, null); }, @@ -873,7 +873,7 @@ var gApplicationsPane = { // Initialization & Destruction - init() { + init: function() { function setEventListener(aId, aEventType, aCallback) { document.getElementById(aId) @@ -952,7 +952,7 @@ var gApplicationsPane = { setTimeout(_delayedPaneLoad, 0, this); }, - destroy() { + destroy: function() { window.removeEventListener("unload", this, false); this._prefSvc.removeObserver(PREF_SHOW_PLUGINS_IN_LIST, this); this._prefSvc.removeObserver(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS, this); @@ -975,7 +975,7 @@ var gApplicationsPane = { // nsISupports - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (aIID.equals(Ci.nsIObserver) || aIID.equals(Ci.nsIDOMEventListener || aIID.equals(Ci.nsISupports))) @@ -987,7 +987,7 @@ var gApplicationsPane = { // nsIObserver - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { // Rebuild the list when there are changes to preferences that influence // whether or not to show certain entries in the list. if (aTopic == "nsPref:changed" && !this._storingAction) { @@ -1008,7 +1008,7 @@ var gApplicationsPane = { // nsIDOMEventListener - handleEvent(aEvent) { + handleEvent: function(aEvent) { if (aEvent.type == "unload") { this.destroy(); } @@ -1017,14 +1017,14 @@ var gApplicationsPane = { // Composed Model Construction - _loadData() { + _loadData: function() { this._loadFeedHandler(); this._loadInternalHandlers(); this._loadPluginHandlers(); this._loadApplicationHandlers(); }, - _loadFeedHandler() { + _loadFeedHandler: function() { this._handledTypes[TYPE_MAYBE_FEED] = feedHandlerInfo; feedHandlerInfo.handledOnlyByPlugin = false; @@ -1039,7 +1039,7 @@ var gApplicationsPane = { * Load higher level internal handlers so they can be turned on/off in the * applications menu. */ - _loadInternalHandlers() { + _loadInternalHandlers: function() { var internalHandlers = [pdfHandlerInfo]; for (let internalHandler of internalHandlers) { if (internalHandler.enabled) { @@ -1066,7 +1066,7 @@ var gApplicationsPane = { * enabledPlugin to get the plugin that would be used, we'd still need to * check the pref ourselves to find out if it's enabled. */ - _loadPluginHandlers() { + _loadPluginHandlers: function() { "use strict"; let mimeTypes = navigator.mimeTypes; @@ -1089,7 +1089,7 @@ var gApplicationsPane = { /** * Load the set of handlers defined by the application datastore. */ - _loadApplicationHandlers() { + _loadApplicationHandlers: function() { var wrappedHandlerInfos = this._handlerSvc.enumerate(); while (wrappedHandlerInfos.hasMoreElements()) { let wrappedHandlerInfo = @@ -1111,7 +1111,7 @@ var gApplicationsPane = { // View Construction - _rebuildVisibleTypes() { + _rebuildVisibleTypes: function() { // Reset the list of visible types and the visible type description counts. this._visibleTypes = []; this._visibleTypeDescriptionCount = {}; @@ -1150,7 +1150,7 @@ var gApplicationsPane = { } }, - _rebuildView() { + _rebuildView: function() { // Clear the list of entries. while (this._list.childNodes.length > 1) this._list.removeChild(this._list.lastChild); @@ -1181,7 +1181,7 @@ var gApplicationsPane = { this._selectLastSelectedType(); }, - _matchesFilter(aType) { + _matchesFilter: function(aType) { var filterValue = this._filter.value.toLowerCase(); return this._describeType(aType).toLowerCase().indexOf(filterValue) != -1 || this._describePreferredAction(aType).toLowerCase().indexOf(filterValue) != -1; @@ -1197,7 +1197,7 @@ var gApplicationsPane = { * @param aHandlerInfo {nsIHandlerInfo} the type being described * @returns {string} a description of the type */ - _describeType(aHandlerInfo) { + _describeType: function(aHandlerInfo) { if (this._visibleTypeDescriptionCount[aHandlerInfo.description] > 1) return this._prefsBundle.getFormattedString("typeDescriptionWithType", [aHandlerInfo.description, @@ -1218,7 +1218,7 @@ var gApplicationsPane = { * is being described * @returns {string} a description of the action */ - _describePreferredAction(aHandlerInfo) { + _describePreferredAction: function(aHandlerInfo) { // alwaysAskBeforeHandling overrides the preferred action, so if that flag // is set, then describe that behavior instead. For most types, this is // the "alwaysAsk" string, but for the feed type we show something special. @@ -1280,7 +1280,7 @@ var gApplicationsPane = { } }, - _selectLastSelectedType() { + _selectLastSelectedType: function() { // If the list is disabled by the pref.downloads.disable_button.edit_actions // preference being locked, then don't select the type, as that would cause // it to appear selected, with a different background and an actions menu @@ -1306,7 +1306,7 @@ var gApplicationsPane = { * * @returns {boolean} whether or not it's valid */ - isValidHandlerApp(aHandlerApp) { + isValidHandlerApp: function(aHandlerApp) { if (!aHandlerApp) return false; @@ -1322,7 +1322,7 @@ var gApplicationsPane = { return false; }, - _isValidHandlerExecutable(aExecutable) { + _isValidHandlerExecutable: function(aExecutable) { let leafName; if (AppConstants.platform == "win") { leafName = `${AppConstants.MOZ_APP_NAME}.exe`; @@ -1344,7 +1344,7 @@ var gApplicationsPane = { * Rebuild the actions menu for the selected entry. Gets called by * the richlistitem constructor when an entry in the list gets selected. */ - rebuildActionsMenu() { + rebuildActionsMenu: function() { var typeItem = this._list.selectedItem; var handlerInfo = this._handledTypes[typeItem.type]; var menu = @@ -1539,7 +1539,7 @@ var gApplicationsPane = { /** * Sort the list when the user clicks on a column header. */ - sort(event) { + sort: function(event) { var column = event.target; // If the user clicked on a new sort column, remove the direction indicator @@ -1562,7 +1562,7 @@ var gApplicationsPane = { /** * Sort the list of visible types by the current sort column/direction. */ - _sortVisibleTypes() { + _sortVisibleTypes: function() { if (!this._sortColumn) return; @@ -1594,11 +1594,11 @@ var gApplicationsPane = { /** * Filter the list when the user enters a filter term into the filter field. */ - filter() { + filter: function() { this._rebuildView(); }, - focusFilterBox() { + focusFilterBox: function() { this._filter.focus(); this._filter.select(); }, @@ -1606,7 +1606,7 @@ var gApplicationsPane = { // Changes - onSelectAction(aActionItem) { + onSelectAction: function(aActionItem) { this._storingAction = true; try { @@ -1617,7 +1617,7 @@ var gApplicationsPane = { } }, - _storeAction(aActionItem) { + _storeAction: function(aActionItem) { var typeItem = this._list.selectedItem; var handlerInfo = this._handledTypes[typeItem.type]; @@ -1662,7 +1662,7 @@ var gApplicationsPane = { } }, - manageApp(aEvent) { + manageApp: function(aEvent) { // Don't let the normal "on select action" handler get this event, // as we handle it specially ourselves. aEvent.stopPropagation(); @@ -1689,7 +1689,7 @@ var gApplicationsPane = { }, - chooseApp(aEvent) { + chooseApp: function(aEvent) { // Don't let the normal "on select action" handler get this event, // as we handle it specially ourselves. aEvent.stopPropagation(); @@ -1777,13 +1777,13 @@ var gApplicationsPane = { // Mark which item in the list was last selected so we can reselect it // when we rebuild the list or when the user returns to the prefpane. - onSelectionChanged() { + onSelectionChanged: function() { if (this._list.selectedItem) this._list.setAttribute("lastSelectedType", this._list.selectedItem.getAttribute("type")); }, - _setIconClassForPreferredAction(aHandlerInfo, aElement) { + _setIconClassForPreferredAction: function(aHandlerInfo, aElement) { // If this returns true, the attribute that CSS sniffs for was set to something // so you shouldn't manually set an icon URI. // This removes the existing actionIcon attribute if any, even if returning false. @@ -1817,7 +1817,7 @@ var gApplicationsPane = { return false; }, - _getIconURLForPreferredAction(aHandlerInfo) { + _getIconURLForPreferredAction: function(aHandlerInfo) { switch (aHandlerInfo.preferredAction) { case Ci.nsIHandlerInfo.useSystemDefault: return this._getIconURLForSystemDefault(aHandlerInfo); @@ -1835,7 +1835,7 @@ var gApplicationsPane = { } }, - _getIconURLForHandlerApp(aHandlerApp) { + _getIconURLForHandlerApp: function(aHandlerApp) { if (aHandlerApp instanceof Ci.nsILocalHandlerApp) return this._getIconURLForFile(aHandlerApp.executable); @@ -1849,7 +1849,7 @@ var gApplicationsPane = { return ""; }, - _getIconURLForFile(aFile) { + _getIconURLForFile: function(aFile) { var fph = this._ioSvc.getProtocolHandler("file"). QueryInterface(Ci.nsIFileProtocolHandler); var urlSpec = fph.getURLSpecFromFile(aFile); @@ -1857,7 +1857,7 @@ var gApplicationsPane = { return "moz-icon://" + urlSpec + "?size=16"; }, - _getIconURLForWebApp(aWebAppURITemplate) { + _getIconURLForWebApp: function(aWebAppURITemplate) { var uri = this._ioSvc.newURI(aWebAppURITemplate, null, null); // Unfortunately we can't use the favicon service to get the favicon, @@ -1873,7 +1873,7 @@ var gApplicationsPane = { return ""; }, - _getIconURLForSystemDefault(aHandlerInfo) { + _getIconURLForSystemDefault: function(aHandlerInfo) { // Handler info objects for MIME types on some OSes implement a property bag // interface from which we can get an icon for the default app, so if we're // dealing with a MIME type on one of those OSes, then try to get the icon. diff --git a/browser/components/preferences/in-content/content.js b/browser/components/preferences/in-content/content.js index 588e54f84876..890a8be9c914 100644 --- a/browser/components/preferences/in-content/content.js +++ b/browser/components/preferences/in-content/content.js @@ -16,7 +16,7 @@ XPCOMUtils.defineLazyGetter(this, "AlertsServiceDND", function() { }); var gContentPane = { - init() + init: function() { function setEventListener(aId, aEventType, aCallback) { @@ -99,7 +99,7 @@ var gContentPane = { * Utility function to enable/disable the button specified by aButtonID based * on the value of the Boolean preference specified by aPreferenceID. */ - updateButtons(aButtonID, aPreferenceID) + updateButtons: function(aButtonID, aPreferenceID) { var button = document.getElementById(aButtonID); var preference = document.getElementById(aPreferenceID); @@ -145,7 +145,7 @@ var gContentPane = { * Displays the popup exceptions dialog where specific site popup preferences * can be set. */ - showPopupExceptions() + showPopupExceptions: function() { var bundlePreferences = document.getElementById("bundlePreferences"); var params = { blockVisible: false, sessionVisible: false, allowVisible: true, @@ -162,7 +162,7 @@ var gContentPane = { /** * Populates the default font list in UI. */ - _rebuildFonts() + _rebuildFonts: function() { var preferences = document.getElementById("contentPreferences"); // Ensure preferences are "visible" to ensure bindings work. @@ -177,7 +177,7 @@ var gContentPane = { /** * */ - _selectDefaultLanguageGroup(aLanguageGroup, aIsSerif) + _selectDefaultLanguageGroup: function(aLanguageGroup, aIsSerif) { const kFontNameFmtSerif = "font.name.serif.%LANG%"; const kFontNameFmtSansSerif = "font.name.sans-serif.%LANG%"; @@ -228,7 +228,7 @@ var gContentPane = { * Returns the type of the current default font for the language denoted by * aLanguageGroup. */ - _readDefaultFontTypeForLanguage(aLanguageGroup) + _readDefaultFontTypeForLanguage: function(aLanguageGroup) { const kDefaultFontType = "font.default.%LANG%"; var defaultFontTypePref = kDefaultFontType.replace(/%LANG%/, aLanguageGroup); @@ -248,7 +248,7 @@ var gContentPane = { * Displays the fonts dialog, where web page font names and sizes can be * configured. */ - configureFonts() + configureFonts: function() { gSubDialog.open("chrome://browser/content/preferences/fonts.xul", "resizable=no"); }, @@ -257,7 +257,7 @@ var gContentPane = { * Displays the colors dialog, where default web page/link/etc. colors can be * configured. */ - configureColors() + configureColors: function() { gSubDialog.open("chrome://browser/content/preferences/colors.xul", "resizable=no"); }, @@ -267,7 +267,7 @@ var gContentPane = { /** * Shows a dialog in which the preferred language for web content may be set. */ - showLanguages() + showLanguages: function() { gSubDialog.open("chrome://browser/content/preferences/languages.xul"); }, @@ -276,18 +276,18 @@ var gContentPane = { * Displays the translation exceptions dialog where specific site and language * translation preferences can be set. */ - showTranslationExceptions() + showTranslationExceptions: function() { gSubDialog.open("chrome://browser/content/preferences/translation.xul"); }, - openTranslationProviderAttribution() + openTranslationProviderAttribution: function() { Components.utils.import("resource:///modules/translation/Translation.jsm"); Translation.openProviderAttribution(); }, - toggleDoNotDisturbNotifications(event) + toggleDoNotDisturbNotifications: function(event) { AlertsServiceDND.manualDoNotDisturb = event.target.checked; }, diff --git a/browser/components/preferences/in-content/main.js b/browser/components/preferences/in-content/main.js index 543fe2fd809d..7f4687da3702 100644 --- a/browser/components/preferences/in-content/main.js +++ b/browser/components/preferences/in-content/main.js @@ -20,7 +20,7 @@ var gMainPane = { /** * Initialization of this. */ - init() + init: function() { function setEventListener(aId, aEventType, aCallback) { @@ -121,7 +121,7 @@ var gMainPane = { .notifyObservers(window, "main-pane-loaded", null); }, - enableE10SChange() + enableE10SChange: function() { if (AppConstants.E10S_TESTING_ONLY) { let e10sCheckbox = document.getElementById("e10sAutoStart"); @@ -155,7 +155,7 @@ var gMainPane = { } }, - separateProfileModeChange() + separateProfileModeChange: function() { if (AppConstants.MOZ_DEV_EDITION) { function quitApp() { @@ -206,7 +206,7 @@ var gMainPane = { } }, - onGetStarted(aEvent) { + onGetStarted: function(aEvent) { if (AppConstants.MOZ_DEV_EDITION) { const Cc = Components.classes, Ci = Components.interfaces; let wm = Cc["@mozilla.org/appshell/window-mediator;1"] @@ -241,7 +241,7 @@ var gMainPane = { * option is preserved. */ - syncFromHomePref() + syncFromHomePref: function() { let homePref = document.getElementById("browser.startup.homepage"); @@ -267,7 +267,7 @@ var gMainPane = { return undefined; }, - syncToHomePref(value) + syncToHomePref: function(value) { // If the value is "", use about:home. if (value == "") @@ -282,7 +282,7 @@ var gMainPane = { * most recent browser window contains multiple tabs), updating preference * window UI to reflect this. */ - setHomePageToCurrent() + setHomePageToCurrent: function() { let homePage = document.getElementById("browser.startup.homepage"); let tabs = this._getTabsForHomePage(); @@ -300,7 +300,7 @@ var gMainPane = { * page. If the user selects a bookmark, that bookmark's name is displayed in * UI and the bookmark's address is stored to the home page preference. */ - setHomePageToBookmark() + setHomePageToBookmark: function() { var rv = { urls: null, names: null }; gSubDialog.open("chrome://browser/content/preferences/selectBookmark.xul", @@ -308,7 +308,7 @@ var gMainPane = { this._setHomePageToBookmarkClosed.bind(this, rv)); }, - _setHomePageToBookmarkClosed(rv, aEvent) { + _setHomePageToBookmarkClosed: function(rv, aEvent) { if (aEvent.detail.button != "accept") return; if (rv.urls && rv.names) { @@ -323,7 +323,7 @@ var gMainPane = { * Switches the "Use Current Page" button between its singular and plural * forms. */ - _updateUseCurrentButton() { + _updateUseCurrentButton: function() { let useCurrent = document.getElementById("useCurrent"); @@ -342,7 +342,7 @@ var gMainPane = { useCurrent.disabled = !tabs.length }, - _getTabsForHomePage() + _getTabsForHomePage: function() { var win; var tabs = []; @@ -366,7 +366,7 @@ var gMainPane = { /** * Check to see if a tab is not about:preferences */ - isNotAboutPreferences(aElement, aIndex, aArray) + isNotAboutPreferences: function(aElement, aIndex, aArray) { return !aElement.linkedBrowser.currentURI.spec.startsWith("about:preferences"); }, @@ -374,7 +374,7 @@ var gMainPane = { /** * Restores the default home page as the user's home page. */ - restoreDefaultHomePage() + restoreDefaultHomePage: function() { var homePage = document.getElementById("browser.startup.homepage"); homePage.value = homePage.defaultValue; @@ -416,7 +416,7 @@ var gMainPane = { * Enables/disables the folder field and Browse button based on whether a * default download directory is being used. */ - readUseDownloadDir() + readUseDownloadDir: function() { var downloadFolder = document.getElementById("downloadFolder"); var chooseFolder = document.getElementById("chooseFolder"); @@ -529,7 +529,7 @@ var gMainPane = { /** * Returns the textual path of a folder in readable form. */ - _getDisplayNameOfFile(aFolder) + _getDisplayNameOfFile: function(aFolder) { // TODO: would like to add support for 'Downloads on Macintosh HD' // for OS X users. @@ -603,7 +603,7 @@ var gMainPane = { * Hide/show the "Show my windows and tabs from last time" option based * on the value of the browser.privatebrowsing.autostart pref. */ - updateBrowserStartupLastSession() + updateBrowserStartupLastSession: function() { let pbAutoStartPref = document.getElementById("browser.privatebrowsing.autostart"); let startupPref = document.getElementById("browser.startup.page"); @@ -650,7 +650,7 @@ var gMainPane = { * * @returns |true| if such links should be opened in new tabs */ - readLinkTarget() { + readLinkTarget: function() { var openNewWindow = document.getElementById("browser.link.open_newwindow"); return openNewWindow.value != 2; }, @@ -661,7 +661,7 @@ var gMainPane = { * @returns 2 if such links should be opened in new windows, * 3 if such links should be opened in new tabs */ - writeLinkTarget() { + writeLinkTarget: function() { var linkTargeting = document.getElementById("linkTargeting"); return linkTargeting.checked ? 3 : 2; }, @@ -677,7 +677,7 @@ var gMainPane = { * Show button for setting browser as default browser or information that * browser is already the default browser. */ - updateSetDefaultBrowser() + updateSetDefaultBrowser: function() { if (AppConstants.HAVE_SHELL_SERVICE) { let shellSvc = getShellService(); @@ -698,7 +698,7 @@ var gMainPane = { /** * Set browser as the operating system default browser. */ - setDefaultBrowser() + setDefaultBrowser: function() { if (AppConstants.HAVE_SHELL_SERVICE) { let alwaysCheckPref = document.getElementById("browser.shell.checkDefaultBrowser"); diff --git a/browser/components/preferences/in-content/preferences.js b/browser/components/preferences/in-content/preferences.js index baf3f406a799..68de4840598d 100644 --- a/browser/components/preferences/in-content/preferences.js +++ b/browser/components/preferences/in-content/preferences.js @@ -42,7 +42,7 @@ function init_category_if_required(category) { function register_module(categoryName, categoryObject) { gCategoryInits.set(categoryName, { inited: false, - init() { + init: function() { categoryObject.init(); this.inited = true; } diff --git a/browser/components/preferences/in-content/privacy.js b/browser/components/preferences/in-content/privacy.js index 54beef47c4b6..8098132e203f 100644 --- a/browser/components/preferences/in-content/privacy.js +++ b/browser/components/preferences/in-content/privacy.js @@ -26,7 +26,7 @@ var gPrivacyPane = { * Show the Tracking Protection UI depending on the * privacy.trackingprotection.ui.enabled pref, and linkify its Learn More link */ - _initTrackingProtection() { + _initTrackingProtection: function() { if (!Services.prefs.getBoolPref("privacy.trackingprotection.ui.enabled")) { return; } @@ -45,7 +45,7 @@ var gPrivacyPane = { * Linkify the Learn More link of the Private Browsing Mode Tracking * Protection UI. */ - _initTrackingProtectionPBM() { + _initTrackingProtectionPBM: function() { let link = document.getElementById("trackingProtectionPBMLearnMore"); let url = Services.urlFormatter.formatURLPref("app.support.baseURL") + "tracking-protection-pbm"; link.setAttribute("href", url); @@ -54,7 +54,7 @@ var gPrivacyPane = { /** * Initialize autocomplete to ensure prefs are in sync. */ - _initAutocomplete() { + _initAutocomplete: function() { Components.classes["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"] .getService(Components.interfaces.mozIPlacesAutoComplete); }, @@ -62,7 +62,7 @@ var gPrivacyPane = { /** * Show the Containers UI depending on the privacy.userContext.ui.enabled pref. */ - _initBrowserContainers() { + _initBrowserContainers: function() { if (!Services.prefs.getBoolPref("privacy.userContext.ui.enabled")) { return; } @@ -76,7 +76,7 @@ var gPrivacyPane = { Services.prefs.getBoolPref("privacy.userContext.enabled"); }, - _checkBrowserContainers(event) { + _checkBrowserContainers: function(event) { let checkbox = document.getElementById("browserContainersCheckbox"); if (checkbox.checked) { Services.prefs.setBoolPref("privacy.userContext.enabled", true); @@ -116,7 +116,7 @@ var gPrivacyPane = { * Sets up the UI for the number of days of history to keep, and updates the * label of the "Clear Now..." button. */ - init() + init: function() { function setEventListener(aId, aEventType, aCallback) { @@ -271,7 +271,7 @@ var gPrivacyPane = { * @returns boolean true if all of the prefs are set to keep history, * false otherwise */ - _checkHistoryValues(aPrefs) { + _checkHistoryValues: function(aPrefs) { for (let pref of Object.keys(aPrefs)) { if (document.getElementById(pref).value != aPrefs[pref]) return false; @@ -282,7 +282,7 @@ var gPrivacyPane = { /** * Initialize the history mode menulist based on the privacy preferences */ - initializeHistoryMode() + initializeHistoryMode: function PPP_initializeHistoryMode() { let mode; let getVal = aPref => document.getElementById(aPref).value; @@ -304,7 +304,7 @@ var gPrivacyPane = { /** * Update the selected pane based on the history mode menulist */ - updateHistoryModePane() + updateHistoryModePane: function PPP_updateHistoryModePane() { let selectedIndex = -1; switch (document.getElementById("historyMode").value) { @@ -326,7 +326,7 @@ var gPrivacyPane = { * Update the private browsing auto-start pref and the history mode * micro-management prefs based on the history mode menulist */ - updateHistoryModePrefs() + updateHistoryModePrefs: function PPP_updateHistoryModePrefs() { let pref = document.getElementById("browser.privatebrowsing.autostart"); switch (document.getElementById("historyMode").value) { @@ -361,7 +361,7 @@ var gPrivacyPane = { * Update the privacy micro-management controls based on the * value of the private browsing auto-start checkbox. */ - updatePrivacyMicroControls() + updatePrivacyMicroControls: function PPP_updatePrivacyMicroControls() { if (document.getElementById("historyMode").value == "custom") { let disabled = this._autoStartPrivateBrowsing = @@ -413,7 +413,7 @@ var gPrivacyPane = { /** * Initialize the starting state for the auto-start private browsing mode pref reverter. */ - initAutoStartPrivateBrowsingReverter() + initAutoStartPrivateBrowsingReverter: function PPP_initAutoStartPrivateBrowsingReverter() { let mode = document.getElementById("historyMode"); let autoStart = document.getElementById("privateBrowsingAutoStart"); @@ -423,7 +423,7 @@ var gPrivacyPane = { _lastMode: null, _lastCheckState: null, - updateAutostart() { + updateAutostart: function PPP_updateAutostart() { let mode = document.getElementById("historyMode"); let autoStart = document.getElementById("privateBrowsingAutoStart"); let pref = document.getElementById("browser.privatebrowsing.autostart"); @@ -490,7 +490,7 @@ var gPrivacyPane = { /** * Displays the available block lists for tracking protection. */ - showBlockLists() + showBlockLists: function() { var bundlePreferences = document.getElementById("bundlePreferences"); let brandName = document.getElementById("bundleBrand") @@ -545,7 +545,7 @@ var gPrivacyPane = { * enables/disables the rest of the cookie UI accordingly, returning true * if cookies are enabled. */ - readAcceptCookies() + readAcceptCookies: function() { var pref = document.getElementById("network.cookie.cookieBehavior"); var acceptThirdPartyLabel = document.getElementById("acceptThirdPartyLabel"); @@ -566,7 +566,7 @@ var gPrivacyPane = { * Enables/disables the "keep until" label and menulist in response to the * "accept cookies" checkbox being checked or unchecked. */ - writeAcceptCookies() + writeAcceptCookies: function() { var accept = document.getElementById("acceptCookies"); var acceptThirdPartyMenu = document.getElementById("acceptThirdPartyMenu"); @@ -581,7 +581,7 @@ var gPrivacyPane = { /** * Converts between network.cookie.cookieBehavior and the third-party cookie UI */ - readAcceptThirdPartyCookies() + readAcceptThirdPartyCookies: function() { var pref = document.getElementById("network.cookie.cookieBehavior"); switch (pref.value) @@ -599,7 +599,7 @@ var gPrivacyPane = { } }, - writeAcceptThirdPartyCookies() + writeAcceptThirdPartyCookies: function() { var accept = document.getElementById("acceptThirdPartyMenu").selectedItem; switch (accept.value) @@ -618,7 +618,7 @@ var gPrivacyPane = { /** * Displays fine-grained, per-site preferences for cookies. */ - showCookieExceptions() + showCookieExceptions: function() { var bundlePreferences = document.getElementById("bundlePreferences"); var params = { blockVisible : true, @@ -635,7 +635,7 @@ var gPrivacyPane = { /** * Displays all the user's cookies in a dialog. */ - showCookies(aCategory) + showCookies: function(aCategory) { gSubDialog.open("chrome://browser/content/preferences/cookies.xul"); }, @@ -653,7 +653,7 @@ var gPrivacyPane = { /** * Displays the Clear Private Data settings dialog. */ - showClearPrivateDataSettings() + showClearPrivateDataSettings: function() { gSubDialog.open("chrome://browser/content/preferences/sanitize.xul", "resizable=no"); }, @@ -663,7 +663,7 @@ var gPrivacyPane = { * Displays a dialog from which individual parts of private data may be * cleared. */ - clearPrivateDataNow(aClearEverything) { + clearPrivateDataNow: function(aClearEverything) { var ts = document.getElementById("privacy.sanitize.timeSpan"); var timeSpanOrig = ts.value; @@ -685,7 +685,7 @@ var gPrivacyPane = { * Enables or disables the "Settings..." button depending * on the privacy.sanitize.sanitizeOnShutdown preference value */ - _updateSanitizeSettingsButton() { + _updateSanitizeSettingsButton: function() { var settingsButton = document.getElementById("clearDataSettings"); var sanitizeOnShutdownPref = document.getElementById("privacy.sanitize.sanitizeOnShutdown"); @@ -704,7 +704,7 @@ var gPrivacyPane = { /** * Enables/disables the Settings button used to configure containers */ - readBrowserContainersCheckbox() + readBrowserContainersCheckbox: function() { var pref = document.getElementById("privacy.userContext.enabled"); var settings = document.getElementById("browserContainersSettings"); diff --git a/browser/components/preferences/in-content/search.js b/browser/components/preferences/in-content/search.js index 063944e7cd9e..7cf77de75507 100644 --- a/browser/components/preferences/in-content/search.js +++ b/browser/components/preferences/in-content/search.js @@ -17,12 +17,12 @@ var gSearchPane = { /** * Initialize autocomplete to ensure prefs are in sync. */ - _initAutocomplete() { + _initAutocomplete: function() { Components.classes["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"] .getService(Components.interfaces.mozIPlacesAutoComplete); }, - init() + init: function() { gEngineView = new EngineView(new EngineStore()); document.getElementById("engineList").view = gEngineView; @@ -75,7 +75,7 @@ var gSearchPane = { permanentPBLabel.hidden = urlbarSuggests.hidden || !permanentPB; }, - buildDefaultEngineDropDown() { + buildDefaultEngineDropDown: function() { // This is called each time something affects the list of engines. let list = document.getElementById("defaultEngine"); // Set selection to the current default engine. @@ -100,7 +100,7 @@ var gSearchPane = { }); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "click": if (aEvent.target.id != "engineChildren" && @@ -162,7 +162,7 @@ var gSearchPane = { } }, - observe(aEngine, aTopic, aVerb) { + observe: function(aEngine, aTopic, aVerb) { if (aTopic == "browser-search-engine-modified") { aEngine.QueryInterface(Components.interfaces.nsISearchEngine); switch (aVerb) { @@ -194,7 +194,7 @@ var gSearchPane = { } }, - onInputBlur(aEvent) { + onInputBlur: function(aEvent) { let tree = document.getElementById("engineList"); if (!tree.hasAttribute("editing")) return; @@ -204,12 +204,12 @@ var gSearchPane = { tree.stopEditing(accept); }, - onTreeSelect() { + onTreeSelect: function() { document.getElementById("removeEngineButton").disabled = !gEngineView.isEngineSelectedAndRemovable(); }, - onTreeKeyPress(aEvent) { + onTreeKeyPress: function(aEvent) { let index = gEngineView.selectedIndex; let tree = document.getElementById("engineList"); if (tree.hasAttribute("editing")) @@ -238,17 +238,17 @@ var gSearchPane = { } }, - onRestoreDefaults() { + onRestoreDefaults: function() { let num = gEngineView._engineStore.restoreDefaultEngines(); gEngineView.rowCountChanged(0, num); gEngineView.invalidate(); }, - showRestoreDefaults(aEnable) { + showRestoreDefaults: function(aEnable) { document.getElementById("restoreDefaultSearchEngines").disabled = !aEnable; }, - remove(aEngine) { + remove: function(aEngine) { let index = gEngineView._engineStore.removeEngine(aEngine); gEngineView.rowCountChanged(index, -1); gEngineView.invalidate(); @@ -294,7 +294,7 @@ var gSearchPane = { return true; }), - saveOneClickEnginesList() { + saveOneClickEnginesList: function() { let hiddenList = []; for (let engine of gEngineView._engineStore.engines) { if (!engine.shown) @@ -304,7 +304,7 @@ var gSearchPane = { hiddenList.join(","); }, - setDefaultEngine() { + setDefaultEngine: function() { Services.search.currentEngine = document.getElementById("defaultEngine").selectedItem.engine; } @@ -345,15 +345,15 @@ EngineStore.prototype = { return val; }, - _getIndexForEngine(aEngine) { + _getIndexForEngine: function ES_getIndexForEngine(aEngine) { return this._engines.indexOf(aEngine); }, - _getEngineByName(aName) { + _getEngineByName: function ES_getEngineByName(aName) { return this._engines.find(engine => engine.name == aName); }, - _cloneEngine(aEngine) { + _cloneEngine: function ES_cloneEngine(aEngine) { var clonedObj = {}; for (var i in aEngine) clonedObj[i] = aEngine[i]; @@ -363,15 +363,15 @@ EngineStore.prototype = { }, // Callback for Array's some(). A thisObj must be passed to some() - _isSameEngine(aEngineClone) { + _isSameEngine: function ES_isSameEngine(aEngineClone) { return aEngineClone.originalEngine == this.originalEngine; }, - addEngine(aEngine) { + addEngine: function ES_addEngine(aEngine) { this._engines.push(this._cloneEngine(aEngine)); }, - moveEngine(aEngine, aNewIndex) { + moveEngine: function ES_moveEngine(aEngine, aNewIndex) { if (aNewIndex < 0 || aNewIndex > this._engines.length - 1) throw new Error("ES_moveEngine: invalid aNewIndex!"); var index = this._getIndexForEngine(aEngine); @@ -388,7 +388,7 @@ EngineStore.prototype = { Services.search.moveEngine(aEngine.originalEngine, aNewIndex); }, - removeEngine(aEngine) { + removeEngine: function ES_removeEngine(aEngine) { if (this._engines.length == 1) { throw new Error("Cannot remove last engine!"); } @@ -407,7 +407,7 @@ EngineStore.prototype = { return index; }, - restoreDefaultEngines() { + restoreDefaultEngines: function ES_restoreDefaultEngines() { var added = 0; for (var i = 0; i < this._defaultEngines.length; ++i) { @@ -436,7 +436,7 @@ EngineStore.prototype = { return added; }, - changeEngine(aEngine, aProp, aNewValue) { + changeEngine: function ES_changeEngine(aEngine, aProp, aNewValue) { var index = this._getIndexForEngine(aEngine); if (index == -1) throw new Error("invalid engine?"); @@ -445,7 +445,7 @@ EngineStore.prototype = { aEngine.originalEngine[aProp] = aNewValue; }, - reloadIcons() { + reloadIcons: function ES_reloadIcons() { this._engines.forEach(function(e) { e.uri = e.originalEngine.uri; }); @@ -476,27 +476,27 @@ EngineView.prototype = { }, // Helpers - rowCountChanged(index, count) { + rowCountChanged: function(index, count) { this.tree.rowCountChanged(index, count); }, - invalidate() { + invalidate: function() { this.tree.invalidate(); }, - ensureRowIsVisible(index) { + ensureRowIsVisible: function(index) { this.tree.ensureRowIsVisible(index); }, - getSourceIndexFromDrag(dataTransfer) { + getSourceIndexFromDrag: function(dataTransfer) { return parseInt(dataTransfer.getData(ENGINE_FLAVOR)); }, - isCheckBox(index, column) { + isCheckBox: function(index, column) { return column.id == "engineShown"; }, - isEngineSelectedAndRemovable() { + isEngineSelectedAndRemovable: function() { return this.selectedIndex != -1 && this.lastIndex != 0; }, @@ -505,7 +505,7 @@ EngineView.prototype = { return this._engineStore.engines.length; }, - getImageSrc(index, column) { + getImageSrc: function(index, column) { if (column.id == "engineName") { if (this._engineStore.engines[index].iconURI) return this._engineStore.engines[index].iconURI.spec; @@ -518,7 +518,7 @@ EngineView.prototype = { return ""; }, - getCellText(index, column) { + getCellText: function(index, column) { if (column.id == "engineName") return this._engineStore.engines[index].name; else if (column.id == "engineKeyword") @@ -526,18 +526,18 @@ EngineView.prototype = { return ""; }, - setTree(tree) { + setTree: function(tree) { this.tree = tree; }, - canDrop(targetIndex, orientation, dataTransfer) { + canDrop: function(targetIndex, orientation, dataTransfer) { var sourceIndex = this.getSourceIndexFromDrag(dataTransfer); return (sourceIndex != -1 && sourceIndex != targetIndex && sourceIndex != targetIndex + orientation); }, - drop(dropIndex, orientation, dataTransfer) { + drop: function(dropIndex, orientation, dataTransfer) { var sourceIndex = this.getSourceIndexFromDrag(dataTransfer); var sourceEngine = this._engineStore.engines[sourceIndex]; @@ -559,37 +559,37 @@ EngineView.prototype = { }, selection: null, - getRowProperties(index) { return ""; }, - getCellProperties(index, column) { return ""; }, - getColumnProperties(column) { return ""; }, - isContainer(index) { return false; }, - isContainerOpen(index) { return false; }, - isContainerEmpty(index) { return false; }, - isSeparator(index) { return false; }, - isSorted(index) { return false; }, - getParentIndex(index) { return -1; }, - hasNextSibling(parentIndex, index) { return false; }, - getLevel(index) { return 0; }, - getProgressMode(index, column) { }, - getCellValue(index, column) { + getRowProperties: function(index) { return ""; }, + getCellProperties: function(index, column) { return ""; }, + getColumnProperties: function(column) { return ""; }, + isContainer: function(index) { return false; }, + isContainerOpen: function(index) { return false; }, + isContainerEmpty: function(index) { return false; }, + isSeparator: function(index) { return false; }, + isSorted: function(index) { return false; }, + getParentIndex: function(index) { return -1; }, + hasNextSibling: function(parentIndex, index) { return false; }, + getLevel: function(index) { return 0; }, + getProgressMode: function(index, column) { }, + getCellValue: function(index, column) { if (column.id == "engineShown") return this._engineStore.engines[index].shown; return undefined; }, - toggleOpenState(index) { }, - cycleHeader(column) { }, - selectionChanged() { }, - cycleCell(row, column) { }, - isEditable(index, column) { return column.id != "engineName"; }, - isSelectable(index, column) { return false; }, - setCellValue(index, column, value) { + toggleOpenState: function(index) { }, + cycleHeader: function(column) { }, + selectionChanged: function() { }, + cycleCell: function(row, column) { }, + isEditable: function(index, column) { return column.id != "engineName"; }, + isSelectable: function(index, column) { return false; }, + setCellValue: function(index, column, value) { if (column.id == "engineShown") { this._engineStore.engines[index].shown = value == "true"; gEngineView.invalidate(); gSearchPane.saveOneClickEnginesList(); } }, - setCellText(index, column, value) { + setCellText: function(index, column, value) { if (column.id == "engineKeyword") { gSearchPane.editKeyword(this._engineStore.engines[index], value) .then(valid => { @@ -598,7 +598,7 @@ EngineView.prototype = { }); } }, - performAction(action) { }, - performActionOnRow(action, index) { }, - performActionOnCell(action, index, column) { } + performAction: function(action) { }, + performActionOnRow: function(action, index) { }, + performActionOnCell: function(action, index, column) { } }; diff --git a/browser/components/preferences/in-content/security.js b/browser/components/preferences/in-content/security.js index 47f2fce33a4b..a468100a1cd4 100644 --- a/browser/components/preferences/in-content/security.js +++ b/browser/components/preferences/in-content/security.js @@ -13,7 +13,7 @@ var gSecurityPane = { /** * Initializes master password UI. */ - init() + init: function() { function setEventListener(aId, aEventType, aCallback) { @@ -52,7 +52,7 @@ var gSecurityPane = { * Enables/disables the add-ons Exceptions button depending on whether * or not add-on installation warnings are displayed. */ - readWarnAddonInstall() + readWarnAddonInstall: function() { var warn = document.getElementById("xpinstall.whitelist.required"); var exceptions = document.getElementById("addonExceptions"); @@ -66,7 +66,7 @@ var gSecurityPane = { /** * Displays the exceptions lists for add-on installation warnings. */ - showAddonExceptions() + showAddonExceptions: function() { var bundlePrefs = document.getElementById("bundlePreferences"); @@ -106,7 +106,7 @@ var gSecurityPane = { * passwords are never saved. When browser is set to start in Private * Browsing mode, the "Remember passwords" UI is useless, so we disable it. */ - readSavePasswords() + readSavePasswords: function() { var pref = document.getElementById("signon.rememberSignons"); var excepts = document.getElementById("passwordExceptions"); @@ -125,7 +125,7 @@ var gSecurityPane = { * Displays a dialog in which the user can view and modify the list of sites * where passwords are never saved. */ - showPasswordExceptions() + showPasswordExceptions: function() { var bundlePrefs = document.getElementById("bundlePreferences"); var params = { @@ -149,7 +149,7 @@ var gSecurityPane = { * The master password is controlled by various bits of NSS functionality, so * the UI for it can't be controlled by the normal preference bindings. */ - _initMasterPasswordUI() + _initMasterPasswordUI: function() { var noMP = !LoginHelper.isMasterPasswordSet(); @@ -238,7 +238,7 @@ var gSecurityPane = { * "use master password" checkbox, and prompts for master password removal if * one is set. */ - updateMasterPasswordButton() + updateMasterPasswordButton: function() { var checkbox = document.getElementById("useMasterPassword"); var button = document.getElementById("changeMasterPassword"); @@ -262,7 +262,7 @@ var gSecurityPane = { * the current master password. When the dialog is dismissed, master password * UI is automatically updated. */ - _removeMasterPassword() + _removeMasterPassword: function() { var secmodDB = Cc["@mozilla.org/security/pkcs11moduledb;1"]. getService(Ci.nsIPKCS11ModuleDB); @@ -284,7 +284,7 @@ var gSecurityPane = { /** * Displays a dialog in which the master password may be changed. */ - changeMasterPassword() + changeMasterPassword: function() { gSubDialog.open("chrome://mozapps/content/preferences/changemp.xul", "resizable=no", null, this._initMasterPasswordUI.bind(this)); @@ -294,7 +294,7 @@ var gSecurityPane = { * Shows the sites where the user has saved passwords and the associated login * information. */ - showPasswords() + showPasswords: function() { gSubDialog.open("chrome://passwordmgr/content/passwordManager.xul"); } diff --git a/browser/components/preferences/in-content/subdialogs.js b/browser/components/preferences/in-content/subdialogs.js index 9a21e383a5e3..bb8d0048f24e 100644 --- a/browser/components/preferences/in-content/subdialogs.js +++ b/browser/components/preferences/in-content/subdialogs.js @@ -19,20 +19,20 @@ var gSubDialog = { ], _resizeObserver: null, - init() { + init: function() { this._frame = document.getElementById("dialogFrame"); this._overlay = document.getElementById("dialogOverlay"); this._box = document.getElementById("dialogBox"); this._closeButton = document.getElementById("dialogClose"); }, - updateTitle(aEvent) { + updateTitle: function(aEvent) { if (aEvent.target != gSubDialog._frame.contentDocument) return; document.getElementById("dialogTitle").textContent = gSubDialog._frame.contentDocument.title; }, - injectXMLStylesheet(aStylesheetURL) { + injectXMLStylesheet: function(aStylesheetURL) { let contentStylesheet = this._frame.contentDocument.createProcessingInstruction( 'xml-stylesheet', 'href="' + aStylesheetURL + '" type="text/css"' @@ -41,7 +41,7 @@ var gSubDialog = { this._frame.contentDocument.documentElement); }, - open(aURL, aFeatures = null, aParams = null, aClosingCallback = null) { + open: function(aURL, aFeatures = null, aParams = null, aClosingCallback = null) { // If we're already open/opening on this URL, do nothing. if (this._openedURL == aURL && !this._isClosing) { return; @@ -76,7 +76,7 @@ var gSubDialog = { featureParams.get("resizable") != "0"); }, - close(aEvent = null) { + close: function(aEvent = null) { if (this._isClosing) { return; } @@ -122,7 +122,7 @@ var gSubDialog = { }, 0); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "command": this._frame.contentWindow.close(); @@ -153,13 +153,13 @@ var gSubDialog = { /* Private methods */ - _onUnload(aEvent) { + _onUnload: function(aEvent) { if (aEvent.target.location.href == this._openedURL) { this._frame.contentWindow.close(); } }, - _onContentLoaded(aEvent) { + _onContentLoaded: function(aEvent) { if (aEvent.target != this._frame || aEvent.target.contentWindow.location == "about:blank") { return; } @@ -209,7 +209,7 @@ var gSubDialog = { this._overlay.style.opacity = "0.01"; }, - _onLoad(aEvent) { + _onLoad: function(aEvent) { if (aEvent.target.contentWindow.location == "about:blank") { return; } @@ -293,7 +293,7 @@ var gSubDialog = { this._trapFocus(); }, - _onResize(mutations) { + _onResize: function(mutations) { let frame = gSubDialog._frame; // The width and height styles are needed for the initial // layout of the frame, but afterward they need to be removed @@ -319,12 +319,12 @@ var gSubDialog = { } }, - _onDialogClosing(aEvent) { + _onDialogClosing: function(aEvent) { this._frame.contentWindow.removeEventListener("dialogclosing", this); this._closingEvent = aEvent; }, - _onKeyDown(aEvent) { + _onKeyDown: function(aEvent) { if (aEvent.currentTarget == window && aEvent.keyCode == aEvent.DOM_VK_ESCAPE && !aEvent.defaultPrevented) { this.close(aEvent); @@ -362,7 +362,7 @@ var gSubDialog = { } }, - _onParentWinFocus(aEvent) { + _onParentWinFocus: function(aEvent) { // Explicitly check for the focus target of |window| to avoid triggering this when the window // is refocused if (aEvent.target != this._closeButton && aEvent.target != window) { @@ -370,7 +370,7 @@ var gSubDialog = { } }, - _addDialogEventListeners() { + _addDialogEventListeners: function() { // Make the close button work. this._closeButton.addEventListener("command", this); @@ -392,7 +392,7 @@ var gSubDialog = { window.addEventListener("keydown", this, true); }, - _removeDialogEventListeners() { + _removeDialogEventListeners: function() { let chromeBrowser = this._getBrowser(); chromeBrowser.removeEventListener("DOMTitleChanged", this, true); chromeBrowser.removeEventListener("unload", this, true); @@ -410,7 +410,7 @@ var gSubDialog = { this._untrapFocus(); }, - _trapFocus() { + _trapFocus: function() { let fm = Services.focus; fm.moveFocus(this._frame.contentWindow, null, fm.MOVEFOCUS_FIRST, 0); this._frame.contentDocument.addEventListener("keydown", this, true); @@ -419,13 +419,13 @@ var gSubDialog = { window.addEventListener("focus", this, true); }, - _untrapFocus() { + _untrapFocus: function() { this._frame.contentDocument.removeEventListener("keydown", this, true); this._closeButton.removeEventListener("keydown", this); window.removeEventListener("focus", this); }, - _getBrowser() { + _getBrowser: function() { return window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShell) diff --git a/browser/components/preferences/in-content/sync.js b/browser/components/preferences/in-content/sync.js index 32c5c934a292..ca3175513dcf 100644 --- a/browser/components/preferences/in-content/sync.js +++ b/browser/components/preferences/in-content/sync.js @@ -42,14 +42,14 @@ var gSyncPane = { return Weave.Svc.Prefs.isSet("serverURL"); }, - needsUpdate() { + needsUpdate: function() { this.page = PAGE_NEEDS_UPDATE; let label = document.getElementById("loginError"); label.textContent = Weave.Utils.getErrorString(Weave.Status.login); label.className = "error"; }, - init() { + init: function() { this._setupEventListeners(); // If the Service hasn't finished initializing, wait for it. @@ -85,7 +85,7 @@ var gSyncPane = { xps.ensureLoaded(); }, - _showLoadPage(xps) { + _showLoadPage: function(xps) { let username; try { username = Services.prefs.getCharPref("services.sync.username"); @@ -109,7 +109,7 @@ var gSyncPane = { } }, - _init() { + _init: function() { let topics = ["weave:service:login:error", "weave:service:login:finish", "weave:service:start-over:finish", @@ -161,7 +161,7 @@ var gSyncPane = { this._initProfileImageUI(); }, - _toggleComputerNameControls(editMode) { + _toggleComputerNameControls: function(editMode) { let textbox = document.getElementById("fxaSyncComputerName"); textbox.disabled = !editMode; document.getElementById("fxaChangeDeviceName").hidden = editMode; @@ -169,25 +169,25 @@ var gSyncPane = { document.getElementById("fxaSaveChangeDeviceName").hidden = !editMode; }, - _focusComputerNameTextbox() { + _focusComputerNameTextbox: function() { let textbox = document.getElementById("fxaSyncComputerName"); let valLength = textbox.value.length; textbox.focus(); textbox.setSelectionRange(valLength, valLength); }, - _blurComputerNameTextbox() { + _blurComputerNameTextbox: function() { document.getElementById("fxaSyncComputerName").blur(); }, - _focusAfterComputerNameTextbox() { + _focusAfterComputerNameTextbox: function() { // Focus the most appropriate element that's *not* the "computer name" box. Services.focus.moveFocus(window, document.getElementById("fxaSyncComputerName"), Services.focus.MOVEFOCUS_FORWARD, 0); }, - _updateComputerNameValue(save) { + _updateComputerNameValue: function(save) { if (save) { let textbox = document.getElementById("fxaSyncComputerName"); Weave.Service.clientsEngine.localName = textbox.value; @@ -195,7 +195,7 @@ var gSyncPane = { this._populateComputerName(Weave.Service.clientsEngine.localName); }, - _setupEventListeners() { + _setupEventListeners: function() { function setEventListener(aId, aEventType, aCallback) { document.getElementById(aId) @@ -294,7 +294,7 @@ var gSyncPane = { }); }, - _initProfileImageUI() { + _initProfileImageUI: function() { try { if (Services.prefs.getBoolPref("identity.fxaccounts.profile_image.enabled")) { document.getElementById("fxaProfileImage").hidden = false; @@ -302,7 +302,7 @@ var gSyncPane = { } catch (e) { } }, - updateWeavePrefs() { + updateWeavePrefs: function() { let service = Components.classes["@mozilla.org/weave/service;1"] .getService(Components.interfaces.nsISupports) .wrappedJSObject; @@ -427,7 +427,7 @@ var gSyncPane = { } }, - startOver(showDialog) { + startOver: function(showDialog) { if (showDialog) { let flags = Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING + Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL + @@ -449,26 +449,26 @@ var gSyncPane = { this.updateWeavePrefs(); }, - updatePass() { + updatePass: function() { if (Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED) gSyncUtils.changePassword(); else gSyncUtils.updatePassphrase(); }, - resetPass() { + resetPass: function() { if (Weave.Status.login == Weave.LOGIN_FAILED_LOGIN_REJECTED) gSyncUtils.resetPassword(); else gSyncUtils.resetPassphrase(); }, - _getEntryPoint() { + _getEntryPoint: function() { let params = new URLSearchParams(document.URL.split("#")[0].split("?")[1] || ""); return params.get("entrypoint") || "preferences"; }, - _openAboutAccounts(action) { + _openAboutAccounts: function(action) { let entryPoint = this._getEntryPoint(); let params = new URLSearchParams(); if (action) { @@ -488,7 +488,7 @@ var gSyncPane = { * "pair" -- pair a device first * "reset" -- reset sync */ - openSetup(wizardType) { + openSetup: function(wizardType) { let service = Components.classes["@mozilla.org/weave/service;1"] .getService(Components.interfaces.nsISupports) .wrappedJSObject; @@ -507,7 +507,7 @@ var gSyncPane = { } }, - openContentInBrowser(url, options) { + openContentInBrowser: function(url, options) { let win = Services.wm.getMostRecentWindow("navigator:browser"); if (!win) { // no window to use, so use _openLink to create a new one. We don't @@ -530,20 +530,20 @@ var gSyncPane = { browser.loadURI(url); }, - signUp() { + signUp: function() { this._openAboutAccounts("signup"); }, - signIn() { + signIn: function() { this._openAboutAccounts("signin"); }, - reSignIn() { + reSignIn: function() { this._openAboutAccounts("reauth"); }, - clickOrSpaceOrEnterPressed(event) { + clickOrSpaceOrEnterPressed: function(event) { // Note: charCode is deprecated, but 'char' not yet implemented. // Replace charCode with char when implemented, see Bug 680830 return ((event.type == "click" && event.button == 0) || @@ -551,7 +551,7 @@ var gSyncPane = { (event.charCode == KeyEvent.DOM_VK_SPACE || event.keyCode == KeyEvent.DOM_VK_RETURN))); }, - openChangeProfileImage(event) { + openChangeProfileImage: function(event) { if (this.clickOrSpaceOrEnterPressed(event)) { fxAccounts.promiseAccountsChangeProfileURI(this._getEntryPoint(), "avatar") .then(url => { @@ -564,7 +564,7 @@ var gSyncPane = { } }, - openManageFirefoxAccount(event) { + openManageFirefoxAccount: function(event) { if (this.clickOrSpaceOrEnterPressed(event)) { this.manageFirefoxAccount(); // Prevent page from scrolling on the space key. @@ -572,7 +572,7 @@ var gSyncPane = { } }, - manageFirefoxAccount() { + manageFirefoxAccount: function() { fxAccounts.promiseAccountsManageURI(this._getEntryPoint()) .then(url => { this.openContentInBrowser(url, { @@ -581,7 +581,7 @@ var gSyncPane = { }); }, - verifyFirefoxAccount() { + verifyFirefoxAccount: function() { let showVerifyNotification = (data) => { let isError = !data; let maybeNot = isError ? "Not" : ""; @@ -609,12 +609,12 @@ var gSyncPane = { .then(onSuccess, onError); }, - openOldSyncSupportPage() { + openOldSyncSupportPage: function() { let url = Services.urlFormatter.formatURLPref("app.support.baseURL") + "old-sync"; this.openContentInBrowser(url); }, - unlinkFirefoxAccount(confirm) { + unlinkFirefoxAccount: function(confirm) { if (confirm) { // We use a string bundle shared with aboutAccounts. let sb = Services.strings.createBundle("chrome://browser/locale/syncSetup.properties"); @@ -646,7 +646,7 @@ var gSyncPane = { }); }, - openAddDevice() { + openAddDevice: function() { if (!Weave.Utils.ensureMPUnlocked()) return; @@ -658,7 +658,7 @@ var gSyncPane = { "syncAddDevice", "centerscreen,chrome,resizable=no"); }, - resetSync() { + resetSync: function() { this.openSetup("reset"); }, diff --git a/browser/components/preferences/in-content/tests/browser_advanced_siteData.js b/browser/components/preferences/in-content/tests/browser_advanced_siteData.js index 4b635a2138de..043c8aea072d 100644 --- a/browser/components/preferences/in-content/tests/browser_advanced_siteData.js +++ b/browser/components/preferences/in-content/tests/browser_advanced_siteData.js @@ -21,13 +21,13 @@ const mockOfflineAppCacheHelper = { originalClear: null, - register() { + register: function() { this.originalClear = OfflineAppCacheHelper.clear; this.clear = sinon.spy(); OfflineAppCacheHelper.clear = this.clear; }, - unregister() { + unregister: function() { OfflineAppCacheHelper.clear = this.originalClear; } }; @@ -55,7 +55,7 @@ function getQuotaUsage(origin) { function getCacheUsage() { return new Promise(resolve => { let obs = { - onNetworkCacheDiskConsumption(usage) { + onNetworkCacheDiskConsumption: function(usage) { resolve(usage); }, QueryInterface: XPCOMUtils.generateQI([ diff --git a/browser/components/preferences/in-content/tests/browser_advanced_update.js b/browser/components/preferences/in-content/tests/browser_advanced_update.js index 9a18fcecae6b..d9d7aa33ae7a 100644 --- a/browser/components/preferences/in-content/tests/browser_advanced_update.js +++ b/browser/components/preferences/in-content/tests/browser_advanced_update.js @@ -20,14 +20,14 @@ const mockUpdateManager = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateManager]), - createInstance(outer, iiD) { + createInstance: function(outer, iiD) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } return this.QueryInterface(iiD); }, - register() { + register: function() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); if (!registrar.isCIDRegistered(this._mockClassId)) { this._originalClassId = registrar.contractIDToCID(this.contractId); @@ -37,7 +37,7 @@ const mockUpdateManager = { } }, - unregister() { + unregister: function() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(this._mockClassId, this); registrar.registerFactory(this._originalClassId, "", this.contractId, this._originalFactory); @@ -47,7 +47,7 @@ const mockUpdateManager = { return this._updates.length; }, - getUpdateAt(index) { + getUpdateAt: function(index) { return this._updates[index]; }, diff --git a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js b/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js index 40741cccab77..32c1bd726374 100644 --- a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js +++ b/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js @@ -27,14 +27,14 @@ add_task(function*() { // Simulate a dumb font backend. win.FontBuilder._enumerator = { _list: ["MockedFont1", "MockedFont2", "MockedFont3"], - EnumerateFonts(lang, type, list) { + EnumerateFonts: function(lang, type, list) { return this._list; }, - EnumerateAllFonts() { + EnumerateAllFonts: function() { return this._list; }, - getDefaultFont() { return null; }, - getStandardFamilyName(name) { return name; }, + getDefaultFont: function() { return null; }, + getStandardFamilyName: function(name) { return name; }, }; win.FontBuilder._allFonts = null; win.FontBuilder._langGroupSupported = false; diff --git a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js b/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js index 8d0a910f0c14..bc2c6d800296 100644 --- a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js +++ b/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js @@ -35,7 +35,7 @@ function openPreferencesViaHash(aPane) { let win = gBrowser.contentWindow; let selectedPane = win.history.state; gBrowser.removeCurrentTab(); - deferred.resolve({selectedPane}); + deferred.resolve({selectedPane: selectedPane}); }); }, true); diff --git a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js b/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js index d604332096b5..15342f127529 100644 --- a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js +++ b/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js @@ -14,7 +14,7 @@ var testRunner = { tests: [ { - test(params) { + test: function(params) { params.url.value = "test.com"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -28,7 +28,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "test.com"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", @@ -41,7 +41,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "test.com"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", @@ -54,7 +54,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "test.com"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -64,7 +64,7 @@ var testRunner = { }, { expectPermObservancesDuringTestFunction: true, - test(params) { + test: function(params) { let uri = params.ioService.newURI("http://test.com", null, null); params.pm.add(uri, "popup", Ci.nsIPermissionManager.DENY_ACTION); is(params.tree.view.rowCount, 0, "adding unrelated permission should not change display"); @@ -72,13 +72,13 @@ var testRunner = { }, observances: [{ type: "popup", origin: "http://test.com", data: "added", capability: Ci.nsIPermissionManager.DENY_ACTION }], - cleanUp(params) { + cleanUp: function(params) { let uri = params.ioService.newURI("http://test.com", null, null); params.pm.remove(uri, "popup"); }, }, { - test(params) { + test: function(params) { params.url.value = "https://test.com:12345"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -92,7 +92,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "https://test.com:12345"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", @@ -105,7 +105,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "https://test.com:12345"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", @@ -118,7 +118,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "https://test.com:12345"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -127,7 +127,7 @@ var testRunner = { observances: [{ type: "cookie", origin: "https://test.com:12345", data: "deleted" }], }, { - test(params) { + test: function(params) { params.url.value = "localhost:12345"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -141,7 +141,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "localhost:12345"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", @@ -154,7 +154,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "localhost:12345"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", @@ -167,7 +167,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test(params) { + test: function(params) { params.url.value = "localhost:12345"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -220,7 +220,7 @@ var testRunner = { _currentTest: -1, - runTests() { + runTests: function() { this._currentTest++; info("Running test #" + (this._currentTest + 1) + "\n"); @@ -236,11 +236,11 @@ var testRunner = { }); }, - runCurrentTest(testNumber) { + runCurrentTest: function(testNumber) { return new Promise(function(resolve, reject) { let helperFunctions = { - windowLoad(win) { + windowLoad: function(win) { let doc = win.document; let params = { doc, @@ -265,7 +265,7 @@ var testRunner = { }; let permObserver = { - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic != "perm-changed") return; diff --git a/browser/components/preferences/in-content/tests/head.js b/browser/components/preferences/in-content/tests/head.js index d9eb3a1aabfa..203fd686782b 100644 --- a/browser/components/preferences/in-content/tests/head.js +++ b/browser/components/preferences/in-content/tests/head.js @@ -136,7 +136,7 @@ function openPreferencesViaOpenPreferencesAPI(aPane, aAdvancedTab, aOptions) { let selectedAdvancedTab = aAdvancedTab && doc.getElementById("advancedPrefs").selectedTab.id; if (!aOptions || !aOptions.leaveOpen) gBrowser.removeCurrentTab(); - deferred.resolve({selectedPane, selectedAdvancedTab}); + deferred.resolve({selectedPane: selectedPane, selectedAdvancedTab: selectedAdvancedTab}); }); }, true); diff --git a/browser/components/preferences/languages.js b/browser/components/preferences/languages.js index 2be9ddfbced2..677892b942ff 100644 --- a/browser/components/preferences/languages.js +++ b/browser/components/preferences/languages.js @@ -10,7 +10,7 @@ var gLanguagesDialog = { _selectedItemID : null, - init() + init: function() { if (!this._availableLanguagesList.length) this._loadAvailableLanguages(); @@ -18,7 +18,7 @@ var gLanguagesDialog = { // Ugly hack used to trigger extra reflow in order to work around XUL bug 1194844; // see bug 1194346. - forceReflow() + forceReflow: function() { this._activeLanguages.style.fontKerning = "none"; setTimeout("gLanguagesDialog._activeLanguages.style.removeProperty('font-kerning')", 0); @@ -34,7 +34,7 @@ var gLanguagesDialog = { return document.getElementById("availableLanguages"); }, - _loadAvailableLanguages() + _loadAvailableLanguages: function() { // This is a parser for: resource://gre/res/language.properties // The file is formatted like so: @@ -102,7 +102,7 @@ var gLanguagesDialog = { this._buildAvailableLanguageList(); }, - _buildAvailableLanguageList() + _buildAvailableLanguageList: function() { var availableLanguagesPopup = document.getElementById("availableLanguagesPopup"); while (availableLanguagesPopup.hasChildNodes()) @@ -126,7 +126,7 @@ var gLanguagesDialog = { } }, - readAcceptLanguages() + readAcceptLanguages: function() { while (this._activeLanguages.hasChildNodes()) this._activeLanguages.removeChild(this._activeLanguages.firstChild); @@ -160,12 +160,12 @@ var gLanguagesDialog = { return undefined; }, - writeAcceptLanguages() + writeAcceptLanguages: function() { return undefined; }, - onAvailableLanguageSelect() + onAvailableLanguageSelect: function() { var addButton = document.getElementById("addButton"); addButton.disabled = false; @@ -173,7 +173,7 @@ var gLanguagesDialog = { this._availableLanguages.removeAttribute("accesskey"); }, - addLanguage() + addLanguage: function() { var selectedID = this._availableLanguages.selectedItem.id; var preference = document.getElementById("intl.accept_languages"); @@ -201,7 +201,7 @@ var gLanguagesDialog = { this._availableLanguages.setAttribute("label", this._availableLanguages.getAttribute("label2")); }, - removeLanguage() + removeLanguage: function() { // Build the new preference value string. var languagesArray = []; @@ -229,7 +229,7 @@ var gLanguagesDialog = { this._buildAvailableLanguageList(); }, - _getLanguageName(aABCD) + _getLanguageName: function(aABCD) { if (!this._availableLanguagesList.length) this._loadAvailableLanguages(); @@ -240,7 +240,7 @@ var gLanguagesDialog = { return ""; }, - moveUp() + moveUp: function() { var selectedItem = this._activeLanguages.selectedItems[0]; var previousItem = selectedItem.previousSibling; @@ -264,7 +264,7 @@ var gLanguagesDialog = { preference.value = string; }, - moveDown() + moveDown: function() { var selectedItem = this._activeLanguages.selectedItems[0]; var nextItem = selectedItem.nextSibling; @@ -288,7 +288,7 @@ var gLanguagesDialog = { preference.value = string; }, - onLanguageSelect() + onLanguageSelect: function() { var upButton = document.getElementById("up"); var downButton = document.getElementById("down"); diff --git a/browser/components/preferences/permissions.js b/browser/components/preferences/permissions.js index 40469cdacf2a..43a7c02dee71 100644 --- a/browser/components/preferences/permissions.js +++ b/browser/components/preferences/permissions.js @@ -32,7 +32,7 @@ var gPermissionManager = { { return this._rowCount; }, - getCellText(aRow, aColumn) + getCellText: function(aRow, aColumn) { if (aColumn.id == "siteCol") return gPermissionManager._permissions[aRow].origin; @@ -41,17 +41,17 @@ var gPermissionManager = { return ""; }, - isSeparator(aIndex) { return false; }, - isSorted() { return false; }, - isContainer(aIndex) { return false; }, - setTree(aTree) {}, - getImageSrc(aRow, aColumn) {}, - getProgressMode(aRow, aColumn) {}, - getCellValue(aRow, aColumn) {}, - cycleHeader(column) {}, - getRowProperties(row) { return ""; }, - getColumnProperties(column) { return ""; }, - getCellProperties(row, column) { + isSeparator: function(aIndex) { return false; }, + isSorted: function() { return false; }, + isContainer: function(aIndex) { return false; }, + setTree: function(aTree) {}, + getImageSrc: function(aRow, aColumn) {}, + getProgressMode: function(aRow, aColumn) {}, + getCellValue: function(aRow, aColumn) {}, + cycleHeader: function(column) {}, + getRowProperties: function(row) { return ""; }, + getColumnProperties: function(column) { return ""; }, + getCellProperties: function(row, column) { if (column.element.getAttribute("id") == "siteCol") return "ltr"; @@ -59,7 +59,7 @@ var gPermissionManager = { } }, - _getCapabilityString(aCapability) + _getCapabilityString: function(aCapability) { var stringKey = null; switch (aCapability) { @@ -79,7 +79,7 @@ var gPermissionManager = { return this._bundle.getString(stringKey); }, - addPermission(aCapability) + addPermission: function(aCapability) { var textbox = document.getElementById("url"); var input_url = textbox.value.replace(/^\s*/, ""); // trim any leading space @@ -127,7 +127,7 @@ var gPermissionManager = { } } - let permissionParams = {principal, type: this._type, capability: aCapability}; + let permissionParams = {principal: principal, type: this._type, capability: aCapability}; if (!permissionExists) { this._permissionsToAdd.set(principal.origin, permissionParams); this._addPermission(permissionParams); @@ -147,7 +147,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = this._permissions.length == 0; }, - _removePermission(aPermission) + _removePermission: function(aPermission) { this._removePermissionFromList(aPermission.principal); @@ -162,7 +162,7 @@ var gPermissionManager = { }, - _handleCapabilityChange() + _handleCapabilityChange: function() { // Re-do the sort, if the status changed from Block to Allow // or vice versa, since if we're sorted on status, we may no @@ -173,7 +173,7 @@ var gPermissionManager = { this._tree.treeBoxObject.invalidate(); }, - _addPermission(aPermission) + _addPermission: function(aPermission) { this._addPermissionToList(aPermission); ++this._view._rowCount; @@ -182,7 +182,7 @@ var gPermissionManager = { this._resortPermissions(); }, - _resortPermissions() + _resortPermissions: function() { gTreeUtils.sort(this._tree, this._view, this._permissions, this._lastPermissionSortColumn, @@ -191,33 +191,33 @@ var gPermissionManager = { !this._lastPermissionSortAscending); // keep sort direction }, - onHostInput(aSiteField) + onHostInput: function(aSiteField) { document.getElementById("btnSession").disabled = !aSiteField.value; document.getElementById("btnBlock").disabled = !aSiteField.value; document.getElementById("btnAllow").disabled = !aSiteField.value; }, - onWindowKeyPress(aEvent) + onWindowKeyPress: function(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); }, - onHostKeyPress(aEvent) + onHostKeyPress: function(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN) document.getElementById("btnAllow").click(); }, - onLoad() + onLoad: function() { this._bundle = document.getElementById("bundlePreferences"); var params = window.arguments[0]; this.init(params); }, - init(aParams) + init: function(aParams) { if (this._type) { // reusing an open dialog, clear the old observer @@ -275,7 +275,7 @@ var gPermissionManager = { urlField.focus(); }, - uninit() + uninit: function() { if (!this._observerRemoved) { Services.obs.removeObserver(this, "perm-changed"); @@ -284,7 +284,7 @@ var gPermissionManager = { } }, - observe(aSubject, aTopic, aData) + observe: function(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { var permission = aSubject.QueryInterface(Components.interfaces.nsIPermission); @@ -311,7 +311,7 @@ var gPermissionManager = { } }, - onPermissionSelected() + onPermissionSelected: function() { var hasSelection = this._tree.view.selection.count > 0; var hasRows = this._tree.view.rowCount > 0; @@ -319,7 +319,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = !hasRows; }, - onPermissionDeleted() + onPermissionDeleted: function() { if (!this._view.rowCount) return; @@ -333,7 +333,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = !this._permissions.length; }, - onAllPermissionsDeleted() + onAllPermissionsDeleted: function() { if (!this._view.rowCount) return; @@ -347,7 +347,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = true; }, - onPermissionKeyPress(aEvent) + onPermissionKeyPress: function(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) { this.onPermissionDeleted(); @@ -359,13 +359,13 @@ var gPermissionManager = { _lastPermissionSortColumn: "", _lastPermissionSortAscending: false, - _permissionsComparator(a, b) + _permissionsComparator : function(a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }, - onPermissionSort(aColumn) + onPermissionSort: function(aColumn) { this._lastPermissionSortAscending = gTreeUtils.sort(this._tree, this._view, @@ -377,7 +377,7 @@ var gPermissionManager = { this._lastPermissionSortColumn = aColumn; }, - onApplyChanges() + onApplyChanges: function() { // Stop observing permission changes since we are about // to write out the pending adds/deletes and don't need @@ -395,7 +395,7 @@ var gPermissionManager = { window.close(); }, - _loadPermissions() + _loadPermissions: function() { this._tree = document.getElementById("permissionsTree"); this._permissions = []; @@ -417,7 +417,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = this._permissions.length == 0; }, - _addPermissionToList(aPermission) + _addPermissionToList: function(aPermission) { if (aPermission.type == this._type && (!this._manageCapability || @@ -432,7 +432,7 @@ var gPermissionManager = { } }, - _removePermissionFromList(aPrincipal) + _removePermissionFromList: function(aPrincipal) { for (let i = 0; i < this._permissions.length; ++i) { if (this._permissions[i].principal.equals(aPrincipal)) { @@ -445,7 +445,7 @@ var gPermissionManager = { } }, - setOrigin(aOrigin) + setOrigin: function(aOrigin) { document.getElementById("url").value = aOrigin; } diff --git a/browser/components/preferences/sanitize.js b/browser/components/preferences/sanitize.js index cf764086db98..a9beea163d92 100644 --- a/browser/components/preferences/sanitize.js +++ b/browser/components/preferences/sanitize.js @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gSanitizeDialog = Object.freeze({ - init() { + init: function() { let customWidthElements = document.getElementsByAttribute("dialogWidth", "*"); let isInSubdialog = document.documentElement.hasAttribute("subdialog"); for (let element of customWidthElements) { @@ -13,7 +13,7 @@ var gSanitizeDialog = Object.freeze({ this.onClearHistoryChanged(); }, - onClearHistoryChanged() { + onClearHistoryChanged: function() { let downloadsPref = document.getElementById("privacy.clearOnShutdown.downloads"); let historyPref = document.getElementById("privacy.clearOnShutdown.history"); downloadsPref.value = historyPref.value; diff --git a/browser/components/preferences/translation.js b/browser/components/preferences/translation.js index 82dd0e7bfedf..0c7d86ff3165 100644 --- a/browser/components/preferences/translation.js +++ b/browser/components/preferences/translation.js @@ -33,7 +33,7 @@ Tree.prototype = { get hasSelection() { return this.selection.count > 0; }, - getSelectedItems() { + getSelectedItems: function() { let result = []; let rc = this.selection.getRangeCount(); @@ -51,30 +51,30 @@ Tree.prototype = { get rowCount() { return this._data.length; }, - getCellText(aRow, aColumn) { + getCellText: function(aRow, aColumn) { return this._data[aRow]; }, - isSeparator(aIndex) { + isSeparator: function(aIndex) { return false; }, - isSorted() { + isSorted: function() { return false; }, - isContainer(aIndex) { + isContainer: function(aIndex) { return false; }, - setTree(aTree) {}, - getImageSrc(aRow, aColumn) {}, - getProgressMode(aRow, aColumn) {}, - getCellValue(aRow, aColumn) {}, - cycleHeader(column) {}, - getRowProperties(row) { + setTree: function(aTree) {}, + getImageSrc: function(aRow, aColumn) {}, + getProgressMode: function(aRow, aColumn) {}, + getCellValue: function(aRow, aColumn) {}, + cycleHeader: function(column) {}, + getRowProperties: function(row) { return ""; }, - getColumnProperties(column) { + getColumnProperties: function(column) { return ""; }, - getCellProperties(row, column) { + getCellProperties: function(row, column) { return ""; }, QueryInterface: XPCOMUtils.generateQI([Ci.nsITreeView]) @@ -87,13 +87,13 @@ function Lang(aCode) } Lang.prototype = { - toString() { + toString: function() { return this._label; } } var gTranslationExceptions = { - onLoad() { + onLoad: function() { if (this._siteTree) { // Re-using an open dialog, clear the old observers. this.uninit(); @@ -123,7 +123,7 @@ var gTranslationExceptions = { }, // Get the list of languages we don't translate as an array. - getLanguageExceptions() { + getLanguageExceptions: function() { let langs = Services.prefs.getCharPref(kLanguagesPref); if (!langs) return []; @@ -134,7 +134,7 @@ var gTranslationExceptions = { return result; }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { if (aData == "cleared") { if (!this._sites.length) @@ -180,22 +180,22 @@ var gTranslationExceptions = { } }, - _handleButtonDisabling(aTree, aIdPart) { + _handleButtonDisabling: function(aTree, aIdPart) { let empty = aTree.isEmpty; document.getElementById("removeAll" + aIdPart + "s").disabled = empty; document.getElementById("remove" + aIdPart).disabled = empty || !aTree.hasSelection; }, - onLanguageSelected() { + onLanguageSelected: function() { this._handleButtonDisabling(this._langTree, "Language"); }, - onSiteSelected() { + onSiteSelected: function() { this._handleButtonDisabling(this._siteTree, "Site"); }, - onLanguageDeleted() { + onLanguageDeleted: function() { let langs = Services.prefs.getCharPref(kLanguagesPref); if (!langs) return; @@ -206,11 +206,11 @@ var gTranslationExceptions = { Services.prefs.setCharPref(kLanguagesPref, langs.join(",")); }, - onAllLanguagesDeleted() { + onAllLanguagesDeleted: function() { Services.prefs.setCharPref(kLanguagesPref, ""); }, - onSiteDeleted() { + onSiteDeleted: function() { let removedSites = this._siteTree.getSelectedItems(); for (let origin of removedSites) { let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(origin); @@ -218,7 +218,7 @@ var gTranslationExceptions = { } }, - onAllSitesDeleted() { + onAllSitesDeleted: function() { if (this._siteTree.isEmpty) return; @@ -233,22 +233,22 @@ var gTranslationExceptions = { this.onSiteSelected(); }, - onSiteKeyPress(aEvent) { + onSiteKeyPress: function(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) this.onSiteDeleted(); }, - onLanguageKeyPress(aEvent) { + onLanguageKeyPress: function(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) this.onLanguageDeleted(); }, - onWindowKeyPress(aEvent) { + onWindowKeyPress: function(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); }, - uninit() { + uninit: function() { Services.obs.removeObserver(this, "perm-changed"); Services.prefs.removeObserver(kLanguagesPref, this); } diff --git a/browser/components/search/content/search.xml b/browser/components/search/content/search.xml index 23f310e9c5b5..9799adf65797 100644 --- a/browser/components/search/content/search.xml +++ b/browser/components/search/content/search.xml @@ -426,7 +426,7 @@ { op : "bump", fieldname : textBox.getAttribute("autocompletesearchparam"), value : aData }, - { handleError(aError) { + { handleError : function(aError) { Components.utils.reportError("Saving search to form history failed: " + aError.message); }}); } @@ -499,7 +499,7 @@ { this._rebuild(); }, - onError(errorCode) { + onError: function(errorCode) { if (errorCode != Ci.nsISearchInstallCallback.ERROR_DUPLICATE_ENGINE) { // Download error is shown by the search service return; diff --git a/browser/components/search/test/browser_426329.js b/browser/components/search/test/browser_426329.js index 259705b4c26a..d9cbd3f7a9b9 100644 --- a/browser/components/search/test/browser_426329.js +++ b/browser/components/search/test/browser_426329.js @@ -47,11 +47,11 @@ function getMenuEntries() { function countEntries(name, value) { return new Promise(resolve => { let count = 0; - let obj = name && value ? {fieldname: name, value} : {}; + let obj = name && value ? {fieldname: name, value: value} : {}; FormHistory.count(obj, - { handleResult(result) { count = result; }, - handleError(error) { throw error; }, - handleCompletion(reason) { + { handleResult: function(result) { count = result; }, + handleError: function(error) { throw error; }, + handleCompletion: function(reason) { if (!reason) { resolve(count); } diff --git a/browser/components/search/test/browser_aboutSearchReset.js b/browser/components/search/test/browser_aboutSearchReset.js index 6001c274af37..75b591077695 100644 --- a/browser/components/search/test/browser_aboutSearchReset.js +++ b/browser/components/search/test/browser_aboutSearchReset.js @@ -49,7 +49,7 @@ var gTests = [ { desc: "Test the 'Keep Current Settings' button.", - *run() { + run: function* () { let engine = yield promiseNewEngine(kTestEngine, {setAsCurrent: true}); let expectedURL = engine. @@ -75,7 +75,7 @@ var gTests = [ { desc: "Test the 'Restore Search Defaults' button.", - *run() { + run: function* () { let currentEngine = Services.search.currentEngine; let originalEngine = Services.search.originalDefaultEngine; let doc = gBrowser.contentDocument; @@ -103,7 +103,7 @@ var gTests = [ { desc: "Click the settings link.", - *run() { + run: function* () { let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, "about:preferences#search") @@ -116,7 +116,7 @@ var gTests = [ { desc: "Load another page without clicking any of the buttons.", - *run() { + run: function* () { yield promiseTabLoadEvent(gBrowser.selectedTab, "about:mozilla"); checkTelemetryRecords(TELEMETRY_RESULT_ENUM.CLOSED_PAGE); diff --git a/browser/components/search/test/browser_abouthome_behavior.js b/browser/components/search/test/browser_abouthome_behavior.js index 5a19ffc6c1eb..e7d062e65e46 100644 --- a/browser/components/search/test/browser_abouthome_behavior.js +++ b/browser/components/search/test/browser_abouthome_behavior.js @@ -64,28 +64,28 @@ function test() { { name: "Search with Bing from about:home", searchURL: replaceUrl("http://www.bing.com/search?q=foo&pc=MOZI&form=MOZSPG"), - run() { + run: function() { verify_about_home_search("Bing"); } }, { name: "Search with Yahoo from about:home", searchURL: replaceUrl("https://search.yahoo.com/search?p=foo&ei=UTF-8&fr=moz35"), - run() { + run: function() { verify_about_home_search("Yahoo"); } }, { name: "Search with Google from about:home", searchURL: replaceUrl("https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8"), - run() { + run: function() { verify_about_home_search("Google"); } }, { name: "Search with Amazon.com from about:home", searchURL: replaceUrl("https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&mode=blended&tag=mozilla-20&sourceid=Mozilla-search"), - run() { + run: function() { verify_about_home_search("Amazon.com"); } } diff --git a/browser/components/search/test/browser_addEngine.js b/browser/components/search/test/browser_addEngine.js index 798c4e9f7294..512b2dd558ab 100644 --- a/browser/components/search/test/browser_addEngine.js +++ b/browser/components/search/test/browser_addEngine.js @@ -46,14 +46,14 @@ var gTests = [ description: "Foo Search", searchForm: "http://mochi.test:8888/browser/browser/components/search/test/" }, - run() { + run: function() { Services.obs.addObserver(observer, "browser-search-engine-modified", false); gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml", null, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC", false); }, - added(engine) { + added: function(engine) { ok(engine, "engine was added."); checkEngine(this.engine, engine); @@ -66,14 +66,14 @@ var gTests = [ gSS.currentEngine = engine; }, - current(engine) { + current: function(engine) { let currentEngine = gSS.currentEngine; is(engine, currentEngine, "engine is current"); is(engine.name, this.engine.name, "current engine was changed successfully"); gSS.removeEngine(engine); }, - removed(engine) { + removed: function(engine) { // Remove the observer before calling the currentEngine getter, // as that getter will set the currentEngine to the original default // which will trigger a notification causing the test to loop over all diff --git a/browser/components/search/test/browser_amazon_behavior.js b/browser/components/search/test/browser_amazon_behavior.js index d695939c6375..55695e11e862 100644 --- a/browser/components/search/test/browser_amazon_behavior.js +++ b/browser/components/search/test/browser_amazon_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base, - run() { + run: function() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base, - run() { + run: function() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search", searchURL: base, - run() { + run: function() { gURLBar.value = "a foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base, - run() { + run: function() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base, - run() { + run: function() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_bing_behavior.js b/browser/components/search/test/browser_bing_behavior.js index 7011fe41dc59..5087bd182004 100644 --- a/browser/components/search/test/browser_bing_behavior.js +++ b/browser/components/search/test/browser_bing_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base + "&form=MOZCON", - run() { + run: function() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base + "&form=MOZLBR", - run() { + run: function() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search with alias", searchURL: base + "&form=MOZLBR", - run() { + run: function() { gURLBar.value = "b foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base + "&form=MOZSBR", - run() { + run: function() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base + "&form=MOZTSB", - run() { + run: function() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_google_behavior.js b/browser/components/search/test/browser_google_behavior.js index f75c86a830de..1f31b35d9d93 100644 --- a/browser/components/search/test/browser_google_behavior.js +++ b/browser/components/search/test/browser_google_behavior.js @@ -30,7 +30,7 @@ function test() { { name: "context menu search", searchURL: base, - run() { + run: function() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -39,7 +39,7 @@ function test() { { name: "keyword search", searchURL: base, - run() { + run: function() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -48,7 +48,7 @@ function test() { { name: "keyword search", searchURL: base, - run() { + run: function() { gURLBar.value = "g foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -57,7 +57,7 @@ function test() { { name: "search bar search", searchURL: base, - run() { + run: function() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -70,7 +70,7 @@ function test() { { name: "new tab search", searchURL: base, - run() { + run: function() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js b/browser/components/search/test/browser_hiddenOneOffs_cleanup.js index 34c7eca17656..7bbcd523dbb3 100644 --- a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js +++ b/browser/components/search/test/browser_hiddenOneOffs_cleanup.js @@ -7,14 +7,14 @@ function promiseNewEngine(basename) { return new Promise((resolve, reject) => { info("Waiting for engine to be added: " + basename); Services.search.init({ - onInitComplete() { + onInitComplete: function() { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess(engine) { + onSuccess: function(engine) { info("Search engine added: " + basename); resolve(engine); }, - onError(errCode) { + onError: function(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); } diff --git a/browser/components/search/test/browser_searchbar_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_keyboard_navigation.js index 7e0602cf034f..26b8939c7d07 100644 --- a/browser/components/search/test/browser_searchbar_keyboard_navigation.js +++ b/browser/components/search/test/browser_searchbar_keyboard_navigation.js @@ -37,16 +37,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value} + value: value} }); searchbar.FormHistory.update(addOps, { - handleCompletion() { + handleCompletion: function() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value} + value: value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_searchbar_openpopup.js b/browser/components/search/test/browser_searchbar_openpopup.js index 939ac9941894..df2a45e539c4 100644 --- a/browser/components/search/test/browser_searchbar_openpopup.js +++ b/browser/components/search/test/browser_searchbar_openpopup.js @@ -58,16 +58,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value} + value: value} }); searchbar.FormHistory.update(addOps, { - handleCompletion() { + handleCompletion: function() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value} + value: value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js index 9ad747f76812..e5e613971617 100644 --- a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js +++ b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js @@ -38,16 +38,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value} + value: value} }); searchbar.FormHistory.update(addOps, { - handleCompletion() { + handleCompletion: function() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value} + value: value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_webapi.js b/browser/components/search/test/browser_webapi.js index 4016484c31f9..d8161ffbe528 100644 --- a/browser/components/search/test/browser_webapi.js +++ b/browser/components/search/test/browser_webapi.js @@ -14,7 +14,7 @@ function AddSearchProvider(...args) { function promiseDialogOpened() { return new Promise((resolve, reject) => { Services.wm.addListener({ - onOpenWindow(xulWin) { + onOpenWindow: function(xulWin) { Services.wm.removeListener(this); let win = xulWin.QueryInterface(Ci.nsIInterfaceRequestor) diff --git a/browser/components/search/test/browser_yahoo_behavior.js b/browser/components/search/test/browser_yahoo_behavior.js index ec4d85d3adc4..5f182971f7f3 100644 --- a/browser/components/search/test/browser_yahoo_behavior.js +++ b/browser/components/search/test/browser_yahoo_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base + "&hsimp=yhs-005", - run() { + run: function() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base + "&hsimp=yhs-002", - run() { + run: function() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search with alias", searchURL: base + "&hsimp=yhs-002", - run() { + run: function() { gURLBar.value = "y foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base + "&hsimp=yhs-001", - run() { + run: function() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base + "&hsimp=yhs-004", - run() { + run: function() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/head.js b/browser/components/search/test/head.js index 318dd54c7897..5fb4fe02cf02 100644 --- a/browser/components/search/test/head.js +++ b/browser/components/search/test/head.js @@ -58,11 +58,11 @@ function promiseNewEngine(basename, options = {}) { options.setAsCurrent == undefined ? true : options.setAsCurrent; info("Waiting for engine to be added: " + basename); Services.search.init({ - onInitComplete() { + onInitComplete: function() { let url = getRootDirectory(gTestPath) + basename; let current = Services.search.currentEngine; Services.search.addEngine(url, null, options.iconURL || "", false, { - onSuccess(engine) { + onSuccess: function(engine) { info("Search engine added: " + basename); if (setAsCurrent) { Services.search.currentEngine = engine; @@ -76,7 +76,7 @@ function promiseNewEngine(basename, options = {}) { }); resolve(engine); }, - onError(errCode) { + onError: function(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); } diff --git a/browser/components/selfsupport/SelfSupportService.js b/browser/components/selfsupport/SelfSupportService.js index 38904cdfd395..bdde07a2f43f 100644 --- a/browser/components/selfsupport/SelfSupportService.js +++ b/browser/components/selfsupport/SelfSupportService.js @@ -30,7 +30,7 @@ MozSelfSupportInterface.prototype = { _window: null, - init(window) { + init: function(window) { this._window = window; }, @@ -42,34 +42,34 @@ MozSelfSupportInterface.prototype = { Preferences.set(PREF_FHR_UPLOAD_ENABLED, enabled); }, - resetPref(name) { + resetPref: function(name) { Services.prefs.clearUserPref(name); }, - resetSearchEngines() { + resetSearchEngines: function() { Services.search.restoreDefaultEngines(); Services.search.resetToOriginalDefaultEngine(); }, - getTelemetryPingList() { + getTelemetryPingList: function() { return this._wrapPromise(TelemetryArchive.promiseArchivedPingList()); }, - getTelemetryPing(pingId) { + getTelemetryPing: function(pingId) { return this._wrapPromise(TelemetryArchive.promiseArchivedPingById(pingId)); }, - getCurrentTelemetryEnvironment() { + getCurrentTelemetryEnvironment: function() { const current = TelemetryEnvironment.currentEnvironment; return new this._window.Promise(resolve => resolve(current)); }, - getCurrentTelemetrySubsessionPing() { + getCurrentTelemetrySubsessionPing: function() { const current = TelemetryController.getCurrentPingData(true); return new this._window.Promise(resolve => resolve(current)); }, - _wrapPromise(promise) { + _wrapPromise: function(promise) { return new this._window.Promise( (resolve, reject) => promise.then(resolve, reject)); }, diff --git a/browser/components/shell/content/setDesktopBackground.js b/browser/components/shell/content/setDesktopBackground.js index e23cd912e68b..094c34aa56da 100644 --- a/browser/components/shell/content/setDesktopBackground.js +++ b/browser/components/shell/content/setDesktopBackground.js @@ -20,7 +20,7 @@ var gSetBackground = { .getService(Ci.nsIShellService); }, - load() + load: function() { this._canvas = document.getElementById("screen"); this._screenWidth = screen.width; @@ -49,7 +49,7 @@ var gSetBackground = { }, 0, this); }, - init(aImage) + init: function(aImage) { this._image = aImage; @@ -76,7 +76,7 @@ var gSetBackground = { this.updatePosition(); }, - setDesktopBackground() + setDesktopBackground: function() { if (AppConstants.platform != "macosx") { document.persist("menuPosition", "value"); @@ -95,7 +95,7 @@ var gSetBackground = { Ci.nsIShellService["BACKGROUND_" + this._position]); }, - updatePosition() + updatePosition: function() { var ctx = this._canvas.getContext("2d"); ctx.clearRect(0, 0, this._screenWidth, this._screenHeight); diff --git a/browser/components/syncedtabs/SyncedTabsDeckComponent.js b/browser/components/syncedtabs/SyncedTabsDeckComponent.js index bdad78e43e32..dfbec056ca0b 100644 --- a/browser/components/syncedtabs/SyncedTabsDeckComponent.js +++ b/browser/components/syncedtabs/SyncedTabsDeckComponent.js @@ -49,7 +49,7 @@ function SyncedTabsDeckComponent({ window: this._window, store: this._syncedTabsListStore, View: TabListView, - SyncedTabs, + SyncedTabs: SyncedTabs, clipboardHelper: Cc["@mozilla.org/widget/clipboardhelper;1"] .getService(Ci.nsIClipboardHelper), getChromeWindow: this._getChromeWindow, diff --git a/browser/components/syncedtabs/SyncedTabsDeckStore.js b/browser/components/syncedtabs/SyncedTabsDeckStore.js index eef594a51956..ede6914c8302 100644 --- a/browser/components/syncedtabs/SyncedTabsDeckStore.js +++ b/browser/components/syncedtabs/SyncedTabsDeckStore.js @@ -31,7 +31,7 @@ Object.assign(SyncedTabsDeckStore.prototype, EventEmitter.prototype, { let panels = this._panels.map(panel => { return {id: panel, selected: panel === this._selectedPanel}; }); - this.emit("change", {panels, isUpdatable}); + this.emit("change", {panels, isUpdatable: isUpdatable}); }, /** diff --git a/browser/components/syncedtabs/test/xpcshell/head.js b/browser/components/syncedtabs/test/xpcshell/head.js index 17590109b6b4..af0458ea6e8b 100644 --- a/browser/components/syncedtabs/test/xpcshell/head.js +++ b/browser/components/syncedtabs/test/xpcshell/head.js @@ -15,9 +15,9 @@ do_get_profile(); // fxa needs a profile directory for storage. let window = { document: {}, location: {}, - setTimeout, - setInterval, - clearTimeout, + setTimeout: setTimeout, + setInterval: setInterval, + clearTimeout: clearTimeout, clearinterval: clearInterval }; let self = window; diff --git a/browser/components/tests/browser/browser_bug538331.js b/browser/components/tests/browser/browser_bug538331.js index 1665163633fc..fc1003413b50 100644 --- a/browser/components/tests/browser/browser_bug538331.js +++ b/browser/components/tests/browser/browser_bug538331.js @@ -135,11 +135,11 @@ function test() var gWindowCatcher = { windowsOpen: 0, finishCalled: false, - start() { + start: function() { Services.ww.registerNotification(this); }, - finish(aFunc) { + finish: function(aFunc) { Services.ww.unregisterNotification(this); this.finishFunc = aFunc; if (this.windowsOpen > 0) @@ -148,7 +148,7 @@ var gWindowCatcher = { this.finishFunc(); }, - closeWindow(win) { + closeWindow: function(win) { info("window catcher closing window: " + win.document.documentURI); win.close(); this.windowsOpen--; @@ -157,11 +157,11 @@ var gWindowCatcher = { } }, - windowLoad(win) { + windowLoad: function(win) { executeSoon(this.closeWindow.bind(this, win)); }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { if (topic != "domwindowopened") return; diff --git a/browser/components/tests/unit/test_distribution.js b/browser/components/tests/unit/test_distribution.js index 83255a083356..86f4c40665cd 100644 --- a/browser/components/tests/unit/test_distribution.js +++ b/browser/components/tests/unit/test_distribution.js @@ -46,7 +46,7 @@ function installDistributionEngine() { do_get_file("data/engine-de-DE.xml").copyTo(localeDir, "engine-de-DE.xml"); Services.dirsvc.registerProvider({ - getFile(aProp, aPersistent) { + getFile: function(aProp, aPersistent) { aPersistent.value = true; if (aProp == XRE_APP_DISTRIBUTION_DIR) return distDir.clone(); diff --git a/browser/components/translation/BingTranslator.jsm b/browser/components/translation/BingTranslator.jsm index cdaec46ff9ef..fc1cc942a14a 100644 --- a/browser/components/translation/BingTranslator.jsm +++ b/browser/components/translation/BingTranslator.jsm @@ -58,7 +58,7 @@ this.BingTranslator.prototype = { * @returns {Promise} A promise that will resolve when the translation * task is finished. */ - translate() { + translate: function() { return Task.spawn(function *() { let currentIndex = 0; this._onFinishedDeferred = Promise.defer(); @@ -98,7 +98,7 @@ this.BingTranslator.prototype = { * Resets the expiration time of the current token, in order to * force the token manager to ask for a new token during the next request. */ - _resetToken() { + _resetToken : function() { // Force the token manager to get update token BingTokenManager._currentExpiryTime = 0; }, @@ -111,7 +111,7 @@ this.BingTranslator.prototype = { * * @param request The BingRequest sent to the server. */ - _chunkCompleted(bingRequest) { + _chunkCompleted: function(bingRequest) { if (this._parseChunkResult(bingRequest)) { this._partialSuccess = true; // Count the number of characters successfully translated. @@ -131,7 +131,7 @@ this.BingTranslator.prototype = { * * @param aError [optional] The XHR object of the request that failed. */ - _chunkFailed(aError) { + _chunkFailed: function(aError) { if (aError instanceof Ci.nsIXMLHttpRequest && [400, 401].indexOf(aError.status) != -1) { let body = aError.responseText; @@ -148,7 +148,7 @@ this.BingTranslator.prototype = { * This function handles resolving the promise * returned by the public `translate()` method when all chunks are completed. */ - _checkIfFinished() { + _checkIfFinished: function() { // Check if all pending requests have been // completed and then resolves the promise. // If at least one chunk was successful, the @@ -177,7 +177,7 @@ this.BingTranslator.prototype = { * @param request The request sent to the server. * @returns boolean True if parsing of this chunk was successful. */ - _parseChunkResult(bingRequest) { + _parseChunkResult: function(bingRequest) { let results; try { let doc = bingRequest.networkRequest.responseXML; @@ -220,7 +220,7 @@ this.BingTranslator.prototype = { * @param startIndex What is the index, in the roots list, that the * chunk should start. */ - _generateNextTranslationRequest(startIndex) { + _generateNextTranslationRequest: function(startIndex) { let currentDataSize = 0; let currentChunks = 0; let output = []; @@ -285,7 +285,7 @@ BingRequest.prototype = { /** * Initiates the request */ - fireRequest() { + fireRequest: function() { return Task.spawn(function *() { // Prepare authentication. let token = yield BingTokenManager.getToken(); @@ -324,11 +324,11 @@ BingRequest.prototype = { onLoad: (function(responseText, xhr) { deferred.resolve(this); }).bind(this), - onError(e, responseText, xhr) { + onError: function(e, responseText, xhr) { deferred.reject(xhr); }, postData: requestString, - headers + headers: headers }; // Fire the request. @@ -358,7 +358,7 @@ var BingTokenManager = { * can be the same one used in the past if it is still * valid. */ - getToken() { + getToken: function() { if (this._pendingRequest) { return this._pendingRequest; } @@ -378,7 +378,7 @@ var BingTokenManager = { * @returns {Promise} A promise that resolves with the token * string once it is obtained. */ - _getNewToken() { + _getNewToken: function() { let url = getUrlParam("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13", "browser.translation.bing.authURL"); let params = [ @@ -392,7 +392,7 @@ var BingTokenManager = { let deferred = Promise.defer(); let options = { - onLoad(responseText, xhr) { + onLoad: function(responseText, xhr) { BingTokenManager._pendingRequest = null; try { let json = JSON.parse(responseText); @@ -411,7 +411,7 @@ var BingTokenManager = { deferred.reject(e); } }, - onError(e, responseText, xhr) { + onError: function(e, responseText, xhr) { BingTokenManager._pendingRequest = null; deferred.reject(e); }, diff --git a/browser/components/translation/LanguageDetector.jsm b/browser/components/translation/LanguageDetector.jsm index e75f777a1f26..a65d6eda124a 100644 --- a/browser/components/translation/LanguageDetector.jsm +++ b/browser/components/translation/LanguageDetector.jsm @@ -134,7 +134,7 @@ this.LanguageDetector = { * entry with the languge code 'un', indicating the percent of * the text which is unknown. */ - detectLanguage(aParams) { + detectLanguage: function(aParams) { if (typeof aParams == "string") aParams = { text: aParams }; diff --git a/browser/components/translation/Translation.jsm b/browser/components/translation/Translation.jsm index 9dc29930f58c..c2591b65ed67 100644 --- a/browser/components/translation/Translation.jsm +++ b/browser/components/translation/Translation.jsm @@ -41,7 +41,7 @@ this.Translation = { return this._defaultTargetLanguage; }, - documentStateReceived(aBrowser, aData) { + documentStateReceived: function(aBrowser, aData) { if (aData.state == this.STATE_OFFER) { if (aData.detectedLanguage == this.defaultTargetLanguage) { // Detected language is the same as the user's locale. @@ -78,7 +78,7 @@ this.Translation = { trUI.showTranslationInfoBar(); }, - openProviderAttribution() { + openProviderAttribution: function() { let attribution = this.supportedEngines[this.translationEngine]; Cu.import("resource:///modules/RecentWindow.jsm"); RecentWindow.getMostRecentBrowserWindow().openUILinkIn(attribution, "tab"); @@ -138,7 +138,7 @@ TranslationUI.prototype = { aBrowser.messageManager.addMessageListener("Translation:Finished", this); this._browser = aBrowser; }, - translate(aFrom, aTo) { + translate: function(aFrom, aTo) { if (aFrom == aTo || (this.state == Translation.STATE_TRANSLATED && this.translatedFrom == aFrom && this.translatedTo == aTo)) { @@ -166,7 +166,7 @@ TranslationUI.prototype = { ); }, - showURLBarIcon() { + showURLBarIcon: function() { let chromeWin = this.browser.ownerGlobal; let PopupNotifications = chromeWin.PopupNotifications; let removeId = this.originalShown ? "translated" : "translate"; @@ -214,14 +214,14 @@ TranslationUI.prototype = { }, originalShown: true, - showOriginalContent() { + showOriginalContent: function() { this.originalShown = true; this.showURLBarIcon(); this.browser.messageManager.sendAsyncMessage("Translation:ShowOriginal"); TranslationTelemetry.recordShowOriginalContent(); }, - showTranslatedContent() { + showTranslatedContent: function() { this.originalShown = false; this.showURLBarIcon(); this.browser.messageManager.sendAsyncMessage("Translation:ShowTranslation"); @@ -231,7 +231,7 @@ TranslationUI.prototype = { return this.browser.ownerGlobal.gBrowser.getNotificationBox(this.browser); }, - showTranslationInfoBar() { + showTranslationInfoBar: function() { let notificationBox = this.notificationBox; let notif = notificationBox.appendNotification("", "translation", null, notificationBox.PRIORITY_INFO_HIGH); @@ -239,7 +239,7 @@ TranslationUI.prototype = { return notif; }, - shouldShowInfoBar(aURI) { + shouldShowInfoBar: function(aURI) { // Never show the infobar automatically while the translation // service is temporarily unavailable. if (Translation.serviceUnavailable) @@ -263,7 +263,7 @@ TranslationUI.prototype = { return true; }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "Translation:Finished": if (msg.data.success) { @@ -284,7 +284,7 @@ TranslationUI.prototype = { } }, - infobarClosed() { + infobarClosed: function() { if (this.state == Translation.STATE_OFFER) TranslationTelemetry.recordDeniedTranslationOffer(); } @@ -298,7 +298,7 @@ TranslationUI.prototype = { */ this.TranslationTelemetry = { - init() { + init: function() { // Constructing histograms. const plain = (id) => Services.telemetry.getHistogramById(id); const keyed = (id) => Services.telemetry.getKeyedHistogramById(id); @@ -326,7 +326,7 @@ this.TranslationTelemetry = { * @param language * The language of the page. */ - recordTranslationOpportunity(language) { + recordTranslationOpportunity: function(language) { return this._recordOpportunity(language, true); }, @@ -337,7 +337,7 @@ this.TranslationTelemetry = { * @param language * The language of the page. */ - recordMissedTranslationOpportunity(language) { + recordMissedTranslationOpportunity: function(language) { return this._recordOpportunity(language, false); }, @@ -351,7 +351,7 @@ this.TranslationTelemetry = { * These translation opportunities should still be recorded in addition to * recording the automatic rejection of the offer. */ - recordAutoRejectedTranslationOffer() { + recordAutoRejectedTranslationOffer: function() { if (!this._canRecord) return; this.HISTOGRAMS.AUTO_REJECTED().add(); }, @@ -365,7 +365,7 @@ this.TranslationTelemetry = { * @param numCharacters * The number of characters that were translated */ - recordTranslation(langFrom, langTo, numCharacters) { + recordTranslation: function(langFrom, langTo, numCharacters) { if (!this._canRecord) return; this.HISTOGRAMS.PAGES().add(); this.HISTOGRAMS.PAGES_BY_LANG().add(langFrom + " -> " + langTo); @@ -384,7 +384,7 @@ this.TranslationTelemetry = { * the user has manually adjusted the detected language false should * be passed. */ - recordDetectedLanguageChange(beforeFirstTranslation) { + recordDetectedLanguageChange: function(beforeFirstTranslation) { if (!this._canRecord) return; this.HISTOGRAMS.DETECTION_CHANGES().add(beforeFirstTranslation); }, @@ -394,7 +394,7 @@ this.TranslationTelemetry = { * only be called when actually executing a translation, not every time the * user changes in the language in the UI. */ - recordTargetLanguageChange() { + recordTargetLanguageChange: function() { if (!this._canRecord) return; this.HISTOGRAMS.TARGET_CHANGES().add(); }, @@ -402,7 +402,7 @@ this.TranslationTelemetry = { /** * Record a denied translation offer. */ - recordDeniedTranslationOffer() { + recordDeniedTranslationOffer: function() { if (!this._canRecord) return; this.HISTOGRAMS.DENIED().add(); }, @@ -410,7 +410,7 @@ this.TranslationTelemetry = { /** * Record a "Show Original" command use. */ - recordShowOriginalContent() { + recordShowOriginalContent: function() { if (!this._canRecord) return; this.HISTOGRAMS.SHOW_ORIGINAL().add(); }, @@ -418,7 +418,7 @@ this.TranslationTelemetry = { /** * Record the state of translation preferences. */ - recordPreferences() { + recordPreferences: function() { if (!this._canRecord) return; if (Services.prefs.getBoolPref(TRANSLATION_PREF_SHOWUI)) { this.HISTOGRAMS.SHOW_UI().add(1); @@ -428,7 +428,7 @@ this.TranslationTelemetry = { } }, - _recordOpportunity(language, success) { + _recordOpportunity: function(language, success) { if (!this._canRecord) return; this.HISTOGRAMS.OPPORTUNITIES().add(success); this.HISTOGRAMS.OPPORTUNITIES_BY_LANG().add(language, success); @@ -438,7 +438,7 @@ this.TranslationTelemetry = { * A shortcut for reading the telemetry preference. * */ - _canRecord() { + _canRecord: function() { return Services.prefs.getBoolPref("toolkit.telemetry.enabled"); } }; diff --git a/browser/components/translation/TranslationContentHandler.jsm b/browser/components/translation/TranslationContentHandler.jsm index 62376d4aa5ed..3b0d59dddd40 100644 --- a/browser/components/translation/TranslationContentHandler.jsm +++ b/browser/components/translation/TranslationContentHandler.jsm @@ -31,7 +31,7 @@ this.TranslationContentHandler = function(global, docShell) { } TranslationContentHandler.prototype = { - handleEvent(aEvent) { + handleEvent: function(aEvent) { // We are only listening to pageshow events. let target = aEvent.target; @@ -61,7 +61,7 @@ TranslationContentHandler.prototype = { }, /* nsIWebProgressListener implementation */ - onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { if (!aWebProgress.isTopLevel || !(aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) || !this.global.content) @@ -108,15 +108,15 @@ TranslationContentHandler.prototype = { }, // Unused methods. - onProgressChange() {}, - onLocationChange() {}, - onStatusChange() {}, - onSecurityChange() {}, + onProgressChange: function() {}, + onLocationChange: function() {}, + onStatusChange: function() {}, + onSecurityChange: function() {}, QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference]), - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "Translation:TranslateDocument": { diff --git a/browser/components/translation/TranslationDocument.jsm b/browser/components/translation/TranslationDocument.jsm index c754251046bd..058d07a498cf 100644 --- a/browser/components/translation/TranslationDocument.jsm +++ b/browser/components/translation/TranslationDocument.jsm @@ -42,7 +42,7 @@ this.TranslationDocument.prototype = { * * @param document The document to be translated */ - _init(document) { + _init: function(document) { let window = document.defaultView; let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -94,7 +94,7 @@ this.TranslationDocument.prototype = { * * @returns A TranslationItem object. */ - _createItemForNode(node, id, isRoot) { + _createItemForNode: function(node, id, isRoot) { if (this.itemsMap.has(node)) { return this.itemsMap.get(node); } @@ -129,7 +129,7 @@ this.TranslationDocument.prototype = { * * @returns A string representation of the TranslationItem. */ - generateTextForItem(item) { + generateTextForItem: function(item) { if (item.original) { return regenerateTextFromOriginalHelper(item); } @@ -187,7 +187,7 @@ this.TranslationDocument.prototype = { * Changes the document to display its translated * content. */ - showTranslation() { + showTranslation: function() { this.originalShown = false; this._swapDocumentContent("translation"); }, @@ -196,7 +196,7 @@ this.TranslationDocument.prototype = { * Changes the document to display its original * content. */ - showOriginal() { + showOriginal: function() { this.originalShown = true; this._swapDocumentContent("original"); }, @@ -208,7 +208,7 @@ this.TranslationDocument.prototype = { * @param target A string that is either "translation" * or "original". */ - _swapDocumentContent(target) { + _swapDocumentContent: function(target) { Task.spawn(function *() { // Let the event loop breath on every 100 nodes // that are replaced. @@ -274,7 +274,7 @@ TranslationItem.prototype = { isRoot: false, isSimpleRoot: false, - toString() { + toString: function() { let rootType = ""; if (this.isRoot) { if (this.isSimpleRoot) { @@ -305,7 +305,7 @@ TranslationItem.prototype = { * @param result A string with the textual result received from the server, * which can be plain-text or a serialized HTML doc. */ - parseResult(result) { + parseResult: function(result) { if (this.isSimpleRoot) { this.translation = [result]; return; @@ -325,7 +325,7 @@ TranslationItem.prototype = { * @returns A TranslationItem with the given id, or null if * it was not found. */ - getChildById(id) { + getChildById: function(id) { for (let child of this.children) { if (("n" + child.id) == id) { return child; @@ -341,7 +341,7 @@ TranslationItem.prototype = { * @param target A string that is either "translation" * or "original". */ - swapText(target) { + swapText: function(target) { swapTextForItem(this, target); } }; @@ -354,7 +354,7 @@ TranslationItem.prototype = { * for correct positioning and spliting of text nodes. */ const TranslationItem_NodePlaceholder = { - toString() { + toString: function() { return "[object TranslationItem_NodePlaceholder]"; } }; diff --git a/browser/components/translation/YandexTranslator.jsm b/browser/components/translation/YandexTranslator.jsm index 11206d91d48a..ab92e09625c9 100644 --- a/browser/components/translation/YandexTranslator.jsm +++ b/browser/components/translation/YandexTranslator.jsm @@ -76,7 +76,7 @@ this.YandexTranslator.prototype = { * @returns {Promise} A promise that will resolve when the translation * task is finished. */ - translate() { + translate: function() { return Task.spawn(function *() { let currentIndex = 0; this._onFinishedDeferred = Promise.defer(); @@ -120,7 +120,7 @@ this.YandexTranslator.prototype = { * * @param request The YandexRequest sent to the server */ - _chunkCompleted(yandexRequest) { + _chunkCompleted: function(yandexRequest) { if (this._parseChunkResult(yandexRequest)) { this._partialSuccess = true; // Count the number of characters successfully translated. @@ -140,7 +140,7 @@ this.YandexTranslator.prototype = { * * @param aError [optional] The XHR object of the request that failed. */ - _chunkFailed(aError) { + _chunkFailed: function(aError) { if (aError instanceof Ci.nsIXMLHttpRequest) { let body = aError.responseText; let json = { code: 0 }; @@ -160,7 +160,7 @@ this.YandexTranslator.prototype = { * This function handles resolving the promise * returned by the public `translate()` method when all chunks are completed. */ - _checkIfFinished() { + _checkIfFinished: function() { // Check if all pending requests have been // completed and then resolves the promise. // If at least one chunk was successful, the @@ -188,7 +188,7 @@ this.YandexTranslator.prototype = { * @param request The request sent to the server. * @returns boolean True if parsing of this chunk was successful. */ - _parseChunkResult(yandexRequest) { + _parseChunkResult: function(yandexRequest) { let results; try { let result = JSON.parse(yandexRequest.networkRequest.responseText); @@ -228,7 +228,7 @@ this.YandexTranslator.prototype = { * @param startIndex What is the index, in the roots list, that the * chunk should start. */ - _generateNextTranslationRequest(startIndex) { + _generateNextTranslationRequest: function(startIndex) { let currentDataSize = 0; let currentChunks = 0; let output = []; @@ -292,7 +292,7 @@ YandexRequest.prototype = { /** * Initiates the request */ - fireRequest() { + fireRequest: function() { return Task.spawn(function *() { // Prepare URL. let url = getUrlParam("https://translate.yandex.net/api/v1.5/tr.json/translate", @@ -317,7 +317,7 @@ YandexRequest.prototype = { onLoad: (function(responseText, xhr) { deferred.resolve(this); }).bind(this), - onError(e, responseText, xhr) { + onError: function(e, responseText, xhr) { deferred.reject(xhr); }, postData: params diff --git a/browser/components/translation/test/browser_translation_infobar.js b/browser/components/translation/test/browser_translation_infobar.js index 9b6917b3fe31..4dbdcbee4c3c 100644 --- a/browser/components/translation/test/browser_translation_infobar.js +++ b/browser/components/translation/test/browser_translation_infobar.js @@ -33,23 +33,23 @@ function waitForCondition(condition, nextTest, errorMsg) { } var TranslationStub = { - translate(aFrom, aTo) { + translate: function(aFrom, aTo) { this.state = Translation.STATE_TRANSLATING; this.translatedFrom = aFrom; this.translatedTo = aTo; }, - _reset() { + _reset: function() { this.translatedFrom = ""; this.translatedTo = ""; }, - failTranslation() { + failTranslation: function() { this.state = Translation.STATE_ERROR; this._reset(); }, - finishTranslation() { + finishTranslation: function() { this.showTranslatedContent(); this.state = Translation.STATE_TRANSLATED; this._reset(); diff --git a/browser/components/translation/test/browser_translation_telemetry.js b/browser/components/translation/test/browser_translation_telemetry.js index 4e3e08925e9c..2c89c283f0b7 100644 --- a/browser/components/translation/test/browser_translation_telemetry.js +++ b/browser/components/translation/test/browser_translation_telemetry.js @@ -24,14 +24,14 @@ var MetricsChecker = { DETECT_LANG : Services.telemetry.getHistogramById("SHOULD_AUTO_DETECT_LANGUAGE"), }, - reset() { + reset: function() { for (let i of Object.keys(this.HISTOGRAMS)) { this.HISTOGRAMS[i].clear(); } this.updateMetrics(); }, - updateMetrics() { + updateMetrics: function() { this._metrics = { opportunitiesCount: this.HISTOGRAMS.OPPORTUNITIES.snapshot().sum || 0, pageCount: this.HISTOGRAMS.PAGES.snapshot().sum || 0, @@ -65,7 +65,7 @@ var MetricsChecker = { /** * A recurrent loop for making assertions about collected metrics. */ - _assertionLoop(prevMetrics, metrics, additions) { + _assertionLoop: function(prevMetrics, metrics, additions) { for (let metric of Object.keys(additions)) { let addition = additions[metric]; // Allows nesting metrics. Useful for keyed histograms. @@ -77,7 +77,7 @@ var MetricsChecker = { } }, - checkAdditions(additions) { + checkAdditions: function(additions) { let prevMetrics = this._metrics; this.updateMetrics(); this._assertionLoop(prevMetrics, this._metrics, additions); diff --git a/browser/components/uitour/UITour-lib.js b/browser/components/uitour/UITour-lib.js index 9b7775864988..40c1a82b4d99 100644 --- a/browser/components/uitour/UITour-lib.js +++ b/browser/components/uitour/UITour-lib.js @@ -27,7 +27,7 @@ if (typeof Mozilla == 'undefined') { var event = new CustomEvent('mozUITour', { bubbles: true, detail: { - action, + action: action, data: data || {} } }); @@ -94,19 +94,19 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.registerPageID = function(pageID) { _sendEvent('registerPageID', { - pageID + pageID: pageID }); }; Mozilla.UITour.showHeartbeat = function(message, thankyouMessage, flowId, engagementURL, learnMoreLabel, learnMoreURL, options) { var args = { - message, - thankyouMessage, - flowId, - engagementURL, - learnMoreLabel, - learnMoreURL, + message: message, + thankyouMessage: thankyouMessage, + flowId: flowId, + engagementURL: engagementURL, + learnMoreLabel: learnMoreLabel, + learnMoreURL: learnMoreURL, }; if (options) { @@ -123,8 +123,8 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.showHighlight = function(target, effect) { _sendEvent('showHighlight', { - target, - effect + target: target, + effect: effect }); }; @@ -152,13 +152,13 @@ if (typeof Mozilla == 'undefined') { targetCallbackID = _waitForCallback(options.targetCallback); _sendEvent('showInfo', { - target, - title, - text, - icon, + target: target, + title: title, + text: text, + icon: icon, buttons: buttonData, - closeButtonCallbackID, - targetCallbackID + closeButtonCallbackID: closeButtonCallbackID, + targetCallbackID: targetCallbackID }); }; @@ -209,14 +209,14 @@ if (typeof Mozilla == 'undefined') { showCallbackID = _waitForCallback(callback); _sendEvent('showMenu', { - name, - showCallbackID, + name: name, + showCallbackID: showCallbackID, }); }; Mozilla.UITour.hideMenu = function(name) { _sendEvent('hideMenu', { - name + name: name }); }; @@ -260,34 +260,34 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.addNavBarWidget = function(name, callback) { _sendEvent('addNavBarWidget', { - name, + name: name, callbackID: _waitForCallback(callback), }); }; Mozilla.UITour.setDefaultSearchEngine = function(identifier) { _sendEvent('setDefaultSearchEngine', { - identifier, + identifier: identifier, }); }; Mozilla.UITour.setTreatmentTag = function(name, value) { _sendEvent('setTreatmentTag', { - name, - value + name: name, + value: value }); }; Mozilla.UITour.getTreatmentTag = function(name, callback) { _sendEvent('getTreatmentTag', { - name, + name: name, callbackID: _waitForCallback(callback) }); }; Mozilla.UITour.setSearchTerm = function(term) { _sendEvent('setSearchTerm', { - term + term: term }); }; @@ -307,7 +307,7 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.openPreferences = function(pane) { _sendEvent('openPreferences', { - pane + pane: pane }); }; diff --git a/browser/components/uitour/UITour.jsm b/browser/components/uitour/UITour.jsm index eeb73ade9eab..2e25fdd458f4 100644 --- a/browser/components/uitour/UITour.jsm +++ b/browser/components/uitour/UITour.jsm @@ -214,7 +214,7 @@ this.UITour = { ["webide", {query: "#webide-button"}], ]), - init() { + init: function() { log.debug("Initializing UITour"); // Lazy getter is initialized here so it can be replicated any time // in a test. @@ -243,7 +243,7 @@ this.UITour = { }, {})); }, - restoreSeenPageIDs() { + restoreSeenPageIDs: function() { delete this.seenPageIDs; if (UITelemetry.enabled) { @@ -276,7 +276,7 @@ this.UITour = { return this.seenPageIDs; }, - addSeenPageID(aPageID) { + addSeenPageID: function(aPageID) { if (!UITelemetry.enabled) return; @@ -287,7 +287,7 @@ this.UITour = { this.persistSeenIDs(); }, - persistSeenIDs() { + persistSeenIDs: function() { if (this.seenPageIDs.size === 0) { Services.prefs.clearUserPref(PREF_SEENPAGEIDS); return; @@ -303,7 +303,7 @@ this.UITour = { return this._readerViewTriggerRegEx = new RegExp(readerViewUITourTrigger, "i"); }, - onLocationChange(aLocation) { + onLocationChange: function(aLocation) { // The ReaderView tour page is expected to run in Reader View, // which disables JavaScript on the page. To get around that, we // automatically start a pre-defined tour on page load (for hysterical @@ -314,7 +314,7 @@ this.UITour = { } }, - onPageEvent(aMessage, aEvent) { + onPageEvent: function(aMessage, aEvent) { let browser = aMessage.target; let window = browser.ownerGlobal; @@ -620,7 +620,7 @@ this.UITour = { value = Services.prefs.getComplexValue("browser.uitour.treatment." + name, Ci.nsISupportsString).data; } catch (ex) {} - this.sendPageCallback(messageManager, data.callbackID, { value }); + this.sendPageCallback(messageManager, data.callbackID, { value: value }); break; } @@ -708,7 +708,7 @@ this.UITour = { window.addEventListener("SSWindowClosing", this); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { log.debug("handleEvent: type =", aEvent.type, "event =", aEvent); switch (aEvent.type) { case "TabSelect": { @@ -734,7 +734,7 @@ this.UITour = { } }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { log.debug("observe: aTopic =", aTopic); switch (aTopic) { // The browser message manager is disconnected when the is @@ -769,7 +769,7 @@ this.UITour = { // additional utm_* URL params that should be appended, validate and append // them to the passed URLSearchParams object. Returns true if the params // were validated and appended, and false if the request should be ignored. - _populateCampaignParams(urlSearchParams, extraURLCampaignParams) { + _populateCampaignParams: function(urlSearchParams, extraURLCampaignParams) { // We are extra paranoid about what params we allow to be appended. if (typeof extraURLCampaignParams == "undefined") { // no params, so it's all good. @@ -811,12 +811,12 @@ this.UITour = { return true; }, - setTelemetryBucket(aPageID) { + setTelemetryBucket: function(aPageID) { let bucket = BUCKET_NAME + BrowserUITelemetry.BUCKET_SEPARATOR + aPageID; BrowserUITelemetry.setBucket(bucket); }, - setExpiringTelemetryBucket(aPageID, aType) { + setExpiringTelemetryBucket: function(aPageID, aType) { let bucket = BUCKET_NAME + BrowserUITelemetry.BUCKET_SEPARATOR + aPageID + BrowserUITelemetry.BUCKET_SEPARATOR + aType; @@ -826,7 +826,7 @@ this.UITour = { // This is registered with UITelemetry by BrowserUITelemetry, so that UITour // can remain lazy-loaded on-demand. - getTelemetry() { + getTelemetry: function() { return { seenPageIDs: [...this.seenPageIDs.keys()], }; @@ -835,7 +835,7 @@ this.UITour = { /** * Tear down a tour from a tab e.g. upon switching/closing tabs. */ - teardownTourForBrowser(aWindow, aBrowser, aTourPageClosing = false) { + teardownTourForBrowser: function(aWindow, aBrowser, aTourPageClosing = false) { log.debug("teardownTourForBrowser: aBrowser = ", aBrowser, aTourPageClosing); if (this.pageIDSourceBrowsers.has(aBrowser)) { @@ -873,7 +873,7 @@ this.UITour = { /** * Tear down all tours for a ChromeWindow. */ - teardownTourForWindow(aWindow) { + teardownTourForWindow: function(aWindow) { log.debug("teardownTourForWindow"); aWindow.gBrowser.tabContainer.removeEventListener("TabSelect", this); aWindow.removeEventListener("SSWindowClosing", this); @@ -892,7 +892,7 @@ this.UITour = { }, // This function is copied to UITourListener. - isSafeScheme(aURI) { + isSafeScheme: function(aURI) { let allowedSchemes = new Set(["https", "about"]); if (!Services.prefs.getBoolPref("browser.uitour.requireSecure")) allowedSchemes.add("http"); @@ -905,7 +905,7 @@ this.UITour = { return true; }, - resolveURL(aBrowser, aURL) { + resolveURL: function(aBrowser, aURL) { try { let uri = Services.io.newURI(aURL, null, aBrowser.currentURI); @@ -918,20 +918,20 @@ this.UITour = { return null; }, - sendPageCallback(aMessageManager, aCallbackID, aData = {}) { + sendPageCallback: function(aMessageManager, aCallbackID, aData = {}) { let detail = {data: aData, callbackID: aCallbackID}; log.debug("sendPageCallback", detail); aMessageManager.sendAsyncMessage("UITour:SendPageCallback", detail); }, - isElementVisible(aElement) { + isElementVisible: function(aElement) { let targetStyle = aElement.ownerGlobal.getComputedStyle(aElement); return !aElement.ownerDocument.hidden && targetStyle.display != "none" && targetStyle.visibility == "visible"; }, - getTarget(aWindow, aTargetName, aSticky = false) { + getTarget: function(aWindow, aTargetName, aSticky = false) { log.debug("getTarget:", aTargetName); let deferred = Promise.defer(); if (typeof aTargetName != "string" || !aTargetName) { @@ -966,7 +966,7 @@ this.UITour = { infoPanelOffsetX: targetObject.infoPanelOffsetX, infoPanelOffsetY: targetObject.infoPanelOffsetY, infoPanelPosition: targetObject.infoPanelPosition, - node, + node: node, removeTargetListener: targetObject.removeTargetListener, targetName: aTargetName, widgetName: targetObject.widgetName, @@ -976,7 +976,7 @@ this.UITour = { return deferred.promise; }, - targetIsInAppMenu(aTarget) { + targetIsInAppMenu: function(aTarget) { let placement = CustomizableUI.getPlacementOfWidget(aTarget.widgetName || aTarget.node.id); if (placement && placement.area == CustomizableUI.AREA_PANEL) { return true; @@ -997,7 +997,7 @@ this.UITour = { * Called before opening or after closing a highlight or info panel to see if * we need to open or close the appMenu to see the annotation's anchor. */ - _setAppMenuStateForAnnotation(aWindow, aAnnotationType, aShouldOpenForHighlight, aCallback = null) { + _setAppMenuStateForAnnotation: function(aWindow, aAnnotationType, aShouldOpenForHighlight, aCallback = null) { log.debug("_setAppMenuStateForAnnotation:", aAnnotationType); log.debug("_setAppMenuStateForAnnotation: Menu is expected to be:", aShouldOpenForHighlight ? "open" : "closed"); @@ -1037,14 +1037,14 @@ this.UITour = { }, - previewTheme(aTheme) { + previewTheme: function(aTheme) { let origin = Services.prefs.getCharPref("browser.uitour.themeOrigin"); let data = LightweightThemeManager.parseTheme(aTheme, origin); if (data) LightweightThemeManager.previewTheme(data); }, - resetTheme() { + resetTheme: function() { LightweightThemeManager.resetPreview(); }, @@ -1387,7 +1387,7 @@ this.UITour = { * @param {Node} aAnchor The element that's supposed to be the anchor * @type {Node} */ - _correctAnchor(aAnchor) { + _correctAnchor: function(aAnchor) { // If the target is in the overflow panel, just return the overflow button. if (aAnchor.getAttribute("overflowedItem")) { let doc = aAnchor.ownerDocument; @@ -1407,7 +1407,7 @@ this.UITour = { * @param aEffect (optional) The effect to use from UITour.highlightEffects or "none". * @see UITour.highlightEffects */ - showHighlight(aChromeWindow, aTarget, aEffect = "none") { + showHighlight: function(aChromeWindow, aTarget, aEffect = "none") { function showHighlightPanel() { let highlighter = aChromeWindow.document.getElementById("UITourHighlight"); @@ -1478,7 +1478,7 @@ this.UITour = { showHighlightPanel.bind(this)); }, - hideHighlight(aWindow) { + hideHighlight: function(aWindow) { let highlighter = aWindow.document.getElementById("UITourHighlight"); this._removeAnnotationPanelMutationObserver(highlighter.parentElement); highlighter.parentElement.hidePopup(); @@ -1617,7 +1617,7 @@ this.UITour = { return tooltip.getAttribute("targetName") == aTargetName && tooltip.state != "closed"; }, - hideInfo(aWindow) { + hideInfo: function(aWindow) { let document = aWindow.document; let tooltip = document.getElementById("UITourTooltip"); @@ -1630,7 +1630,7 @@ this.UITour = { tooltipButtons.firstChild.remove(); }, - showMenu(aWindow, aMenuName, aOpenCallback = null) { + showMenu: function(aWindow, aMenuName, aOpenCallback = null) { log.debug("showMenu:", aMenuName); function openMenuButton(aMenuBtn) { if (!aMenuBtn || !aMenuBtn.boxObject || aMenuBtn.open) { @@ -1731,7 +1731,7 @@ this.UITour = { } }, - hideMenu(aWindow, aMenuName) { + hideMenu: function(aWindow, aMenuName) { log.debug("hideMenu:", aMenuName); function closeMenuButton(aMenuBtn) { if (aMenuBtn && aMenuBtn.boxObject) @@ -1749,11 +1749,11 @@ this.UITour = { } }, - showNewTab(aWindow, aBrowser) { + showNewTab: function(aWindow, aBrowser) { aWindow.openLinkIn("about:newtab", "current", {targetBrowser: aBrowser}); }, - hideAnnotationsForPanel(aEvent, aTargetPositionCallback) { + hideAnnotationsForPanel: function(aEvent, aTargetPositionCallback) { let win = aEvent.target.ownerGlobal; let annotationElements = new Map([ // [annotationElement (panel), method to hide the annotation] @@ -1778,7 +1778,7 @@ this.UITour = { UITour.appMenuOpenForAnnotation.clear(); }, - hideAppMenuAnnotations(aEvent) { + hideAppMenuAnnotations: function(aEvent) { UITour.hideAnnotationsForPanel(aEvent, UITour.targetIsInAppMenu); }, @@ -1788,13 +1788,13 @@ this.UITour = { }); }, - onPanelHidden(aEvent) { + onPanelHidden: function(aEvent) { aEvent.target.removeAttribute("noautohide"); UITour.recreatePopup(aEvent.target); UITour.clearAvailableTargetsCache(); }, - recreatePopup(aPanel) { + recreatePopup: function(aPanel) { // After changing popup attributes that relate to how the native widget is created // (e.g. @noautohide) we need to re-create the frame/widget for it to take effect. if (aPanel.hidden) { @@ -1808,7 +1808,7 @@ this.UITour = { aPanel.hidden = false; }, - getConfiguration(aMessageManager, aWindow, aConfiguration, aCallbackID) { + getConfiguration: function(aMessageManager, aWindow, aConfiguration, aCallbackID) { switch (aConfiguration) { case "appinfo": let props = ["defaultUpdateChannel", "version"]; @@ -1888,7 +1888,7 @@ this.UITour = { } }, - setConfiguration(aWindow, aConfiguration, aValue) { + setConfiguration: function(aWindow, aConfiguration, aValue) { switch (aConfiguration) { case "defaultBrowser": // Ignore aValue in this case because the default browser can only @@ -1906,7 +1906,7 @@ this.UITour = { } }, - getAvailableTargets(aMessageManager, aChromeWindow, aCallbackID) { + getAvailableTargets: function(aMessageManager, aChromeWindow, aCallbackID) { Task.spawn(function*() { let window = aChromeWindow; let data = this.availableTargetsCache.get(window); @@ -1941,7 +1941,7 @@ this.UITour = { }); }, - startSubTour(aFeature) { + startSubTour: function(aFeature) { if (aFeature != "string") { log.error("startSubTour: No feature option specified"); return; @@ -1955,7 +1955,7 @@ this.UITour = { } }, - addNavBarWidget(aTarget, aMessageManager, aCallbackID) { + addNavBarWidget: function(aTarget, aMessageManager, aCallbackID) { if (aTarget.node) { log.error("addNavBarWidget: can't add a widget already present:", aTarget); return; @@ -1973,7 +1973,7 @@ this.UITour = { this.sendPageCallback(aMessageManager, aCallbackID); }, - _addAnnotationPanelMutationObserver(aPanelEl) { + _addAnnotationPanelMutationObserver: function(aPanelEl) { if (AppConstants.platform == "linux") { let observer = this._annotationPanelMutationObservers.get(aPanelEl); if (observer) { @@ -1990,7 +1990,7 @@ this.UITour = { } }, - _removeAnnotationPanelMutationObserver(aPanelEl) { + _removeAnnotationPanelMutationObserver: function(aPanelEl) { if (AppConstants.platform == "linux") { let observer = this._annotationPanelMutationObservers.get(aPanelEl); if (observer) { @@ -2005,7 +2005,7 @@ this.UITour = { * nsXULPopupManager::PopupResized and lead to incorrect width and height attributes getting * set on the panel. */ - _annotationMutationCallback(aMutations) { + _annotationMutationCallback: function(aMutations) { for (let mutation of aMutations) { // Remove both attributes at once and ignore remaining mutations to be proccessed. mutation.target.removeAttribute("width"); @@ -2055,7 +2055,7 @@ this.UITour = { } let detail = { event: eventName, - params, + params: params, }; messageManager.sendAsyncMessage("UITour:SendPageNotification", detail); } @@ -2096,7 +2096,7 @@ this.UITour.init(); * Public API to be called by the UITour code */ const UITourHealthReport = { - recordTreatmentTag(tag, value) { + recordTreatmentTag: function(tag, value) { return TelemetryController.submitExternalPing("uitour-tag", { version: 1, diff --git a/browser/components/uitour/content-UITour.js b/browser/components/uitour/content-UITour.js index f7ef7d371a59..f5646486f653 100644 --- a/browser/components/uitour/content-UITour.js +++ b/browser/components/uitour/content-UITour.js @@ -8,7 +8,7 @@ const PREF_TEST_WHITELIST = "browser.uitour.testingOrigins"; const UITOUR_PERMISSION = "uitour"; var UITourListener = { - handleEvent(event) { + handleEvent: function(event) { if (!Services.prefs.getBoolPref("browser.uitour.enabled")) { return; } @@ -24,7 +24,7 @@ var UITourListener = { }); }, - isTestingOrigin(aURI) { + isTestingOrigin: function(aURI) { if (Services.prefs.getPrefType(PREF_TEST_WHITELIST) != Services.prefs.PREF_STRING) { return false; } @@ -44,7 +44,7 @@ var UITourListener = { }, // This function is copied from UITour.jsm. - isSafeScheme(aURI) { + isSafeScheme: function(aURI) { let allowedSchemes = new Set(["https", "about"]); if (!Services.prefs.getBoolPref("browser.uitour.requireSecure")) allowedSchemes.add("http"); @@ -55,7 +55,7 @@ var UITourListener = { return true; }, - ensureTrustedOrigin() { + ensureTrustedOrigin: function() { if (content.top != content) return false; @@ -74,7 +74,7 @@ var UITourListener = { return this.isTestingOrigin(uri); }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { switch (aMessage.name) { case "UITour:SendPageCallback": this.sendPageEvent("Response", aMessage.data); @@ -85,7 +85,7 @@ var UITourListener = { } }, - sendPageEvent(type, detail) { + sendPageEvent: function(type, detail) { if (!this.ensureTrustedOrigin()) { return; } diff --git a/browser/components/uitour/test/browser_UITour_defaultBrowser.js b/browser/components/uitour/test/browser_UITour_defaultBrowser.js index f5f529d30b19..5ebf553b0562 100644 --- a/browser/components/uitour/test/browser_UITour_defaultBrowser.js +++ b/browser/components/uitour/test/browser_UITour_defaultBrowser.js @@ -12,8 +12,8 @@ Cc["@mozilla.org/moz/jssubscript-loader;1"] function MockShellService() {} MockShellService.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIShellService]), - isDefaultBrowser(aStartupCheck, aForAllTypes) { return false; }, - setDefaultBrowser(aClaimAllTypes, aForAllUsers) { + isDefaultBrowser: function(aStartupCheck, aForAllTypes) { return false; }, + setDefaultBrowser: function(aClaimAllTypes, aForAllUsers) { setDefaultBrowserCalled = true; }, shouldCheckDefaultBrowser: false, @@ -23,12 +23,12 @@ MockShellService.prototype = { BACKGROUND_CENTER : 3, BACKGROUND_FILL : 4, BACKGROUND_FIT : 5, - setDesktopBackground(aElement, aPosition) {}, + setDesktopBackground: function(aElement, aPosition) {}, APPLICATION_MAIL : 0, APPLICATION_NEWS : 1, - openApplication(aApplication) {}, + openApplication: function(aApplication) {}, desktopBackgroundColor: 0, - openApplicationWithURI(aApplication, aURI) {}, + openApplicationWithURI: function(aApplication, aURI) {}, defaultFeedReader: 0, }; diff --git a/browser/components/uitour/test/browser_UITour_heartbeat.js b/browser/components/uitour/test/browser_UITour_heartbeat.js index 5b6a3ba717ef..6cfeb2a2732c 100644 --- a/browser/components/uitour/test/browser_UITour_heartbeat.js +++ b/browser/components/uitour/test/browser_UITour_heartbeat.js @@ -221,7 +221,7 @@ add_UITour_task(function* test_heartbeat_take_optional_icon_URL() { // Show the Heartbeat notification and wait for it to be displayed. let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL, null, null, { - iconURL + iconURL: iconURL }); // Validate the returned timestamp. diff --git a/browser/components/uitour/test/browser_UITour_modalDialog.js b/browser/components/uitour/test/browser_UITour_modalDialog.js index a697d5f2df3a..49d01474f9c2 100644 --- a/browser/components/uitour/test/browser_UITour_modalDialog.js +++ b/browser/components/uitour/test/browser_UITour_modalDialog.js @@ -22,7 +22,7 @@ function startCallbackTimer() { var observer = SpecialPowers.wrapCallbackObject({ - QueryInterface(iid) { + QueryInterface : function(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports, Ci.nsISupportsWeakReference]; @@ -31,7 +31,7 @@ var observer = SpecialPowers.wrapCallbackObject({ return this; }, - observe(subject, topic, data) { + observe : function(subject, topic, data) { var doc = getDialogDoc(); if (doc) handleDialog(doc); diff --git a/browser/components/uitour/test/browser_no_tabs.js b/browser/components/uitour/test/browser_no_tabs.js index 05c0f2b9f67f..62048b1568d3 100644 --- a/browser/components/uitour/test/browser_no_tabs.js +++ b/browser/components/uitour/test/browser_no_tabs.js @@ -26,7 +26,7 @@ function createHiddenBrowser(aURL) { browser.setAttribute("src", aURL); doc.documentElement.appendChild(browser); - resolve({frame, browser}); + resolve({frame: frame, browser: browser}); })); } diff --git a/browser/experiments/Experiments.jsm b/browser/experiments/Experiments.jsm index 9038c7d801b4..f76092f497f9 100644 --- a/browser/experiments/Experiments.jsm +++ b/browser/experiments/Experiments.jsm @@ -211,7 +211,7 @@ var Experiments = { /** * Provides access to the global `Experiments.Experiments` instance. */ - instance() { + instance: function() { if (!gExperiments) { gExperiments = new Experiments.Experiments(); } @@ -236,11 +236,11 @@ Experiments.Policy = function() { }; Experiments.Policy.prototype = { - now() { + now: function() { return new Date(); }, - random() { + random: function() { let pref = gPrefs.get(PREF_FORCE_SAMPLE); if (pref !== undefined) { let val = Number.parseFloat(pref); @@ -256,19 +256,19 @@ Experiments.Policy.prototype = { return Math.random(); }, - futureDate(offset) { + futureDate: function(offset) { return new Date(this.now().getTime() + offset); }, - oneshotTimer(callback, timeout, thisObj, name) { + oneshotTimer: function(callback, timeout, thisObj, name) { return CommonUtils.namedTimer(callback, timeout, thisObj, name); }, - updatechannel() { + updatechannel: function() { return UpdateUtils.UpdateChannel; }, - locale() { + locale: function() { let chrome = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry); return chrome.getSelectedLocale("global"); }, @@ -277,7 +277,7 @@ Experiments.Policy.prototype = { * For testing a race condition, one of the tests delays the callback of * writing the cache by replacing this policy function. */ - delayCacheWrite(promise) { + delayCacheWrite: function(promise) { return promise; }, }; @@ -373,7 +373,7 @@ Experiments.Experiments.prototype = { return !this._shutdown; }, - init() { + init: function() { this._shutdown = false; configureLogging(); @@ -467,7 +467,7 @@ Experiments.Experiments.prototype = { }), // Return state information, for debugging purposes. - _getState() { + _getState: function() { let activeExperiment = this._getActiveExperiment(); let state = { isShutdown: this._shutdown, @@ -497,13 +497,13 @@ Experiments.Experiments.prototype = { return state; }, - _addToForensicsLog(what, string) { + _addToForensicsLog: function(what, string) { this._forensicsLogs.shift(); let timeInSec = Math.floor(Services.telemetry.msSinceProcessStart() / 1000); this._forensicsLogs.push(`${timeInSec}: ${what} - ${string}`); }, - _registerWithAddonManager(previousExperimentsProvider) { + _registerWithAddonManager: function(previousExperimentsProvider) { this._log.trace("Registering instance with Addon Manager."); AddonManager.addAddonListener(this); @@ -526,7 +526,7 @@ Experiments.Experiments.prototype = { }, - _unregisterWithAddonManager() { + _unregisterWithAddonManager: function() { this._log.trace("Unregistering instance with Addon Manager."); this._log.trace("Removing install listener from add-on manager."); @@ -546,7 +546,7 @@ Experiments.Experiments.prototype = { * Change the PreviousExperimentsProvider that this instance uses. * For testing only. */ - _setPreviousExperimentsProvider(provider) { + _setPreviousExperimentsProvider: function(provider) { this._unregisterWithAddonManager(); this._registerWithAddonManager(provider); }, @@ -554,7 +554,7 @@ Experiments.Experiments.prototype = { /** * Throws an exception if we've already shut down. */ - _checkForShutdown() { + _checkForShutdown: function() { if (this._shutdown) { throw new AlreadyShutdownError("uninit() already called"); } @@ -594,7 +594,7 @@ Experiments.Experiments.prototype = { } }), - _telemetryStatusChanged() { + _telemetryStatusChanged: function() { this._toggleExperimentsEnabled(gExperimentsEnabled); }, @@ -616,7 +616,7 @@ Experiments.Experiments.prototype = { * * @return Promise> Array of experiment info objects. */ - getExperiments() { + getExperiments: function() { return Task.spawn(function*() { yield this._loadTask; let list = []; @@ -628,7 +628,7 @@ Experiments.Experiments.prototype = { } list.push({ - id, + id: id, name: experiment._name, description: experiment._description, active: experiment.enabled, @@ -648,7 +648,7 @@ Experiments.Experiments.prototype = { * Returns the ExperimentInfo for the active experiment, or null * if there is none. */ - getActiveExperiment() { + getActiveExperiment: function() { let experiment = this._getActiveExperiment(); if (!experiment) { return null; @@ -718,7 +718,7 @@ Experiments.Experiments.prototype = { /** * Determine whether another date has the same UTC day as now(). */ - _dateIsTodayUTC(d) { + _dateIsTodayUTC: function(d) { let now = this._policy.now(); return stripDateToMidnight(now).getTime() == stripDateToMidnight(d).getTime(); @@ -734,7 +734,7 @@ Experiments.Experiments.prototype = { * * @return Promise */ - lastActiveToday() { + lastActiveToday: function() { return Task.spawn(function* getMostRecentActiveExperimentTask() { let experiments = yield this.getExperiments(); @@ -753,7 +753,7 @@ Experiments.Experiments.prototype = { }.bind(this)); }, - _run() { + _run: function() { this._log.trace("_run"); this._checkForShutdown(); if (!this._mainTask) { @@ -783,7 +783,7 @@ Experiments.Experiments.prototype = { return this._mainTask; }, - *_main() { + _main: function*() { do { this._log.trace("_main iteration"); yield this._loadTask; @@ -804,7 +804,7 @@ Experiments.Experiments.prototype = { while (this._refresh || this._terminateReason || this._dirty); }, - *_loadManifest() { + _loadManifest: function*() { this._log.trace("_loadManifest"); let uri = Services.urlFormatter.formatURLPref(PREF_BRANCH + PREF_MANIFEST_URI); @@ -833,7 +833,7 @@ Experiments.Experiments.prototype = { * @return Promise<> * The promise is resolved when the manifest and experiment list is updated. */ - updateManifest() { + updateManifest: function() { this._log.trace("updateManifest()"); if (!gExperimentsEnabled) { @@ -848,7 +848,7 @@ Experiments.Experiments.prototype = { return this._run(); }, - notify(timer) { + notify: function(timer) { this._log.trace("notify()"); this._checkForShutdown(); return this._run(); @@ -856,7 +856,7 @@ Experiments.Experiments.prototype = { // START OF ADD-ON LISTENERS - onUninstalled(addon) { + onUninstalled: function(addon) { this._log.trace("onUninstalled() - addon id: " + addon.id); if (gActiveUninstallAddonIDs.has(addon.id)) { this._log.trace("matches pending uninstall"); @@ -873,7 +873,7 @@ Experiments.Experiments.prototype = { /** * @returns {Boolean} returns false when we cancel the install. */ - onInstallStarted(install) { + onInstallStarted: function(install) { if (install.addon.type != "experiment") { return true; } @@ -917,7 +917,7 @@ Experiments.Experiments.prototype = { // END OF ADD-ON LISTENERS. - _getExperimentByAddonId(addonId) { + _getExperimentByAddonId: function(addonId) { for (let [, entry] of this._experiments) { if (entry._addonId === addonId) { return entry; @@ -931,7 +931,7 @@ Experiments.Experiments.prototype = { * Helper function to make HTTP GET requests. Returns a promise that is resolved with * the responseText when the request is complete. */ - _httpGetRequest(url) { + _httpGetRequest: function(url) { this._log.trace("httpGetRequest(" + url + ")"); let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest); @@ -986,7 +986,7 @@ Experiments.Experiments.prototype = { /* * Part of the main task to save the cache to disk, called from _main. */ - *_saveToCache() { + _saveToCache: function* () { this._log.trace("_saveToCache"); let path = this._cacheFilePath; this._dirty = false; @@ -1029,7 +1029,7 @@ Experiments.Experiments.prototype = { } }), - _populateFromCache(data) { + _populateFromCache: function(data) { this._log.trace("populateFromCache() - data: " + JSON.stringify(data)); // If the user has a newer cache version than we can understand, we fail @@ -1062,7 +1062,7 @@ Experiments.Experiments.prototype = { * Update the experiment entries from the experiments * array in the manifest */ - _updateExperiments(manifestObject) { + _updateExperiments: function(manifestObject) { this._log.trace("_updateExperiments() - experiments: " + JSON.stringify(manifestObject)); if (manifestObject.version !== MANIFEST_VERSION) { @@ -1113,7 +1113,7 @@ Experiments.Experiments.prototype = { this._dirty = true; }, - getActiveExperimentID() { + getActiveExperimentID: function() { if (!this._experiments) { return null; } @@ -1124,7 +1124,7 @@ Experiments.Experiments.prototype = { return e.id; }, - getActiveExperimentBranch() { + getActiveExperimentBranch: function() { if (!this._experiments) { return null; } @@ -1135,7 +1135,7 @@ Experiments.Experiments.prototype = { return e.branch; }, - _getActiveExperiment() { + _getActiveExperiment: function() { let enabled = [...this._experiments.values()].filter(experiment => experiment._enabled); if (enabled.length == 1) { @@ -1155,7 +1155,7 @@ Experiments.Experiments.prototype = { * * @return Promise<> Promise that will get resolved once the task is done or failed. */ - disableExperiment(reason) { + disableExperiment: function(reason) { if (!reason) { throw new Error("Must specify a termination reason."); } @@ -1180,7 +1180,7 @@ Experiments.Experiments.prototype = { * Task function to check applicability of experiments, disable the active * experiment if needed and activate the first applicable candidate. */ - *_evaluateExperiments() { + _evaluateExperiments: function*() { this._log.trace("_evaluateExperiments"); this._checkForShutdown(); @@ -1317,7 +1317,7 @@ Experiments.Experiments.prototype = { /* * Schedule the soonest re-check of experiment applicability that is needed. */ - _scheduleNextRun() { + _scheduleNextRun: function() { this._checkForShutdown(); if (this._timer) { @@ -1462,7 +1462,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The experiment data from the manifest. * @return boolean Whether initialization succeeded. */ - initFromManifestData(data) { + initFromManifestData: function(data) { if (!this._isManifestDataValid(data)) { return false; } @@ -1522,7 +1522,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The entry data from the cache. * @return boolean Whether initialization succeeded. */ - initFromCacheData(data) { + initFromCacheData: function(data) { for (let [key, dval] of this.UPGRADE_KEYS) { if (!(key in data)) { data[key] = dval; @@ -1567,7 +1567,7 @@ Experiments.ExperimentEntry.prototype = { /* * Returns a JSON representation of this object. */ - toJSON() { + toJSON: function() { let obj = {}; // Dates are serialized separately as epoch ms. @@ -1592,7 +1592,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The experiment data from the manifest. * @return boolean Whether updating succeeded. */ - updateFromManifestData(data) { + updateFromManifestData: function(data) { let old = this._manifestData; if (!this._isManifestDataValid(data)) { @@ -1624,7 +1624,7 @@ Experiments.ExperimentEntry.prototype = { * If it is not applicable it is rejected with * a Promise which contains the reason. */ - isApplicable() { + isApplicable: function() { let versionCmp = Cc["@mozilla.org/xpcom/version-comparator;1"] .getService(Ci.nsIVersionComparator); let app = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo); @@ -2015,7 +2015,7 @@ Experiments.ExperimentEntry.prototype = { * * @return Promise */ - _getAddon() { + _getAddon: function() { if (!this._addonId) { return Promise.resolve(null); } @@ -2030,7 +2030,7 @@ Experiments.ExperimentEntry.prototype = { }); }, - _logTermination(terminationKind, terminationReason) { + _logTermination: function(terminationKind, terminationReason) { if (terminationKind === undefined) { return; } @@ -2051,7 +2051,7 @@ Experiments.ExperimentEntry.prototype = { /** * Determine whether an active experiment should be stopped. */ - shouldStop() { + shouldStop: function() { if (!this._enabled) { throw new Error("shouldStop must not be called on disabled experiments."); } @@ -2059,7 +2059,7 @@ Experiments.ExperimentEntry.prototype = { let deferred = Promise.defer(); this.isApplicable().then( () => deferred.resolve({shouldStop: false}), - reason => deferred.resolve({shouldStop: true, reason}) + reason => deferred.resolve({shouldStop: true, reason: reason}) ); return deferred.promise; @@ -2068,7 +2068,7 @@ Experiments.ExperimentEntry.prototype = { /* * Should this be discarded from the cache due to age? */ - shouldDiscard() { + shouldDiscard: function() { let limit = this._policy.now(); limit.setDate(limit.getDate() - KEEP_HISTORY_N_DAYS); return (this._lastChangedDate < limit); @@ -2078,7 +2078,7 @@ Experiments.ExperimentEntry.prototype = { * Get next date (in epoch-ms) to schedule a re-evaluation for this. * Returns 0 if it doesn't need one. */ - getScheduleTime() { + getScheduleTime: function() { if (this._enabled) { let startTime = this._startDate.getTime(); let maxActiveTime = startTime + 1000 * this._manifestData.maxActiveSeconds; @@ -2095,7 +2095,7 @@ Experiments.ExperimentEntry.prototype = { /* * Perform sanity checks on the experiment data. */ - _isManifestDataValid(data) { + _isManifestDataValid: function(data) { this._log.trace("isManifestDataValid() - data: " + JSON.stringify(data)); for (let key of this.MANIFEST_REQUIRED_FIELDS) { @@ -2148,12 +2148,12 @@ this.Experiments.PreviousExperimentProvider = function(experiments) { this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ name: "PreviousExperimentProvider", - startup() { + startup: function() { this._log.trace("startup()"); Services.obs.addObserver(this, EXPERIMENTS_CHANGED_TOPIC, false); }, - shutdown() { + shutdown: function() { this._log.trace("shutdown()"); try { Services.obs.removeObserver(this, EXPERIMENTS_CHANGED_TOPIC); @@ -2162,7 +2162,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ } }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case EXPERIMENTS_CHANGED_TOPIC: this._updateExperimentList(); @@ -2170,7 +2170,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ } }, - getAddonByID(id, cb) { + getAddonByID: function(id, cb) { for (let experiment of this._experimentList) { if (experiment.id == id) { cb(new PreviousExperimentAddon(experiment)); @@ -2181,7 +2181,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ cb(null); }, - getAddonsByTypes(types, cb) { + getAddonsByTypes: function(types, cb) { if (types && types.length > 0 && types.indexOf("experiment") == -1) { cb([]); return; @@ -2190,7 +2190,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ cb(this._experimentList.map(e => new PreviousExperimentAddon(e))); }, - _updateExperimentList() { + _updateExperimentList: function() { return this._experiments.getExperiments().then((experiments) => { let list = experiments.filter(e => !e.active); @@ -2323,11 +2323,11 @@ PreviousExperimentAddon.prototype = Object.freeze({ // BEGIN REQUIRED METHODS - isCompatibleWith(appVersion, platformVersion) { + isCompatibleWith: function(appVersion, platformVersion) { return true; }, - findUpdates(listener, reason, appVersion, platformVersion) { + findUpdates: function(listener, reason, appVersion, platformVersion) { AddonManagerPrivate.callNoUpdateListeners(this, listener, reason, appVersion, platformVersion); }, diff --git a/browser/experiments/ExperimentsService.js b/browser/experiments/ExperimentsService.js index 28da659bb0a9..478793617f29 100644 --- a/browser/experiments/ExperimentsService.js +++ b/browser/experiments/ExperimentsService.js @@ -54,7 +54,7 @@ ExperimentsService.prototype = { classID: Components.ID("{f7800463-3b97-47f9-9341-b7617e6d8d49}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback, Ci.nsIObserver]), - notify(timer) { + notify: function(timer) { if (!gExperimentsEnabled) { return; } @@ -67,14 +67,14 @@ ExperimentsService.prototype = { } }, - _delayedInit() { + _delayedInit: function() { if (!this._initialized) { this._initialized = true; Experiments.instance(); // for side effects } }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case "profile-after-change": if (gExperimentsEnabled) { diff --git a/browser/experiments/test/xpcshell/test_activate.js b/browser/experiments/test/xpcshell/test_activate.js index 3e62c896241d..60deafbfb3d5 100644 --- a/browser/experiments/test/xpcshell/test_activate.js +++ b/browser/experiments/test/xpcshell/test_activate.js @@ -52,7 +52,7 @@ function isApplicable(experiment) { let deferred = Promise.defer(); experiment.isApplicable().then( result => deferred.resolve({ applicable: true, reason: null }), - reason => deferred.resolve({ applicable: false, reason }) + reason => deferred.resolve({ applicable: false, reason: reason }) ); return deferred.promise; diff --git a/browser/extensions/pocket/bootstrap.js b/browser/extensions/pocket/bootstrap.js index 1d2f7313679f..a9a70d0b7011 100644 --- a/browser/extensions/pocket/bootstrap.js +++ b/browser/extensions/pocket/bootstrap.js @@ -91,13 +91,13 @@ function CreatePocketWidget(reason) { label: gPocketBundle.GetStringFromName("pocket-button.label"), tooltiptext: gPocketBundle.GetStringFromName("pocket-button.tooltiptext"), // Use forwarding functions here to avoid loading Pocket.jsm on startup: - onViewShowing() { + onViewShowing: function() { return Pocket.onPanelViewShowing.apply(this, arguments); }, - onViewHiding() { + onViewHiding: function() { return Pocket.onPanelViewHiding.apply(this, arguments); }, - onBeforeCreated(doc) { + onBeforeCreated: function(doc) { // Bug 1223127,CUI should make this easier to do. if (doc.getElementById("PanelUI-pocketView")) return; @@ -158,10 +158,10 @@ function CreatePocketWidget(reason) { // PocketContextMenu // When the context menu is opened check if we need to build and enable pocket UI. var PocketContextMenu = { - init() { + init: function() { Services.obs.addObserver(this, "on-build-contextmenu", false); }, - shutdown() { + shutdown: function() { Services.obs.removeObserver(this, "on-build-contextmenu"); // loop through windows and remove context menus // iterate through all windows and add pocket to them @@ -174,7 +174,7 @@ var PocketContextMenu = { } } }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { let subject = aSubject.wrappedJSObject; let document = subject.menu.ownerDocument; let pocketEnabled = CustomizableUI.getPlacementOfWidget("pocket-button"); @@ -240,20 +240,20 @@ var PocketReader = { this._hidden = hide; this.update(); }, - startup() { + startup: function() { // Setup the listeners, update will be called when the widget is added, // no need to do that now. let mm = Services.mm; mm.addMessageListener("Reader:OnSetup", this); mm.addMessageListener("Reader:Clicked-pocket-button", this); }, - shutdown() { + shutdown: function() { let mm = Services.mm; mm.removeMessageListener("Reader:OnSetup", this); mm.removeMessageListener("Reader:Clicked-pocket-button", this); this.hidden = true; }, - update() { + update: function() { if (this.hidden) { Services.mm.broadcastAsyncMessage("Reader:RemoveButton", { id: "pocket-button" }); } else { @@ -263,7 +263,7 @@ var PocketReader = { image: "chrome://pocket/content/panels/img/pocket.svg#pocket-mark" }); } }, - receiveMessage(message) { + receiveMessage: function(message) { switch (message.name) { case "Reader:OnSetup": { // Tell the reader about our button. @@ -299,7 +299,7 @@ var PocketReader = { function pktUIGetter(prop, window) { return { - get() { + get: function() { // delete any getters for properties loaded from main.js so we only load main.js once delete window.pktUI; delete window.pktApi; @@ -313,7 +313,7 @@ function pktUIGetter(prop, window) { } var PocketOverlay = { - startup(reason) { + startup: function(reason) { let styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"] .getService(Ci.nsIStyleSheetService); this._sheetType = styleSheetService.AUTHOR_SHEET; @@ -329,7 +329,7 @@ var PocketOverlay = { this.onWindowOpened(win); } }, - shutdown(reason) { + shutdown: function(reason) { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.broadcastAsyncMessage("PocketShuttingDown"); @@ -359,14 +359,14 @@ var PocketOverlay = { PocketContextMenu.shutdown(); PocketReader.shutdown(); }, - onWindowOpened(window) { + onWindowOpened: function(window) { if (window.hasOwnProperty("pktUI")) return; this.setWindowScripts(window); this.addStyles(window); this.updateWindow(window); }, - setWindowScripts(window) { + setWindowScripts: function(window) { XPCOMUtils.defineLazyModuleGetter(window, "Pocket", "chrome://pocket/content/Pocket.jsm"); // Can't use XPCOMUtils for these because the scripts try to define the variables @@ -376,7 +376,7 @@ var PocketOverlay = { Object.defineProperty(window, "pktUIMessaging", pktUIGetter("pktUIMessaging", window)); }, // called for each window as it is opened - updateWindow(window) { + updateWindow: function(window) { // insert our three menu items let document = window.document; let hidden = !CustomizableUI.getPlacementOfWidget("pocket-button"); @@ -438,7 +438,7 @@ var PocketOverlay = { sib.parentNode.insertBefore(menu, sib); } }, - onWidgetAfterDOMChange(aWidgetNode) { + onWidgetAfterDOMChange: function(aWidgetNode) { if (aWidgetNode.id != "pocket-button") { return; } @@ -455,12 +455,12 @@ var PocketOverlay = { PocketReader.hidden = hidden; }, - addStyles(win) { + addStyles: function(win) { let utils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); utils.addSheet(this._cachedSheet, this._sheetType); }, - removeStyles(win) { + removeStyles: function(win) { let utils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); utils.removeSheet(gPocketStyleURI, this._sheetType); } diff --git a/browser/extensions/pocket/content/AboutPocket.jsm b/browser/extensions/pocket/content/AboutPocket.jsm index 53e7788b3e47..c7f57aa87304 100644 --- a/browser/extensions/pocket/content/AboutPocket.jsm +++ b/browser/extensions/pocket/content/AboutPocket.jsm @@ -31,11 +31,11 @@ function AboutPage(chromeURL, aboutHost, classID, description, uriFlags) { AboutPage.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]), - getURIFlags(aURI) { // eslint-disable-line no-unused-vars + getURIFlags: function(aURI) { // eslint-disable-line no-unused-vars return this.uriFlags; }, - newChannel(aURI, aLoadInfo) { + newChannel: function(aURI, aLoadInfo) { let newURI = Services.io.newURI(this.chromeURL, null, null); let channel = Services.io.newChannelFromURIWithLoadInfo(newURI, aLoadInfo); @@ -48,20 +48,20 @@ AboutPage.prototype = { return channel; }, - createInstance(outer, iid) { + createInstance: function(outer, iid) { if (outer !== null) { throw Cr.NS_ERROR_NO_AGGREGATION; } return this.QueryInterface(iid); }, - register() { + register: function() { Cm.QueryInterface(Ci.nsIComponentRegistrar).registerFactory( this.classID, this.description, "@mozilla.org/network/protocol/about;1?what=" + this.aboutHost, this); }, - unregister() { + unregister: function() { Cm.QueryInterface(Ci.nsIComponentRegistrar).unregisterFactory( this.classID, this); } diff --git a/browser/extensions/pocket/content/main.js b/browser/extensions/pocket/content/main.js index 07147fd2155a..ff3b5eccaff2 100644 --- a/browser/extensions/pocket/content/main.js +++ b/browser/extensions/pocket/content/main.js @@ -175,7 +175,7 @@ var pktUI = (function() { + inOverflowMenu + "&locale=" + getUILocale(), { - onShow() { + onShow: function() { }, onHide: panelDidHide, width: inOverflowMenu ? overflowMenuWidth : 300, @@ -203,7 +203,7 @@ var pktUI = (function() { } var panelId = showPanel("about:pocket-saved?pockethost=" + Services.prefs.getCharPref("extensions.pocket.site") + "&premiumStatus=" + (pktApi.isPremiumUser() ? '1' : '0') + '&inoverflowmenu=' + inOverflowMenu + "&locale=" + getUILocale(), { - onShow() { + onShow: function() { var saveLinkMessageId = 'saveLink'; // Send error message for invalid url @@ -229,15 +229,15 @@ var pktUI = (function() { // Add url var options = { - success(data, request) { + success: function(data, request) { var item = data.item; var successResponse = { status: "success", - item + item: item }; pktUIMessaging.sendMessageToPanel(panelId, saveLinkMessageId, successResponse); }, - error(error, request) { + error: function(error, request) { // If user is not authorized show singup page if (request.status === 401) { showSignUp(); @@ -418,8 +418,8 @@ var pktUI = (function() { pktUIMessaging.addMessageListener(iframe, _getTagsMessageId, function(panelId, data) { pktApi.getTags(function(tags, usedTags) { pktUIMessaging.sendResponseMessageToPanel(panelId, _getTagsMessageId, { - tags, - usedTags + tags: tags, + usedTags: usedTags }); }); }); @@ -428,17 +428,17 @@ var pktUI = (function() { var _getSuggestedTagsMessageId = "getSuggestedTags"; pktUIMessaging.addMessageListener(iframe, _getSuggestedTagsMessageId, function(panelId, data) { pktApi.getSuggestedTagsForURL(data.url, { - success(data, response) { + success: function(data, response) { var suggestedTags = data.suggested_tags; var successResponse = { status: "success", value: { - suggestedTags + suggestedTags: suggestedTags } } pktUIMessaging.sendResponseMessageToPanel(panelId, _getSuggestedTagsMessageId, successResponse); }, - error(error, response) { + error: function(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _getSuggestedTagsMessageId, error); } }) @@ -448,11 +448,11 @@ var pktUI = (function() { var _addTagsMessageId = "addTags"; pktUIMessaging.addMessageListener(iframe, _addTagsMessageId, function(panelId, data) { pktApi.addTagsToURL(data.url, data.tags, { - success(data, response) { + success: function(data, response) { var successResponse = {status: "success"}; pktUIMessaging.sendResponseMessageToPanel(panelId, _addTagsMessageId, successResponse); }, - error(error, response) { + error: function(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _addTagsMessageId, error); } }); @@ -462,11 +462,11 @@ var pktUI = (function() { var _deleteItemMessageId = "deleteItem"; pktUIMessaging.addMessageListener(iframe, _deleteItemMessageId, function(panelId, data) { pktApi.deleteItem(data.itemId, { - success(data, response) { + success: function(data, response) { var successResponse = {status: "success"}; pktUIMessaging.sendResponseMessageToPanel(panelId, _deleteItemMessageId, successResponse); }, - error(error, response) { + error: function(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _deleteItemMessageId, error); } }) @@ -485,7 +485,7 @@ var pktUI = (function() { strings[str.key] = str.value; } } - pktUIMessaging.sendResponseMessageToPanel(panelId, _initL10NMessageId, { strings }); + pktUIMessaging.sendResponseMessageToPanel(panelId, _initL10NMessageId, { strings: strings }); }); } @@ -588,15 +588,15 @@ var pktUI = (function() { * Public functions */ return { - getPanelFrame, + getPanelFrame: getPanelFrame, - openTabWithUrl, + openTabWithUrl: openTabWithUrl, - pocketPanelDidShow, - pocketPanelDidHide, + pocketPanelDidShow: pocketPanelDidShow, + pocketPanelDidHide: pocketPanelDidHide, - tryToSaveUrl, - tryToSaveCurrentPage + tryToSaveUrl: tryToSaveUrl, + tryToSaveCurrentPage: tryToSaveCurrentPage }; }()); @@ -669,12 +669,12 @@ var pktUIMessaging = (function() { * iframe as a message response */ function sendErrorMessageToPanel(panelId, messageId, error) { - var errorResponse = {status: "error", error}; + var errorResponse = {status: "error", error: error}; sendMessageToPanel(panelId, messageId, errorResponse); } function sendErrorResponseMessageToPanel(panelId, messageId, error) { - var errorResponse = {status: "error", error}; + var errorResponse = {status: "error", error: error}; sendResponseMessageToPanel(panelId, messageId, errorResponse); } @@ -730,10 +730,10 @@ var pktUIMessaging = (function() { * Public */ return { - addMessageListener, - sendMessageToPanel, - sendResponseMessageToPanel, - sendErrorMessageToPanel, - sendErrorResponseMessageToPanel + addMessageListener: addMessageListener, + sendMessageToPanel: sendMessageToPanel, + sendResponseMessageToPanel: sendResponseMessageToPanel, + sendErrorMessageToPanel: sendErrorMessageToPanel, + sendErrorResponseMessageToPanel: sendErrorResponseMessageToPanel } }()); diff --git a/browser/extensions/pocket/content/panels/js/messages.js b/browser/extensions/pocket/content/panels/js/messages.js index eeeceb0a78f4..ae08c3e73a3b 100644 --- a/browser/extensions/pocket/content/panels/js/messages.js +++ b/browser/extensions/pocket/content/panels/js/messages.js @@ -40,7 +40,7 @@ var pktPanelMessaging = (function() { // Payload needs to be an object in format: // { panelId: panelId, data: {} } var messagePayload = { - panelId, + panelId: panelId, data: (payload || {}) }; @@ -70,9 +70,9 @@ var pktPanelMessaging = (function() { * Public functions */ return { - panelIdFromURL, - addMessageListener, - removeMessageListener, - sendMessage + panelIdFromURL: panelIdFromURL, + addMessageListener : addMessageListener, + removeMessageListener : removeMessageListener, + sendMessage: sendMessage }; }()); diff --git a/browser/extensions/pocket/content/panels/js/saved.js b/browser/extensions/pocket/content/panels/js/saved.js index 64642f474a75..ff47020d040c 100644 --- a/browser/extensions/pocket/content/panels/js/saved.js +++ b/browser/extensions/pocket/content/panels/js/saved.js @@ -173,7 +173,7 @@ var PKT_SAVED_OVERLAY = function(options) noResultsHideDropdown: true, scrollKeyboard: true, emptyInputLength: 200, - search_function(term, cb) { + search_function: function(term, cb) { var returnlist = []; if (term.length) { var limit = 15; @@ -191,7 +191,7 @@ var PKT_SAVED_OVERLAY = function(options) } cb(returnlist); }, - textToData(text) { + textToData: function(text) { if ($.trim(text).length > 25 || !$.trim(text).length) { if (text.length > 25) { myself.showTagsError(myself.dictJSON.maxtaglength); @@ -205,7 +205,7 @@ var PKT_SAVED_OVERLAY = function(options) myself.hideTagsError(); return {name:myself.sanitizeText(text.toLowerCase())}; }, - onReady() { + onReady: function() { $('.token-input-dropdown').addClass('token-input-dropdown-tag'); inputwrapper.find('.token-input-input-token input').attr('placeholder', $('.tag-input').attr('placeholder')).css('width', '200px'); if ($('.pkt_ext_suggestedtag_detail').length) { @@ -237,22 +237,22 @@ var PKT_SAVED_OVERLAY = function(options) }); myself.checkPlaceholderStatus(); }, - onAdd() { + onAdd: function() { myself.checkValidTagSubmit(); changestamp = Date.now(); myself.hideInactiveTags(); myself.checkPlaceholderStatus(); }, - onDelete() { + onDelete: function() { myself.checkValidTagSubmit(); changestamp = Date.now(); myself.showActiveTags(); myself.checkPlaceholderStatus(); }, - onShowDropdown() { + onShowDropdown: function() { thePKT_SAVED.sendMessage("expandSavePanel"); }, - onHideDropdown() { + onHideDropdown: function() { thePKT_SAVED.sendMessage("collapseSavePanel"); } }); @@ -457,7 +457,7 @@ var PKT_SAVED_OVERLAY = function(options) }; PKT_SAVED_OVERLAY.prototype = { - create() + create : function() { if (this.active) { @@ -497,7 +497,7 @@ PKT_SAVED_OVERLAY.prototype = { this.initOpenListInput(); this.initAutoCloseEvents(); }, - createPremiumFunctionality() + createPremiumFunctionality: function() { if (this.premiumStatus && !$('.pkt_ext_suggestedtag_detail').length) { @@ -512,7 +512,7 @@ PKT_SAVED_OVERLAY.prototype = { var PKT_SAVED = function() {}; PKT_SAVED.prototype = { - init() { + init: function() { if (this.inited) { return; } @@ -522,15 +522,15 @@ PKT_SAVED.prototype = { this.inited = true; }, - addMessageListener(messageId, callback) { + addMessageListener: function(messageId, callback) { pktPanelMessaging.addMessageListener(this.panelId, messageId, callback); }, - sendMessage(messageId, payload, callback) { + sendMessage: function(messageId, payload, callback) { pktPanelMessaging.sendMessage(this.panelId, messageId, payload, callback); }, - create() { + create: function() { var myself = this; var url = window.location.href.match(/premiumStatus=([\w|\d|\.]*)&?/); if (url && url.length > 1) diff --git a/browser/extensions/pocket/content/panels/js/signup.js b/browser/extensions/pocket/content/panels/js/signup.js index 13794995286d..08821be99324 100644 --- a/browser/extensions/pocket/content/panels/js/signup.js +++ b/browser/extensions/pocket/content/panels/js/signup.js @@ -61,7 +61,7 @@ var PKT_SIGNUP_OVERLAY = function(options) }; PKT_SIGNUP_OVERLAY.prototype = { - create() + create : function() { var controlvariant = window.location.href.match(/controlvariant=([\w|\.]*)&?/); if (controlvariant && controlvariant.length > 1) @@ -145,7 +145,7 @@ PKT_SIGNUP_OVERLAY.prototype = { var PKT_SIGNUP = function() {}; PKT_SIGNUP.prototype = { - init() { + init: function() { if (this.inited) { return; } @@ -155,15 +155,15 @@ PKT_SIGNUP.prototype = { this.inited = true; }, - addMessageListener(messageId, callback) { + addMessageListener: function(messageId, callback) { pktPanelMessaging.addMessageListener(this.panelId, messageId, callback); }, - sendMessage(messageId, payload, callback) { + sendMessage: function(messageId, payload, callback) { pktPanelMessaging.sendMessage(this.panelId, messageId, payload, callback); }, - create() { + create: function() { this.overlay.create(); // tell back end we're ready diff --git a/browser/extensions/pocket/content/pktApi.jsm b/browser/extensions/pocket/content/pktApi.jsm index f18117ec0a13..63b6d415c9e8 100644 --- a/browser/extensions/pocket/content/pktApi.jsm +++ b/browser/extensions/pocket/content/pktApi.jsm @@ -337,7 +337,7 @@ var pktApi = (function() { var sendData = { access_token: accessToken, - url, + url: url, since: since ? since : 0 }; @@ -348,7 +348,7 @@ var pktApi = (function() { return apiRequest({ path: "/firefox/save", data: sendData, - success(data) { + success: function(data) { // Update premium status, tags and since var tags = data.tags; @@ -458,7 +458,7 @@ var pktApi = (function() { * @return {Boolean} Returns Boolean whether the api call started sucessfully */ function addTagsToURL(url, tags, options) { - return addTags({url}, tags, options); + return addTags({url: url}, tags, options); } /** @@ -475,7 +475,7 @@ var pktApi = (function() { // Tags add action var action = { action: "tags_add", - tags + tags: tags }; action = extend(action, actionPart); @@ -584,7 +584,7 @@ var pktApi = (function() { * @return {Boolean} Returns Boolean whether the api call started sucessfully */ function getSuggestedTagsForURL(url, options) { - return getSuggestedTags({url}, options); + return getSuggestedTags({url: url}, options); } /** @@ -600,7 +600,7 @@ var pktApi = (function() { return apiRequest({ path: "/getSuggestedTags", - data, + data: data, success: options.success, error: options.error }); @@ -642,16 +642,16 @@ var pktApi = (function() { * Public functions */ return { - isUserLoggedIn, - clearUserData, - addLink, - deleteItem, - addTagsToItem, - addTagsToURL, - getTags, - isPremiumUser, - getSuggestedTagsForItem, - getSuggestedTagsForURL, - getSignupPanelTabTestVariant, + isUserLoggedIn : isUserLoggedIn, + clearUserData: clearUserData, + addLink: addLink, + deleteItem: deleteItem, + addTagsToItem: addTagsToItem, + addTagsToURL: addTagsToURL, + getTags: getTags, + isPremiumUser: isPremiumUser, + getSuggestedTagsForItem: getSuggestedTagsForItem, + getSuggestedTagsForURL: getSuggestedTagsForURL, + getSignupPanelTabTestVariant: getSignupPanelTabTestVariant, }; }()); diff --git a/browser/extensions/pocket/test/head.js b/browser/extensions/pocket/test/head.js index a4cf877b0196..e044a42c76ba 100644 --- a/browser/extensions/pocket/test/head.js +++ b/browser/extensions/pocket/test/head.js @@ -36,7 +36,7 @@ function promisePocketDisabled() { } return new Promise((resolve, reject) => { let listener = { - onWidgetDestroyed(widgetid) { + onWidgetDestroyed: function(widgetid) { if (widgetid == "pocket-button") { CustomizableUI.removeListener(listener); info( "pocket-button destroyed"); diff --git a/browser/extensions/presentation/bootstrap.js b/browser/extensions/presentation/bootstrap.js index d81e3643adaa..5cd2f11036b9 100644 --- a/browser/extensions/presentation/bootstrap.js +++ b/browser/extensions/presentation/bootstrap.js @@ -33,7 +33,7 @@ function shutdown(aData, aReason) { // Register/unregister a constructor as a factory. function Factory() {} Factory.prototype = { - register(targetConstructor) { + register: function(targetConstructor) { let proto = targetConstructor.prototype; this._classID = proto.classID; @@ -45,7 +45,7 @@ Factory.prototype = { proto.contractID, factory); }, - unregister() { + unregister: function() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(this._classID, this._factory); this._factory = null; @@ -55,14 +55,14 @@ Factory.prototype = { var Presentation = { // PUBLIC APIs - init() { + init: function() { log("init"); // Register PresentationDevicePrompt into a XPCOM component. Cu.import(PRESENTATION_DEVICE_PROMPT_PATH); this._register(); }, - uninit() { + uninit: function() { log("uninit"); // Unregister PresentationDevicePrompt XPCOM component. this._unregister(); @@ -70,13 +70,13 @@ var Presentation = { }, // PRIVATE APIs - _register() { + _register: function() { log("_register"); this._devicePromptFactory = new Factory(); this._devicePromptFactory.register(PresentationDevicePrompt); }, - _unregister() { + _unregister: function() { log("_unregister"); this._devicePromptFactory.unregister(); delete this._devicePromptFactory; diff --git a/browser/extensions/presentation/content/PresentationDevicePrompt.jsm b/browser/extensions/presentation/content/PresentationDevicePrompt.jsm index 949040192712..883ffff34fa3 100644 --- a/browser/extensions/presentation/content/PresentationDevicePrompt.jsm +++ b/browser/extensions/presentation/content/PresentationDevicePrompt.jsm @@ -171,7 +171,7 @@ PresentationPermissionPrompt.prototype = { } return this.principal.URI.hostPort; }, - _createPopupContent() { + _createPopupContent: function() { log("_createPopupContent"); if (!this._devices.length) { @@ -223,7 +223,7 @@ PresentationDevicePrompt.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIPresentationDevicePrompt]), // This will be fired when window.PresentationRequest(URL).start() is called. - promptDeviceSelection(aRequest) { + promptDeviceSelection: function(aRequest) { log("promptDeviceSelection"); // Cancel request if no available device. @@ -238,7 +238,7 @@ PresentationDevicePrompt.prototype = { let promptUI = new PresentationPermissionPrompt(aRequest, devices); promptUI.prompt(); }, - _loadDevices() { + _loadDevices: function() { let deviceManager = Cc["@mozilla.org/presentation-device/manager;1"] .getService(Ci.nsIPresentationDeviceManager); let devices = deviceManager.getAvailableDevices().QueryInterface(Ci.nsIArray); diff --git a/browser/modules/AboutHome.jsm b/browser/modules/AboutHome.jsm index 627e7bd56af2..01cbafba99f4 100644 --- a/browser/modules/AboutHome.jsm +++ b/browser/modules/AboutHome.jsm @@ -104,7 +104,7 @@ var AboutHome = { "AboutHome:MaybeShowAutoMigrationUndoNotification", ], - init() { + init: function() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); for (let msg of this.MESSAGES) { @@ -112,7 +112,7 @@ var AboutHome = { } }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { let window = aMessage.target.ownerGlobal; switch (aMessage.name) { @@ -160,7 +160,7 @@ var AboutHome = { // Send all the chrome-privileged data needed by about:home. This // gets re-sent when the search engine changes. - sendAboutHomeData(target) { + sendAboutHomeData: function(target) { let wrapper = {}; Components.utils.import("resource:///modules/sessionstore/SessionStore.jsm", wrapper); diff --git a/browser/modules/AboutNewTab.jsm b/browser/modules/AboutNewTab.jsm index afb04ad499fb..145cec09a71a 100644 --- a/browser/modules/AboutNewTab.jsm +++ b/browser/modules/AboutNewTab.jsm @@ -22,17 +22,17 @@ var AboutNewTab = { pageListener: null, - init() { + init: function() { this.pageListener = new RemotePages("about:newtab"); this.pageListener.addMessageListener("NewTab:Customize", this.customize.bind(this)); }, - customize(message) { + customize: function(message) { NewTabUtils.allPages.enabled = message.data.enabled; NewTabUtils.allPages.enhanced = message.data.enhanced; }, - uninit() { + uninit: function() { this.pageListener.destroy(); this.pageListener = null; }, diff --git a/browser/modules/BrowserUITelemetry.jsm b/browser/modules/BrowserUITelemetry.jsm index 8f74aca423a8..6e54d45df651 100644 --- a/browser/modules/BrowserUITelemetry.jsm +++ b/browser/modules/BrowserUITelemetry.jsm @@ -170,7 +170,7 @@ const BUCKET_PREFIX = "bucket_"; const BUCKET_SEPARATOR = "|"; this.BrowserUITelemetry = { - init() { + init: function() { UITelemetry.addSimpleMeasureFunction("toolbars", this.getToolbarMeasures.bind(this)); UITelemetry.addSimpleMeasureFunction("contextmenu", @@ -189,7 +189,7 @@ this.BrowserUITelemetry = { CustomizableUI.addListener(this); }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { switch (aTopic) { case "sessionstore-windows-restored": this._gatherFirstWindowMeasurements(); @@ -241,7 +241,7 @@ this.BrowserUITelemetry = { * @returns a reference to the second last object in the chain - * so in our example, that'd be "b". */ - _ensureObjectChain(aKeys, aEndWith, aRoot) { + _ensureObjectChain: function(aKeys, aEndWith, aRoot) { let current = aRoot; let parent = null; aKeys.unshift(this._bucket); @@ -260,13 +260,13 @@ this.BrowserUITelemetry = { }, _countableEvents: {}, - _countEvent(aKeyArray, root = this._countableEvents) { + _countEvent: function(aKeyArray, root = this._countableEvents) { let countObject = this._ensureObjectChain(aKeyArray, 0, root); let lastItemKey = aKeyArray[aKeyArray.length - 1]; countObject[lastItemKey]++; }, - _countMouseUpEvent(aCategory, aAction, aButton) { + _countMouseUpEvent: function(aCategory, aAction, aButton) { const BUTTONS = ["left", "middle", "right"]; let buttonKey = BUTTONS[aButton]; if (buttonKey) { @@ -275,7 +275,7 @@ this.BrowserUITelemetry = { }, _firstWindowMeasurements: null, - _gatherFirstWindowMeasurements() { + _gatherFirstWindowMeasurements: function() { // We'll gather measurements as soon as the session has restored. // We do this here instead of waiting for UITelemetry to ask for // our measurements because at that point all browser windows have @@ -295,7 +295,7 @@ this.BrowserUITelemetry = { }); }, - _registerWindow(aWindow) { + _registerWindow: function(aWindow) { aWindow.addEventListener("unload", this); let document = aWindow.document; @@ -323,7 +323,7 @@ this.BrowserUITelemetry = { WINDOW_DURATION_MAP.set(aWindow, {}); }, - _unregisterWindow(aWindow) { + _unregisterWindow: function(aWindow) { aWindow.removeEventListener("unload", this); let document = aWindow.document; @@ -349,7 +349,7 @@ this.BrowserUITelemetry = { } }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "unload": this._unregisterWindow(aEvent.currentTarget); @@ -363,7 +363,7 @@ this.BrowserUITelemetry = { } }, - _handleMouseUp(aEvent) { + _handleMouseUp: function(aEvent) { let targetID = aEvent.currentTarget.id; switch (targetID) { @@ -381,7 +381,7 @@ this.BrowserUITelemetry = { } }, - _handleMouseDown(aEvent) { + _handleMouseDown: function(aEvent) { if (aEvent.currentTarget.id == "PanelUI-menu-button") { // _countMouseUpEvent expects a detail for the second argument, // but we don't really have any details to give. Just passing in @@ -391,13 +391,13 @@ this.BrowserUITelemetry = { } }, - _PlacesChevronMouseUp(aEvent) { + _PlacesChevronMouseUp: function(aEvent) { let target = aEvent.originalTarget; let result = target.id == "PlacesChevron" ? "chevron" : "overflowed-item"; this._countMouseUpEvent("click-bookmarks-bar", result, aEvent.button); }, - _PlacesToolbarItemsMouseUp(aEvent) { + _PlacesToolbarItemsMouseUp: function(aEvent) { let target = aEvent.originalTarget; // If this isn't a bookmark-item, we don't care about it. if (!target.classList.contains("bookmark-item")) { @@ -408,14 +408,14 @@ this.BrowserUITelemetry = { this._countMouseUpEvent("click-bookmarks-bar", result, aEvent.button); }, - _menubarMouseUp(aEvent) { + _menubarMouseUp: function(aEvent) { let target = aEvent.originalTarget; let tag = target.localName let result = (tag == "menu" || tag == "menuitem") ? tag : "other"; this._countMouseUpEvent("click-menubar", result, aEvent.button); }, - _bookmarksMenuButtonMouseUp(aEvent) { + _bookmarksMenuButtonMouseUp: function(aEvent) { let bookmarksWidget = CustomizableUI.getWidget("bookmarks-menu-button"); if (bookmarksWidget.areaType == CustomizableUI.TYPE_MENU_PANEL) { // In the menu panel, only the star is visible, and that opens up the @@ -441,7 +441,7 @@ this.BrowserUITelemetry = { } }, - _checkForBuiltinItem(aEvent) { + _checkForBuiltinItem: function(aEvent) { let item = aEvent.originalTarget; // We don't want to count clicks on the private browsing @@ -482,7 +482,7 @@ this.BrowserUITelemetry = { } }, - _getWindowMeasurements(aWindow, searchResult) { + _getWindowMeasurements: function(aWindow, searchResult) { let document = aWindow.document; let result = {}; @@ -582,14 +582,14 @@ this.BrowserUITelemetry = { return result; }, - getToolbarMeasures() { + getToolbarMeasures: function() { let result = this._firstWindowMeasurements || {}; result.countableEvents = this._countableEvents; result.durations = this._durations; return result; }, - getSyncState() { + getSyncState: function() { let result = {}; for (let sub of ["desktop", "mobile"]) { let count = 0; @@ -601,11 +601,11 @@ this.BrowserUITelemetry = { return result; }, - countCustomizationEvent(aEventType) { + countCustomizationEvent: function(aEventType) { this._countEvent(["customize", aEventType]); }, - countSearchEvent(source, query, selection) { + countSearchEvent: function(source, query, selection) { this._countEvent(["search", source]); if ((/^[a-zA-Z]+:[^\/\\]/).test(query)) { this._countEvent(["search", "urlbar-keyword"]); @@ -615,35 +615,35 @@ this.BrowserUITelemetry = { } }, - countOneoffSearchEvent(id, type, where) { + countOneoffSearchEvent: function(id, type, where) { this._countEvent(["search-oneoff", id, type, where]); }, - countSearchSettingsEvent(source) { + countSearchSettingsEvent: function(source) { this._countEvent(["click-builtin-item", source, "search-settings"]); }, - countPanicEvent(timeId) { + countPanicEvent: function(timeId) { this._countEvent(["forget-button", timeId]); }, - countTabMutingEvent(action, reason) { + countTabMutingEvent: function(action, reason) { this._countEvent(["tab-audio-control", action, reason || "no reason given"]); }, - countSyncedTabEvent(what, where) { + countSyncedTabEvent: function(what, where) { // "what" will be, eg, "open" // "where" will be "toolbarbutton-subview" or "sidebar" this._countEvent(["synced-tabs", what, where]); }, - countSidebarEvent(sidebarID, action) { + countSidebarEvent: function(sidebarID, action) { // sidebarID is the ID of the sidebar (duh!) // action will be "hide" or "show" this._countEvent(["sidebar", sidebarID, action]); }, - _logAwesomeBarSearchResult(url) { + _logAwesomeBarSearchResult: function(url) { let spec = Services.search.parseSubmissionURL(url); if (spec.engine) { let matchedEngine = "default"; @@ -658,7 +658,7 @@ this.BrowserUITelemetry = { customization: [], }, - onCustomizeStart(aWindow) { + onCustomizeStart: function(aWindow) { this._countEvent(["customize", "start"]); let durationMap = WINDOW_DURATION_MAP.get(aWindow); if (!durationMap) { @@ -672,12 +672,12 @@ this.BrowserUITelemetry = { }; }, - onCustomizeEnd(aWindow) { + onCustomizeEnd: function(aWindow) { let durationMap = WINDOW_DURATION_MAP.get(aWindow); if (durationMap && "customization" in durationMap) { let duration = aWindow.performance.now() - durationMap.customization.start; this._durations.customization.push({ - duration, + duration: duration, bucket: durationMap.customization.bucket, }); delete durationMap.customization; @@ -720,7 +720,7 @@ this.BrowserUITelemetry = { _contextMenuInteractions: {}, - registerContextMenuInteraction(keys, itemID) { + registerContextMenuInteraction: function(keys, itemID) { if (itemID) { if (itemID == "openlinkprivate") { // Don't record anything, not even an other-item count @@ -738,7 +738,7 @@ this.BrowserUITelemetry = { this._countEvent(keys, this._contextMenuInteractions); }, - getContextMenuInfo() { + getContextMenuInfo: function() { return this._contextMenuInteractions; }, @@ -777,7 +777,7 @@ this.BrowserUITelemetry = { * * @param aName Name of bucket, or null for default bucket name (__DEFAULT__) */ - setBucket(aName) { + setBucket: function(aName) { if (this._bucketTimer) { Timer.clearTimeout(this._bucketTimer); this._bucketTimer = null; @@ -820,7 +820,7 @@ this.BrowserUITelemetry = { * timed as though they started expiring 300ms before * setExpiringBucket was called. */ - setExpiringBucket(aName, aTimeSteps, aTimeOffset = 0) { + setExpiringBucket: function(aName, aTimeSteps, aTimeOffset = 0) { if (aTimeSteps.length === 0) { this.setBucket(null); return; @@ -858,7 +858,7 @@ this.BrowserUITelemetry = { * * @return Minimal string representation. */ - _toTimeStr(aTimeMS) { + _toTimeStr: function(aTimeMS) { let timeStr = ""; function reduce(aUnitLength, aSymbol) { diff --git a/browser/modules/CastingApps.jsm b/browser/modules/CastingApps.jsm index 3d4f6f5b0941..6f9be7c3ba5a 100644 --- a/browser/modules/CastingApps.jsm +++ b/browser/modules/CastingApps.jsm @@ -12,17 +12,17 @@ Cu.import("resource://gre/modules/SimpleServiceDiscovery.jsm"); var CastingApps = { - _sendEventToVideo(element, data) { + _sendEventToVideo: function(element, data) { let event = element.ownerDocument.createEvent("CustomEvent"); event.initCustomEvent("media-videoCasting", false, true, JSON.stringify(data)); element.dispatchEvent(event); }, - makeURI(url, charset, baseURI) { + makeURI: function(url, charset, baseURI) { return Services.io.newURI(url, charset, baseURI); }, - getVideo(element) { + getVideo: function(element) { if (!element) { return null; } @@ -45,7 +45,7 @@ var CastingApps = { // Use the file extension to guess the mime type let sourceURI = this.makeURI(sourceURL, null, this.makeURI(element.baseURI)); if (this.allowableExtension(sourceURI, extensions)) { - return { element, source: sourceURI.spec, poster: posterURL, sourceURI}; + return { element: element, source: sourceURI.spec, poster: posterURL, sourceURI: sourceURI}; } } @@ -58,14 +58,14 @@ var CastingApps = { // Using the type attribute is our ideal way to guess the mime type. Otherwise, // fallback to using the file extension to guess the mime type if (this.allowableMimeType(sourceNode.type, types) || this.allowableExtension(sourceURI, extensions)) { - return { element, source: sourceURI.spec, poster: posterURL, sourceURI, type: sourceNode.type }; + return { element: element, source: sourceURI.spec, poster: posterURL, sourceURI: sourceURI, type: sourceNode.type }; } } return null; }, - sendVideoToService(videoElement, service) { + sendVideoToService: function(videoElement, service) { if (!service) return; @@ -101,9 +101,9 @@ var CastingApps = { } this.session = { - service, - app, - remoteMedia, + service: service, + app: app, + remoteMedia: remoteMedia, data: { title: video.title, source: video.source, @@ -116,7 +116,7 @@ var CastingApps = { }); }, - getServicesForVideo(videoElement) { + getServicesForVideo: function(videoElement) { let video = this.getVideo(videoElement); if (!video) { return {}; @@ -130,12 +130,12 @@ var CastingApps = { return filteredServices; }, - getServicesForMirroring() { + getServicesForMirroring: function() { return SimpleServiceDiscovery.services.filter(service => service.mirror); }, // RemoteMedia callback API methods - onRemoteMediaStart(remoteMedia) { + onRemoteMediaStart: function(remoteMedia) { if (!this.session) { return; } @@ -148,17 +148,17 @@ var CastingApps = { } }, - onRemoteMediaStop(remoteMedia) { + onRemoteMediaStop: function(remoteMedia) { }, - onRemoteMediaStatus(remoteMedia) { + onRemoteMediaStatus: function(remoteMedia) { }, - allowableExtension(uri, extensions) { + allowableExtension: function(uri, extensions) { return (uri instanceof Ci.nsIURL) && extensions.indexOf(uri.fileExtension) != -1; }, - allowableMimeType(type, types) { + allowableMimeType: function(type, types) { return types.indexOf(type) != -1; } }; diff --git a/browser/modules/ContentClick.jsm b/browser/modules/ContentClick.jsm index d2e0419054c4..997588bcd5ba 100644 --- a/browser/modules/ContentClick.jsm +++ b/browser/modules/ContentClick.jsm @@ -16,12 +16,12 @@ Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); var ContentClick = { - init() { + init: function() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Content:Click", this); }, - receiveMessage(message) { + receiveMessage: function(message) { switch (message.name) { case "Content:Click": this.contentAreaClick(message.json, message.target) @@ -29,7 +29,7 @@ var ContentClick = { } }, - contentAreaClick(json, browser) { + contentAreaClick: function(json, browser) { // This is heavily based on contentAreaClick from browser.js (Bug 903016) // The json is set up in a way to look like an Event. let window = browser.ownerGlobal; diff --git a/browser/modules/ContentCrashHandlers.jsm b/browser/modules/ContentCrashHandlers.jsm index dda1780ac1fc..18dd516391a6 100644 --- a/browser/modules/ContentCrashHandlers.jsm +++ b/browser/modules/ContentCrashHandlers.jsm @@ -55,7 +55,7 @@ this.TabCrashHandler = { return this.prefs = Services.prefs.getBranch("browser.tabs.crashReporting."); }, - init() { + init: function() { if (this.initialized) return; this.initialized = true; @@ -74,7 +74,7 @@ this.TabCrashHandler = { this.pageListener.addMessageListener("restoreAll", this.receiveMessage.bind(this)); }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { switch (aTopic) { case "ipc:content-shutdown": { aSubject.QueryInterface(Ci.nsIPropertyBag2); @@ -140,7 +140,7 @@ this.TabCrashHandler = { } }, - receiveMessage(message) { + receiveMessage: function(message) { let browser = message.target.browser; let gBrowser = browser.ownerGlobal.gBrowser; let tab = gBrowser.getTabForBrowser(browser); @@ -400,7 +400,7 @@ this.TabCrashHandler = { this.removeSubmitCheckboxesForSameCrash(childID); }, - removeSubmitCheckboxesForSameCrash(childID) { + removeSubmitCheckboxesForSameCrash: function(childID) { let enumerator = Services.wm.getEnumerator("navigator:browser"); while (enumerator.hasMoreElements()) { let window = enumerator.getNext(); @@ -428,7 +428,7 @@ this.TabCrashHandler = { } }, - onAboutTabCrashedLoad(message) { + onAboutTabCrashedLoad: function(message) { this._crashedTabCount++; // Broadcast to all about:tabcrashed pages a count of @@ -834,7 +834,7 @@ this.UnsubmittedCrashHandler = { }, { label: gNavigatorBundle.GetStringFromName("pendingCrashReports.viewAll"), - callback() { + callback: function() { chromeWin.openUILinkIn("about:crashes", "tab"); return true; }, diff --git a/browser/modules/ContentLinkHandler.jsm b/browser/modules/ContentLinkHandler.jsm index 90e33470d0f5..443cae2daf71 100644 --- a/browser/modules/ContentLinkHandler.jsm +++ b/browser/modules/ContentLinkHandler.jsm @@ -27,7 +27,7 @@ const SIZES_TELEMETRY_ENUM = { }; this.ContentLinkHandler = { - init(chromeGlobal) { + init: function(chromeGlobal) { chromeGlobal.addEventListener("DOMLinkAdded", (event) => { this.onLinkEvent(event, chromeGlobal); }, false); @@ -36,7 +36,7 @@ this.ContentLinkHandler = { }, false); }, - onLinkEvent(event, chromeGlobal) { + onLinkEvent: function(event, chromeGlobal) { var link = event.originalTarget; var rel = link.rel && link.rel.toLowerCase(); if (!link || !link.ownerDocument || !rel || !link.href) @@ -124,7 +124,7 @@ this.ContentLinkHandler = { { let engine = { title: link.title, href: link.href }; chromeGlobal.sendAsyncMessage("Link:AddSearch", - {engine, + {engine: engine, url: link.ownerDocument.documentURI}); searchAdded = true; } @@ -134,7 +134,7 @@ this.ContentLinkHandler = { } }, - getLinkIconURI(aLink) { + getLinkIconURI: function(aLink) { let targetDoc = aLink.ownerDocument; var uri = BrowserUtils.makeURI(aLink.href, targetDoc.characterSet); try { diff --git a/browser/modules/ContentSearch.jsm b/browser/modules/ContentSearch.jsm index a825cc698559..42525702905c 100644 --- a/browser/modules/ContentSearch.jsm +++ b/browser/modules/ContentSearch.jsm @@ -108,7 +108,7 @@ this.ContentSearch = { // fetch cancellation from _cancelSuggestions. _currentSuggestion: null, - init() { + init: function() { Cc["@mozilla.org/globalmessagemanager;1"]. getService(Ci.nsIMessageListenerManager). addMessageListener(INBOUND_MESSAGE, this); @@ -133,7 +133,7 @@ this.ContentSearch = { return this._searchSuggestionUIStrings; }, - destroy() { + destroy: function() { if (this._destroyedPromise) { return this._destroyedPromise; } @@ -154,13 +154,13 @@ this.ContentSearch = { * @param messageManager * The MessageManager object of the selected browser. */ - focusInput(messageManager) { + focusInput: function(messageManager) { messageManager.sendAsyncMessage(OUTBOUND_MESSAGE, { type: "FocusInput" }); }, - receiveMessage(msg) { + receiveMessage: function(msg) { // Add a temporary event handler that exists only while the message is in // the event queue. If the message's source docshell changes browsers in // the meantime, then we need to update msg.target. event.detail will be @@ -190,13 +190,13 @@ this.ContentSearch = { this._processEventQueue(); }, - observe(subj, topic, data) { + observe: function(subj, topic, data) { switch (topic) { case "nsPref:changed": case "browser-search-engine-modified": this._eventQueue.push({ type: "Observe", - data, + data: data, }); this._processEventQueue(); break; @@ -207,7 +207,7 @@ this.ContentSearch = { } }, - removeFormHistoryEntry(msg, entry) { + removeFormHistoryEntry: function(msg, entry) { let browserData = this._suggestionDataForBrowser(msg.target); if (browserData && browserData.previousFormHistoryResult) { let { previousFormHistoryResult } = browserData; @@ -220,7 +220,7 @@ this.ContentSearch = { } }, - performSearch(msg, data) { + performSearch: function(msg, data) { this._ensureDataHasProperties(data, [ "engineName", "searchString", @@ -273,7 +273,7 @@ this.ContentSearch = { let priv = PrivateBrowsingUtils.isBrowserPrivate(browser); // fetch() rejects its promise if there's a pending request, but since we // process our event queue serially, there's never a pending request. - this._currentSuggestion = { controller, target: browser }; + this._currentSuggestion = { controller: controller, target: browser }; let suggestions = yield controller.fetch(searchString, priv, engine); this._currentSuggestion = null; @@ -350,7 +350,7 @@ this.ContentSearch = { return state; }), - _processEventQueue() { + _processEventQueue: function() { if (this._currentEventPromise || !this._eventQueue.length) { return; } @@ -369,7 +369,7 @@ this.ContentSearch = { }.bind(this)); }, - _cancelSuggestions(msg) { + _cancelSuggestions: function(msg) { let cancelled = false; // cancel active suggestion request if (this._currentSuggestion && this._currentSuggestion.target === msg.target) { @@ -401,25 +401,25 @@ this.ContentSearch = { } }), - _onMessageGetState(msg, data) { + _onMessageGetState: function(msg, data) { return this.currentStateObj().then(state => { this._reply(msg, "State", state); }); }, - _onMessageGetStrings(msg, data) { + _onMessageGetStrings: function(msg, data) { this._reply(msg, "Strings", this.searchSuggestionUIStrings); }, - _onMessageSearch(msg, data) { + _onMessageSearch: function(msg, data) { this.performSearch(msg, data); }, - _onMessageSetCurrentEngine(msg, data) { + _onMessageSetCurrentEngine: function(msg, data) { Services.search.currentEngine = Services.search.getEngineByName(data); }, - _onMessageManageEngines(msg, data) { + _onMessageManageEngines: function(msg, data) { let browserWin = msg.target.ownerGlobal; browserWin.openPreferences("paneSearch"); }, @@ -444,11 +444,11 @@ this.ContentSearch = { yield this.addFormHistoryEntry(msg, entry); }), - _onMessageRemoveFormHistoryEntry(msg, entry) { + _onMessageRemoveFormHistoryEntry: function(msg, entry) { this.removeFormHistoryEntry(msg, entry); }, - _onMessageSpeculativeConnect(msg, engineName) { + _onMessageSpeculativeConnect: function(msg, engineName) { let engine = Services.search.getEngineByName(engineName); if (!engine) { throw new Error("Unknown engine name: " + engineName); @@ -473,7 +473,7 @@ this.ContentSearch = { } }), - _suggestionDataForBrowser(browser, create = false) { + _suggestionDataForBrowser: function(browser, create = false) { let data = this._suggestionMap.get(browser); if (!data && create) { // Since one SearchSuggestionController instance is meant to be used per @@ -487,7 +487,7 @@ this.ContentSearch = { return data; }, - _reply(msg, type, data) { + _reply: function(msg, type, data) { // We reply asyncly to messages, and by the time we reply the browser we're // responding to may have been destroyed. messageManager is null then. if (!Cu.isDeadWrapper(msg.target) && msg.target.messageManager) { @@ -495,16 +495,16 @@ this.ContentSearch = { } }, - _broadcast(type, data) { + _broadcast: function(type, data) { Cc["@mozilla.org/globalmessagemanager;1"]. getService(Ci.nsIMessageListenerManager). broadcastAsyncMessage(...this._msgArgs(type, data)); }, - _msgArgs(type, data) { + _msgArgs: function(type, data) { return [OUTBOUND_MESSAGE, { - type, - data, + type: type, + data: data, }]; }, @@ -515,13 +515,13 @@ this.ContentSearch = { "searchWithEngine", [engine.name], 1); let obj = { name: engine.name, - placeholder, + placeholder: placeholder, iconBuffer: yield this._arrayBufferFromDataURI(favicon), }; return obj; }), - _arrayBufferFromDataURI(uri) { + _arrayBufferFromDataURI: function(uri) { if (!uri) { return Promise.resolve(null); } @@ -546,7 +546,7 @@ this.ContentSearch = { return deferred.promise; }, - _ensureDataHasProperties(data, requiredProperties) { + _ensureDataHasProperties: function(data, requiredProperties) { for (let prop of requiredProperties) { if (!(prop in data)) { throw new Error("Message data missing required property: " + prop); @@ -554,7 +554,7 @@ this.ContentSearch = { } }, - _initService() { + _initService: function() { if (!this._initServicePromise) { let deferred = Promise.defer(); this._initServicePromise = deferred.promise; diff --git a/browser/modules/ContentWebRTC.jsm b/browser/modules/ContentWebRTC.jsm index bc6930ea34ba..24c25a3b2b19 100644 --- a/browser/modules/ContentWebRTC.jsm +++ b/browser/modules/ContentWebRTC.jsm @@ -19,7 +19,7 @@ const kBrowserURL = "chrome://browser/content/browser.xul"; this.ContentWebRTC = { _initialized: false, - init() { + init: function() { if (this._initialized) return; @@ -33,7 +33,7 @@ this.ContentWebRTC = { Services.obs.addObserver(processShutdown, "content-child-shutdown", false); }, - uninit() { + uninit: function() { Services.obs.removeObserver(handleGUMRequest, "getUserMedia:request"); Services.obs.removeObserver(handlePCRequest, "PeerConnection:request"); Services.obs.removeObserver(updateIndicators, "recording-device-events"); @@ -46,7 +46,7 @@ this.ContentWebRTC = { }, // Called only for 'unload' to remove pending gUM prompts in reloaded frames. - handleEvent(aEvent) { + handleEvent: function(aEvent) { let contentWindow = aEvent.target.defaultView; let mm = getMessageManagerForWindow(contentWindow); for (let key of contentWindow.pendingGetUserMediaRequests.keys()) { @@ -57,7 +57,7 @@ this.ContentWebRTC = { } }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { switch (aMessage.name) { case "rtcpeer:Allow": case "rtcpeer:Deny": { @@ -115,9 +115,9 @@ function handlePCRequest(aSubject, aTopic, aData) { contentWindow.pendingPeerConnectionRequests.add(callID); let request = { - windowID, - innerWindowID, - callID, + windowID: windowID, + innerWindowID: innerWindowID, + callID: callID, documentURI: contentWindow.document.documentURI, secure: isSecure, }; @@ -210,11 +210,11 @@ function prompt(aContentWindow, aWindowID, aCallID, aConstraints, aDevices, aSec windowID: aWindowID, documentURI: aContentWindow.document.documentURI, secure: aSecure, - requestTypes, - sharingScreen, - sharingAudio, - audioDevices, - videoDevices + requestTypes: requestTypes, + sharingScreen: sharingScreen, + sharingAudio: sharingAudio, + audioDevices: audioDevices, + videoDevices: videoDevices }; let mm = getMessageManagerForWindow(aContentWindow); diff --git a/browser/modules/DirectoryLinksProvider.jsm b/browser/modules/DirectoryLinksProvider.jsm index 2563436c553e..9a15397a410f 100644 --- a/browser/modules/DirectoryLinksProvider.jsm +++ b/browser/modules/DirectoryLinksProvider.jsm @@ -268,7 +268,7 @@ var DirectoryLinksProvider = { } }, - _cacheSuggestedLinks(link) { + _cacheSuggestedLinks: function(link) { // Don't cache links that don't have the expected 'frecent_sites' if (!link.frecent_sites) { return; @@ -729,7 +729,7 @@ var DirectoryLinksProvider = { }.bind(this)); }, - _handleManyLinksChanged() { + _handleManyLinksChanged: function() { this._topSitesWithSuggestedLinks.clear(); this._suggestedLinks.forEach((suggestedLinks, site) => { if (NewTabUtils.isTopPlacesSite(site)) { @@ -744,7 +744,7 @@ var DirectoryLinksProvider = { * * @return true if _topSitesWithSuggestedLinks was modified, false otherwise. */ - _handleLinkChanged(aLink) { + _handleLinkChanged: function(aLink) { let changedLinkSite = NewTabUtils.extractSite(aLink.url); let linkStored = this._topSitesWithSuggestedLinks.has(changedLinkSite); @@ -768,13 +768,13 @@ var DirectoryLinksProvider = { return false; }, - _populatePlacesLinks() { + _populatePlacesLinks: function() { NewTabUtils.links.populateProviderCache(NewTabUtils.placesProvider, () => { this._handleManyLinksChanged(); }); }, - onDeleteURI(aProvider, aLink) { + onDeleteURI: function(aProvider, aLink) { let {url} = aLink; // remove clicked flag for that url and // call observer upon disk write completion @@ -783,14 +783,14 @@ var DirectoryLinksProvider = { }); }, - onClearHistory() { + onClearHistory: function() { // remove all clicked flags and call observers upon file write this._removeAllTileClicks().then(() => { this._callObservers("onClearHistory"); }); }, - onLinkChanged(aProvider, aLink) { + onLinkChanged: function(aProvider, aLink) { // Make sure NewTabUtils.links handles the notification first. setTimeout(() => { if (this._handleLinkChanged(aLink) || this._shouldUpdateSuggestedTile()) { @@ -799,14 +799,14 @@ var DirectoryLinksProvider = { }, 0); }, - onManyLinksChanged() { + onManyLinksChanged: function() { // Make sure NewTabUtils.links handles the notification first. setTimeout(() => { this._handleManyLinksChanged(); }, 0); }, - _getCurrentTopSiteCount() { + _getCurrentTopSiteCount: function() { let visibleTopSiteCount = 0; let newTabLinks = NewTabUtils.links.getLinks(); for (let link of newTabLinks.slice(0, MIN_VISIBLE_HISTORY_TILES)) { @@ -822,7 +822,7 @@ var DirectoryLinksProvider = { return visibleTopSiteCount; }, - _shouldUpdateSuggestedTile() { + _shouldUpdateSuggestedTile: function() { let sortedLinks = NewTabUtils.getProviderLinks(this); let mostFrecentLink = {}; @@ -850,7 +850,7 @@ var DirectoryLinksProvider = { * * @return the chosen suggested tile, or undefined if there isn't one */ - _updateSuggestedTile() { + _updateSuggestedTile: function() { let sortedLinks = NewTabUtils.getProviderLinks(this); if (!sortedLinks) { @@ -1249,7 +1249,7 @@ var DirectoryLinksProvider = { } }, - _removeObservers() { + _removeObservers: function() { this._observers.clear(); } }; diff --git a/browser/modules/E10SUtils.jsm b/browser/modules/E10SUtils.jsm index 5f6e9243d152..fdfde0a157d0 100644 --- a/browser/modules/E10SUtils.jsm +++ b/browser/modules/E10SUtils.jsm @@ -46,13 +46,13 @@ this.E10SUtils = { WEB_REMOTE_TYPE, FILE_REMOTE_TYPE, - canLoadURIInProcess(aURL, aProcess) { + canLoadURIInProcess: function(aURL, aProcess) { let remoteType = aProcess == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT ? DEFAULT_REMOTE_TYPE : NOT_REMOTE; return remoteType == this.getRemoteTypeForURI(aURL, true, remoteType); }, - getRemoteTypeForURI(aURL, aMultiProcess, + getRemoteTypeForURI: function(aURL, aMultiProcess, aPreferredRemoteType = DEFAULT_REMOTE_TYPE) { if (!aMultiProcess) { return NOT_REMOTE; @@ -143,12 +143,12 @@ this.E10SUtils = { return validatedWebRemoteType(aPreferredRemoteType); }, - shouldLoadURIInThisProcess(aURI) { + shouldLoadURIInThisProcess: function(aURI) { let remoteType = Services.appinfo.remoteType; return remoteType == this.getRemoteTypeForURI(aURI.spec, true, remoteType); }, - shouldLoadURI(aDocShell, aURI, aReferrer) { + shouldLoadURI: function(aDocShell, aURI, aReferrer) { // Inner frames should always load in the current process if (aDocShell.QueryInterface(Ci.nsIDocShellTreeItem).sameTypeParent) return true; @@ -157,7 +157,7 @@ this.E10SUtils = { return this.shouldLoadURIInThisProcess(aURI); }, - redirectLoad(aDocShell, aURI, aReferrer, aFreshProcess) { + redirectLoad: function(aDocShell, aURI, aReferrer, aFreshProcess) { // Retarget the load to the correct process let messageManager = aDocShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIContentFrameMessageManager); @@ -175,7 +175,7 @@ this.E10SUtils = { return false; }, - wrapHandlingUserInput(aWindow, aIsHandling, aCallback) { + wrapHandlingUserInput: function(aWindow, aIsHandling, aCallback) { var handlingUserInput; try { handlingUserInput = aWindow.QueryInterface(Ci.nsIInterfaceRequestor) diff --git a/browser/modules/Feeds.jsm b/browser/modules/Feeds.jsm index c9708488080a..179d2b83d23e 100644 --- a/browser/modules/Feeds.jsm +++ b/browser/modules/Feeds.jsm @@ -72,7 +72,7 @@ this.Feeds = { * Whether this is already a known feed or not, if true only a security * check will be performed. */ - isValidFeed(aLink, aPrincipal, aIsFeed) { + isValidFeed: function(aLink, aPrincipal, aIsFeed) { if (!aLink || !aPrincipal) return false; diff --git a/browser/modules/FormSubmitObserver.jsm b/browser/modules/FormSubmitObserver.jsm index 01bd144739df..7de3ab30de8a 100644 --- a/browser/modules/FormSubmitObserver.jsm +++ b/browser/modules/FormSubmitObserver.jsm @@ -38,7 +38,7 @@ FormSubmitObserver.prototype = * Public apis */ - init(aWindow, aTabChildGlobal) + init: function(aWindow, aTabChildGlobal) { this._content = aWindow; this._tab = aTabChildGlobal; @@ -57,7 +57,7 @@ FormSubmitObserver.prototype = this._tab.addEventListener("unload", this, false); }, - uninit() + uninit: function() { Services.obs.removeObserver(this, "invalidformsubmit"); this._content.removeEventListener("pageshow", this, false); @@ -72,7 +72,7 @@ FormSubmitObserver.prototype = * Events */ - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "pageshow": if (this._isRootDocumentEvent(aEvent)) { @@ -95,7 +95,7 @@ FormSubmitObserver.prototype = * nsIFormSubmitObserver */ - notifyInvalidSubmit(aFormElement, aInvalidElements) + notifyInvalidSubmit : function(aFormElement, aInvalidElements) { // We are going to handle invalid form submission attempt by focusing the // first invalid element and show the corresponding validation message in a @@ -149,7 +149,7 @@ FormSubmitObserver.prototype = * with. Updates the validation message or closes the popup if form data * becomes valid. */ - _onInput(aEvent) { + _onInput: function(aEvent) { let element = aEvent.originalTarget; // If the form input is now valid, hide the popup. @@ -170,7 +170,7 @@ FormSubmitObserver.prototype = * Blur event handler in which we disconnect from the form element and * hide the popup. */ - _onBlur(aEvent) { + _onBlur: function(aEvent) { aEvent.originalTarget.removeEventListener("input", this, false); aEvent.originalTarget.removeEventListener("blur", this, false); this._element = null; @@ -182,7 +182,7 @@ FormSubmitObserver.prototype = * information. Can be called repetitively to update the currently * displayed popup position and text. */ - _showPopup(aElement) { + _showPopup: function(aElement) { // Collect positional information and show the popup let panelData = {}; @@ -214,15 +214,15 @@ FormSubmitObserver.prototype = this._mm.sendAsyncMessage("FormValidation:ShowPopup", panelData); }, - _hidePopup() { + _hidePopup: function() { this._mm.sendAsyncMessage("FormValidation:HidePopup", {}); }, - _getWindowUtils() { + _getWindowUtils: function() { return this._content.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); }, - _isRootDocumentEvent(aEvent) { + _isRootDocumentEvent: function(aEvent) { if (this._content == null) { return true; } diff --git a/browser/modules/FormValidationHandler.jsm b/browser/modules/FormValidationHandler.jsm index 0193d644dfe6..62565af58d97 100644 --- a/browser/modules/FormValidationHandler.jsm +++ b/browser/modules/FormValidationHandler.jsm @@ -25,13 +25,13 @@ var FormValidationHandler = * Public apis */ - init() { + init: function() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("FormValidation:ShowPopup", this); mm.addMessageListener("FormValidation:HidePopup", this); }, - uninit() { + uninit: function() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.removeMessageListener("FormValidation:ShowPopup", this); mm.removeMessageListener("FormValidation:HidePopup", this); @@ -39,7 +39,7 @@ var FormValidationHandler = this._anchor = null; }, - hidePopup() { + hidePopup: function() { this._hidePopup(); }, @@ -47,7 +47,7 @@ var FormValidationHandler = * Events */ - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { let window = aMessage.target.ownerGlobal; let json = aMessage.json; let tabBrowser = window.gBrowser; @@ -66,11 +66,11 @@ var FormValidationHandler = } }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { this._hidePopup(); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "FullZoomChange": case "TextZoomChange": @@ -88,7 +88,7 @@ var FormValidationHandler = * Internal */ - _onPopupHiding(aEvent) { + _onPopupHiding: function(aEvent) { aEvent.originalTarget.removeEventListener("popuphiding", this, true); let tabBrowser = aEvent.originalTarget.ownerDocument.getElementById("content"); tabBrowser.selectedBrowser.removeEventListener("scroll", this, true); @@ -115,7 +115,7 @@ var FormValidationHandler = * position - popup positional string constants. * message - the form element validation message text. */ - _showPopup(aWindow, aPanelData) { + _showPopup: function(aWindow, aPanelData) { let previouslyShown = !!this._panel; this._panel = aWindow.document.getElementById("invalid-form-popup"); this._panel.firstChild.textContent = aPanelData.message; @@ -149,7 +149,7 @@ var FormValidationHandler = * Hide the popup if currently displayed. Will fire an event to onPopupHiding * above if visible. */ - _hidePopup() { + _hidePopup: function() { if (this._panel) { this._panel.hidePopup(); } diff --git a/browser/modules/HiddenFrame.jsm b/browser/modules/HiddenFrame.jsm index 207ffe9bf50e..b5582bd97f37 100644 --- a/browser/modules/HiddenFrame.jsm +++ b/browser/modules/HiddenFrame.jsm @@ -39,7 +39,7 @@ HiddenFrame.prototype = { * @returns Promise Returns a promise which is resolved when the hidden frame has finished * loading. */ - get() { + get: function() { if (!this._deferred) { this._deferred = PromiseUtils.defer(); this._create(); @@ -48,7 +48,7 @@ HiddenFrame.prototype = { return this._deferred.promise; }, - destroy() { + destroy: function() { clearTimeout(this._retryTimerId); if (this._frame) { @@ -62,7 +62,7 @@ HiddenFrame.prototype = { } }, - handleEvent() { + handleEvent: function() { let contentWindow = this._frame.contentWindow; if (contentWindow.location.href === XUL_PAGE) { this._frame.removeEventListener("load", this, true); @@ -72,7 +72,7 @@ HiddenFrame.prototype = { } }, - _create() { + _create: function() { if (this.isReady) { let doc = this.hiddenDOMDocument; this._frame = doc.createElementNS(HTML_NS, "iframe"); diff --git a/browser/modules/NetworkPrioritizer.jsm b/browser/modules/NetworkPrioritizer.jsm index 82cdc6dd03be..ef71d320dfb6 100644 --- a/browser/modules/NetworkPrioritizer.jsm +++ b/browser/modules/NetworkPrioritizer.jsm @@ -87,7 +87,7 @@ var BrowserHelper = { windowEntry.lastSelectedBrowser = aBrowser; }, - onRemotenessChange(aBrowser) { + onRemotenessChange: function(aBrowser) { aBrowser.setPriority(_priorityBackup.get(aBrowser.permanentKey)); }, diff --git a/browser/modules/PermissionUI.jsm b/browser/modules/PermissionUI.jsm index e6d95ab437eb..19b4faaabdb8 100644 --- a/browser/modules/PermissionUI.jsm +++ b/browser/modules/PermissionUI.jsm @@ -481,7 +481,7 @@ GeolocationPermissionPrompt.prototype = { gBrowserBundle.GetStringFromName("geolocation.allowLocation.accesskey"), action: null, expireType: null, - callback(state) { + callback: function(state) { if (state && state.checkboxChecked) { secHistogram.add(ALWAYS_SHARE); } else { @@ -496,7 +496,7 @@ GeolocationPermissionPrompt.prototype = { expireType: PrivateBrowsingUtils.isWindowPrivate(this.browser.ownerGlobal) ? Ci.nsIPermissionManager.EXPIRE_SESSION : null, - callback(state) { + callback: function(state) { if (state && state.checkboxChecked) { secHistogram.add(NEVER_SHARE); } diff --git a/browser/modules/PluginContent.jsm b/browser/modules/PluginContent.jsm index c087576e842f..7c1139f6285a 100644 --- a/browser/modules/PluginContent.jsm +++ b/browser/modules/PluginContent.jsm @@ -31,7 +31,7 @@ const FLASH_MIME_TYPE = "application/x-shockwave-flash"; const REPLACEMENT_STYLE_SHEET = Services.io.newURI("chrome://pluginproblem/content/pluginReplaceBinding.css", null, null); PluginContent.prototype = { - init(global) { + init: function(global) { this.global = global; // Need to hold onto the content window or else it'll get destroyed this.content = this.global.content; @@ -62,7 +62,7 @@ PluginContent.prototype = { Services.obs.addObserver(this, "decoder-doctor-notification", false); }, - uninit() { + uninit: function() { let global = this.global; global.removeEventListener("PluginBindingAttached", this, true); @@ -89,7 +89,7 @@ PluginContent.prototype = { delete this.content; }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "BrowserPlugins:ActivatePlugins": this.activatePlugins(msg.data.pluginInfo, msg.data.newState); @@ -143,7 +143,7 @@ PluginContent.prototype = { } }, - onPageShow(event) { + onPageShow: function(event) { // Ignore events that aren't from the main document. if (!this.content || event.target != this.content.document) { return; @@ -157,7 +157,7 @@ PluginContent.prototype = { } }, - onPageHide(event) { + onPageHide: function(event) { // Ignore events that aren't from the main document. if (!this.content || event.target != this.content.document) { return; @@ -168,12 +168,12 @@ PluginContent.prototype = { this.haveShownNotification = false; }, - getPluginUI(plugin, anonid) { + getPluginUI: function(plugin, anonid) { return plugin.ownerDocument. getAnonymousElementByAttribute(plugin, "anonid", anonid); }, - _getPluginInfo(pluginElement) { + _getPluginInfo: function(pluginElement) { if (pluginElement instanceof Ci.nsIDOMHTMLAnchorElement) { // Anchor elements are our place holders, and we only have them for Flash let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); @@ -223,11 +223,11 @@ PluginContent.prototype = { } return { mimetype: tagMimetype, - pluginName, - pluginTag, - permissionString, - fallbackType, - blocklistState, + pluginName: pluginName, + pluginTag: pluginTag, + permissionString: permissionString, + fallbackType: fallbackType, + blocklistState: blocklistState, }; }, @@ -237,7 +237,7 @@ PluginContent.prototype = { * nsIObjectLoadingContent. This only should happen if the plugin is * click-to-play (see bug 1186948). */ - _getPluginInfoForTag(pluginTag, tagMimetype) { + _getPluginInfoForTag: function(pluginTag, tagMimetype) { let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); let pluginName = gNavigatorBundle.GetStringFromName("pluginInfo.unknownPlugin"); @@ -268,22 +268,22 @@ PluginContent.prototype = { } return { mimetype: tagMimetype, - pluginName, - pluginTag, - permissionString, + pluginName: pluginName, + pluginTag: pluginTag, + permissionString: permissionString, // Since we should only have entered _getPluginInfoForTag when // examining a click-to-play plugin, we can safely hard-code // this fallback type, since we don't actually have an // nsIObjectLoadingContent to check. fallbackType: Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY, - blocklistState, + blocklistState: blocklistState, }; }, /** * Update the visibility of the plugin overlay. */ - setVisibility(plugin, overlay, shouldShow) { + setVisibility : function(plugin, overlay, shouldShow) { overlay.classList.toggle("visible", shouldShow); if (shouldShow) { overlay.removeAttribute("dismissed"); @@ -298,7 +298,7 @@ PluginContent.prototype = { * This function will handle showing or hiding the overlay. * @returns true if the plugin is invisible. */ - shouldShowOverlay(plugin, overlay) { + shouldShowOverlay : function(plugin, overlay) { // If the overlay size is 0, we haven't done layout yet. Presume that // plugins are visible until we know otherwise. if (overlay.scrollWidth == 0) { @@ -347,7 +347,7 @@ PluginContent.prototype = { return true; }, - addLinkClickCallback(linkNode, callbackName /* callbackArgs...*/) { + addLinkClickCallback: function(linkNode, callbackName /* callbackArgs...*/) { // XXX just doing (callback)(arg) was giving a same-origin error. bug? let self = this; let callbackArgs = Array.prototype.slice.call(arguments).slice(2); @@ -378,7 +378,7 @@ PluginContent.prototype = { }, // Helper to get the binding handler type from a plugin object - _getBindingType(plugin) { + _getBindingType : function(plugin) { if (!(plugin instanceof Ci.nsIObjectLoadingContent)) return null; @@ -403,7 +403,7 @@ PluginContent.prototype = { } }, - handleEvent(event) { + handleEvent: function(event) { let eventType = event.type; if (eventType == "unload") { @@ -583,7 +583,7 @@ PluginContent.prototype = { } }, - _recordFlashPluginTelemetry(eventType, plugin) { + _recordFlashPluginTelemetry: function(eventType, plugin) { if (!Services.telemetry.canRecordExtended) { return; } @@ -618,7 +618,7 @@ PluginContent.prototype = { } }, - _finishRecordingFlashPluginTelemetry() { + _finishRecordingFlashPluginTelemetry: function() { if (this.flashPluginStats) { Services.telemetry.getHistogramById('FLASH_PLUGIN_INSTANCES_ON_PAGE') .add(this.flashPluginStats.instancesCount); @@ -626,12 +626,12 @@ PluginContent.prototype = { } }, - isKnownPlugin(objLoadingContent) { + isKnownPlugin: function(objLoadingContent) { return (objLoadingContent.getContentTypeForMIMEType(objLoadingContent.actualType) == Ci.nsIObjectLoadingContent.TYPE_PLUGIN); }, - canActivatePlugin(objLoadingContent) { + canActivatePlugin: function(objLoadingContent) { // if this isn't a known plugin, we can't activate it // (this also guards pluginHost.getPermissionStringForType against // unexpected input) @@ -652,7 +652,7 @@ PluginContent.prototype = { isFallbackTypeValid; }, - hideClickToPlayOverlay(plugin) { + hideClickToPlayOverlay: function(plugin) { let overlay = this.getPluginUI(plugin, "main"); if (overlay) { overlay.classList.remove("visible"); @@ -660,7 +660,7 @@ PluginContent.prototype = { }, // Forward a link click callback to the chrome process. - forwardCallback(name, pluginTag) { + forwardCallback: function(name, pluginTag) { this.global.sendAsyncMessage("PluginContent:LinkClickCallback", { name, pluginTag }); }, @@ -692,12 +692,12 @@ PluginContent.prototype = { { runID, keyVals, submitURLOptIn }); }, - reloadPage() { + reloadPage: function() { this.global.content.location.reload(); }, // Event listener for click-to-play plugins. - _handleClickToPlayEvent(plugin) { + _handleClickToPlayEvent: function(plugin) { let doc = plugin.ownerDocument; let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); let permissionString; @@ -730,7 +730,7 @@ PluginContent.prototype = { } }, - onOverlayClick(event) { + onOverlayClick: function(event) { let document = event.target.ownerDocument; let plugin = document.getBindingParent(event.target); let contentWindow = plugin.ownerGlobal.top; @@ -747,7 +747,7 @@ PluginContent.prototype = { } }, - reshowClickToPlayNotification() { + reshowClickToPlayNotification: function() { let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -766,7 +766,7 @@ PluginContent.prototype = { /** * Activate the plugins that the user has specified. */ - activatePlugins(pluginInfo, newState) { + activatePlugins: function(pluginInfo, newState) { let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -812,7 +812,7 @@ PluginContent.prototype = { this.updateNotificationUI(); }, - _showClickToPlayNotification(plugin, showNow) { + _showClickToPlayNotification: function(plugin, showNow) { let plugins = []; // If plugin is null, that means the user has navigated back to a page with @@ -872,8 +872,8 @@ PluginContent.prototype = { this.global.sendAsyncMessage("PluginContent:ShowClickToPlayNotification", { plugins: [...this.pluginData.values()], - showNow, - location, + showNow: showNow, + location: location, }, null, principal); }, @@ -888,7 +888,7 @@ PluginContent.prototype = { * document). If this parameter is omitted, it defaults * to the current top-level document. */ - updateNotificationUI(document) { + updateNotificationUI: function(document) { document = document || this.content.document; // We're only interested in the top-level document, since that's @@ -953,23 +953,23 @@ PluginContent.prototype = { // If there are any items remaining in `actions` now, they are hidden // plugins that need a notification bar. this.global.sendAsyncMessage("PluginContent:UpdateHiddenPluginUI", { - haveInsecure, + haveInsecure: haveInsecure, actions: [...actions.values()], - location, + location: location, }, null, principal); }, - removeNotification(name) { - this.global.sendAsyncMessage("PluginContent:RemoveNotification", { name }); + removeNotification: function(name) { + this.global.sendAsyncMessage("PluginContent:RemoveNotification", { name: name }); }, - clearPluginCaches() { + clearPluginCaches: function() { this.pluginData.clear(); this.pluginCrashData.clear(); }, - hideNotificationBar(name) { - this.global.sendAsyncMessage("PluginContent:HideNotificationBar", { name }); + hideNotificationBar: function(name) { + this.global.sendAsyncMessage("PluginContent:HideNotificationBar", { name: name }); }, /** @@ -983,7 +983,7 @@ PluginContent.prototype = { * @returns bool * True if the plugin is a descendant of the full screen DOM element, false otherwise. **/ - isWithinFullScreenElement(fullScreenElement, domElement) { + isWithinFullScreenElement: function(fullScreenElement, domElement) { /** * Traverses down iframes until it find a non-iframe full screen DOM element. @@ -1018,7 +1018,7 @@ PluginContent.prototype = { * fired for both NPAPI and Gecko Media plugins. In the latter case, the * target of the event is the document that the GMP is being used in. */ - onPluginCrashed(target, aEvent) { + onPluginCrashed: function(target, aEvent) { if (!(aEvent instanceof this.content.PluginCrashedEvent)) return; @@ -1057,7 +1057,7 @@ PluginContent.prototype = { }); }, - NPAPIPluginProcessCrashed({pluginName, runID, state}) { + NPAPIPluginProcessCrashed: function({pluginName, runID, state}) { let message = gNavigatorBundle.formatStringFromName("crashedpluginsMessage.title", [pluginName], 1); @@ -1086,8 +1086,8 @@ PluginContent.prototype = { // WeakSet. Once the WeakSet is empty, we can clear the map. if (!this.pluginCrashData.has(runID)) { this.pluginCrashData.set(runID, { - state, - message, + state: state, + message: message, instances: new WeakSet(), }); } @@ -1098,7 +1098,7 @@ PluginContent.prototype = { } }, - setCrashedNPAPIPluginState({plugin, state, message}) { + setCrashedNPAPIPluginState: function({plugin, state, message}) { // Force a layout flush so the binding is attached. plugin.clientTop; let overlay = this.getPluginUI(plugin, "main"); @@ -1165,7 +1165,7 @@ PluginContent.prototype = { } }, - NPAPIPluginCrashReportSubmitted({ runID, state }) { + NPAPIPluginCrashReportSubmitted: function({ runID, state }) { this.pluginCrashData.delete(runID); let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -1181,7 +1181,7 @@ PluginContent.prototype = { } }, - GMPCrashed(aEvent) { + GMPCrashed: function(aEvent) { let target = aEvent.target; let pluginName = aEvent.pluginName; let gmpPlugin = aEvent.gmpPlugin; diff --git a/browser/modules/ProcessHangMonitor.jsm b/browser/modules/ProcessHangMonitor.jsm index 8f439f4335c6..7c7c86b2c129 100644 --- a/browser/modules/ProcessHangMonitor.jsm +++ b/browser/modules/ProcessHangMonitor.jsm @@ -49,7 +49,7 @@ var ProcessHangMonitor = { /** * Initialize hang reporting. Called once in the parent process. */ - init() { + init: function() { Services.obs.addObserver(this, "process-hang-report", false); Services.obs.addObserver(this, "clear-hang-report", false); Services.obs.addObserver(this, "xpcom-shutdown", false); @@ -60,7 +60,7 @@ var ProcessHangMonitor = { * Terminate JavaScript associated with the hang being reported for * the selected browser in |win|. */ - terminateScript(win) { + terminateScript: function(win) { this.handleUserInput(win, report => report.terminateScript()); }, @@ -68,7 +68,7 @@ var ProcessHangMonitor = { * Start devtools debugger for JavaScript associated with the hang * being reported for the selected browser in |win|. */ - debugScript(win) { + debugScript: function(win) { this.handleUserInput(win, report => { function callback() { report.endStartingDebugger(); @@ -87,7 +87,7 @@ var ProcessHangMonitor = { * for the selected browser in |win|. Will attempt to generate a combined * crash report for all processes. */ - terminatePlugin(win) { + terminatePlugin: function(win) { this.handleUserInput(win, report => report.terminatePlugin()); }, @@ -95,7 +95,7 @@ var ProcessHangMonitor = { * Dismiss the browser notification and invoke an appropriate action based on * the hang type. */ - stopIt(win) { + stopIt: function(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return; @@ -115,7 +115,7 @@ var ProcessHangMonitor = { * Dismiss the notification, clear the report from the active list and set up * a new timer to track a wait period during which we won't notify. */ - waitLonger(win) { + waitLonger: function(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return; @@ -155,7 +155,7 @@ var ProcessHangMonitor = { * |win|, invoke |func| on that report and stop notifying the user * about it. */ - handleUserInput(win, func) { + handleUserInput: function(win, func) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return null; @@ -165,7 +165,7 @@ var ProcessHangMonitor = { return func(report); }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case "xpcom-shutdown": Services.obs.removeObserver(this, "xpcom-shutdown"); @@ -198,7 +198,7 @@ var ProcessHangMonitor = { /** * Find a active hang report for the given element. */ - findActiveReport(browser) { + findActiveReport: function(browser) { let frameLoader = browser.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader; for (let report of this._activeReports) { if (report.isReportForBrowser(frameLoader)) { @@ -211,7 +211,7 @@ var ProcessHangMonitor = { /** * Find a paused hang report for the given element. */ - findPausedReport(browser) { + findPausedReport: function(browser) { let frameLoader = browser.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader; for (let [report, ] of this._pausedReports) { if (report.isReportForBrowser(frameLoader)) { @@ -225,7 +225,7 @@ var ProcessHangMonitor = { * Remove an active hang report from the active list and cancel the timer * associated with it. */ - removeActiveReport(report) { + removeActiveReport: function(report) { this._activeReports.delete(report); this.updateWindows(); }, @@ -234,7 +234,7 @@ var ProcessHangMonitor = { * Remove a paused hang report from the paused list and cancel the timer * associated with it. */ - removePausedReport(report) { + removePausedReport: function(report) { let timer = this._pausedReports.get(report); if (timer) { timer.cancel(); @@ -248,7 +248,7 @@ var ProcessHangMonitor = { * each window to watch for events that would cause a different hang * report to be displayed. */ - updateWindows() { + updateWindows: function() { let e = Services.wm.getEnumerator("navigator:browser"); while (e.hasMoreElements()) { let win = e.getNext(); @@ -267,7 +267,7 @@ var ProcessHangMonitor = { /** * If there is a hang report for the current tab in |win|, display it. */ - updateWindow(win) { + updateWindow: function(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (report) { @@ -280,7 +280,7 @@ var ProcessHangMonitor = { /** * Show the notification for a hang. */ - showNotification(win, report) { + showNotification: function(win, report) { let nb = win.document.getElementById("high-priority-global-notificationbox"); let notification = nb.getNotificationWithValue("process-hang"); if (notification) { @@ -292,14 +292,14 @@ var ProcessHangMonitor = { let buttons = [{ label: bundle.getString("processHang.button_stop.label"), accessKey: bundle.getString("processHang.button_stop.accessKey"), - callback() { + callback: function() { ProcessHangMonitor.stopIt(win); } }, { label: bundle.getString("processHang.button_wait.label"), accessKey: bundle.getString("processHang.button_wait.accessKey"), - callback() { + callback: function() { ProcessHangMonitor.waitLonger(win); } }]; @@ -308,7 +308,7 @@ var ProcessHangMonitor = { buttons.push({ label: bundle.getString("processHang.button_debug.label"), accessKey: bundle.getString("processHang.button_debug.accessKey"), - callback() { + callback: function() { ProcessHangMonitor.debugScript(win); } }); @@ -323,7 +323,7 @@ var ProcessHangMonitor = { /** * Ensure that no hang notifications are visible in |win|. */ - hideNotification(win) { + hideNotification: function(win) { let nb = win.document.getElementById("high-priority-global-notificationbox"); let notification = nb.getNotificationWithValue("process-hang"); if (notification) { @@ -335,17 +335,17 @@ var ProcessHangMonitor = { * Install event handlers on |win| to watch for events that would * cause a different hang report to be displayed. */ - trackWindow(win) { + trackWindow: function(win) { win.gBrowser.tabContainer.addEventListener("TabSelect", this, true); win.gBrowser.tabContainer.addEventListener("TabRemotenessChange", this, true); }, - untrackWindow(win) { + untrackWindow: function(win) { win.gBrowser.tabContainer.removeEventListener("TabSelect", this, true); win.gBrowser.tabContainer.removeEventListener("TabRemotenessChange", this, true); }, - handleEvent(event) { + handleEvent: function(event) { let win = event.target.ownerGlobal; // If a new tab is selected or if a tab changes remoteness, then @@ -360,7 +360,7 @@ var ProcessHangMonitor = { * Handle a potentially new hang report. If it hasn't been seen * before, show a notification for it in all open XUL windows. */ - reportHang(report) { + reportHang: function(report) { // If this hang was already reported reset the timer for it. if (this._activeReports.has(report)) { // if this report is in active but doesn't have a notification associated @@ -389,7 +389,7 @@ var ProcessHangMonitor = { this.updateWindows(); }, - clearHang(report) { + clearHang: function(report) { this.removeActiveReport(report); this.removePausedReport(report); report.userCanceled(); diff --git a/browser/modules/ReaderParent.jsm b/browser/modules/ReaderParent.jsm index 8b59ac5d15a9..6fcaada42685 100644 --- a/browser/modules/ReaderParent.jsm +++ b/browser/modules/ReaderParent.jsm @@ -28,20 +28,20 @@ var ReaderParent = { "Reader:UpdateReaderButton", ], - init() { + init: function() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); for (let msg of this.MESSAGES) { mm.addMessageListener(msg, this); } }, - receiveMessage(message) { + receiveMessage: function(message) { switch (message.name) { case "Reader:ArticleGet": this._getArticle(message.data.url, message.target).then((article) => { // Make sure the target browser is still alive before trying to send data back. if (message.target.messageManager) { - message.target.messageManager.sendAsyncMessage("Reader:ArticleData", { article }); + message.target.messageManager.sendAsyncMessage("Reader:ArticleData", { article: article }); } }, e => { if (e && e.newURL) { @@ -80,7 +80,7 @@ var ReaderParent = { } }, - updateReaderButton(browser) { + updateReaderButton: function(browser) { let win = browser.ownerGlobal; if (browser != win.gBrowser.selectedBrowser) { return; @@ -124,7 +124,7 @@ var ReaderParent = { } }, - forceShowReaderIcon(browser) { + forceShowReaderIcon: function(browser) { browser.isArticle = true; this.updateReaderButton(browser); }, @@ -136,7 +136,7 @@ var ReaderParent = { this.toggleReaderMode(event); }, - toggleReaderMode(event) { + toggleReaderMode: function(event) { let win = event.target.ownerGlobal; let browser = win.gBrowser.selectedBrowser; browser.messageManager.sendAsyncMessage("Reader:ToggleReaderMode"); diff --git a/browser/modules/RemotePrompt.jsm b/browser/modules/RemotePrompt.jsm index 9dde55b8f6dd..da4945c2eb8d 100644 --- a/browser/modules/RemotePrompt.jsm +++ b/browser/modules/RemotePrompt.jsm @@ -17,12 +17,12 @@ Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/SharedPromptUtils.jsm"); var RemotePrompt = { - init() { + init: function() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Prompt:Open", this); }, - receiveMessage(message) { + receiveMessage: function(message) { switch (message.name) { case "Prompt:Open": if (message.data.uri) { @@ -34,7 +34,7 @@ var RemotePrompt = { } }, - openTabPrompt(args, browser) { + openTabPrompt: function(args, browser) { let window = browser.ownerGlobal; let tabPrompt = window.gBrowser.getTabModalPromptBox(browser) let newPrompt; @@ -92,7 +92,7 @@ var RemotePrompt = { } }, - openModalWindow(args, browser) { + openModalWindow: function(args, browser) { let window = browser.ownerGlobal; try { PromptUtils.fireDialogEvent(window, "DOMWillOpenModalDialog", browser); diff --git a/browser/modules/SelfSupportBackend.jsm b/browser/modules/SelfSupportBackend.jsm index d8fbb71dca54..d25b4a74fbd6 100644 --- a/browser/modules/SelfSupportBackend.jsm +++ b/browser/modules/SelfSupportBackend.jsm @@ -53,11 +53,11 @@ const IS_UNIFIED_TELEMETRY = Preferences.get(PREF_TELEMETRY_UNIFIED, false); var gLogAppenderDump = null; this.SelfSupportBackend = Object.freeze({ - init() { + init: function() { SelfSupportBackendInternal.init(); }, - uninit() { + uninit: function() { SelfSupportBackendInternal.uninit(); }, }); @@ -75,7 +75,7 @@ var SelfSupportBackendInternal = { /** * Initializes the self support backend. */ - init() { + init: function() { this._configureLogging(); this._log.trace("init"); @@ -108,7 +108,7 @@ var SelfSupportBackendInternal = { /** * Shut down the self support backend, if active. */ - uninit() { + uninit: function() { this._log.trace("uninit"); Preferences.ignore(PREF_BRANCH_LOG, this._configureLogging, this); @@ -142,7 +142,7 @@ var SelfSupportBackendInternal = { * Handle notifications. Once all windows are created, we wait a little bit more * since tabs might still be loading. Then, we open the self support. */ - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { this._log.trace("observe - Topic " + aTopic); if (aTopic === "sessionstore-windows-restored") { @@ -154,7 +154,7 @@ var SelfSupportBackendInternal = { /** * Configure the logger based on the preferences. */ - _configureLogging() { + _configureLogging: function() { if (!this._log) { this._log = Log.repository.getLogger(LOGGER_NAME); @@ -183,7 +183,7 @@ var SelfSupportBackendInternal = { * Create an hidden frame to host our |browser|, then load the SelfSupport page in it. * @param aURL The URL to load in the browser. */ - _makeHiddenBrowser(aURL) { + _makeHiddenBrowser: function(aURL) { this._frame = new HiddenFrame(); return this._frame.get().then(aFrame => { let doc = aFrame.document; @@ -197,7 +197,7 @@ var SelfSupportBackendInternal = { }); }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { this._log.trace("handleEvent - aEvent.type " + aEvent.type + ", Trusted " + aEvent.isTrusted); if (aEvent.type === "DOMWindowClose") { @@ -217,7 +217,7 @@ var SelfSupportBackendInternal = { /** * Called when the self support page correctly loads. */ - _pageSuccessCallback() { + _pageSuccessCallback: function() { this._log.debug("_pageSuccessCallback - Page correctly loaded."); this._browser.removeProgressListener(this._progressListener); this._progressListener.destroy(); @@ -230,7 +230,7 @@ var SelfSupportBackendInternal = { /** * Called when the self support page fails to load. */ - _pageLoadErrorCallback() { + _pageLoadErrorCallback: function() { this._log.info("_pageLoadErrorCallback - Too many failed load attempts. Giving up."); this.uninit(); }, @@ -240,7 +240,7 @@ var SelfSupportBackendInternal = { * self support page and attempt to load the page content. If loading fails, try again * after an interval. */ - _loadSelfSupport() { + _loadSelfSupport: function() { // Fetch the Self Support URL from the preferences. let unformattedURL = Preferences.get(PREF_URL, null); let url = Services.urlFormatter.formatURL(unformattedURL); @@ -290,7 +290,7 @@ function ProgressListener(aLoadErrorCallback, aLoadSuccessCallback) { } ProgressListener.prototype = { - onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { if (aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) { this._log.warn("onLocationChange - There was a problem fetching the SelfSupport URL (attempt " + this._loadAttempts + ")."); @@ -312,7 +312,7 @@ ProgressListener.prototype = { } }, - onStateChange(aWebProgress, aRequest, aFlags, aStatus) { + onStateChange: function(aWebProgress, aRequest, aFlags, aStatus) { if (aFlags & Ci.nsIWebProgressListener.STATE_STOP && aFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK && aFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW && @@ -321,7 +321,7 @@ ProgressListener.prototype = { } }, - destroy() { + destroy: function() { // Make sure we don't try to reload self support when shutting down. clearTimeout(this._reloadTimerId); }, diff --git a/browser/modules/SitePermissions.jsm b/browser/modules/SitePermissions.jsm index c384a22cfa63..38fd1ab93b61 100644 --- a/browser/modules/SitePermissions.jsm +++ b/browser/modules/SitePermissions.jsm @@ -27,7 +27,7 @@ this.SitePermissions = { * * install addon permission is excluded, check bug 1303108 */ - getAllByURI(aURI) { + getAllByURI: function(aURI) { let result = []; if (!this.isSupportedURI(aURI)) { return result; @@ -64,7 +64,7 @@ this.SitePermissions = { * - id: the state constant * - label: the translated label of that state */ - getPermissionItem(aId, aState) { + getPermissionItem: function(aId, aState) { let availableStates = this.getAvailableStates(aId).map(state => { return { id: state, label: this.getStateLabel(aId, state) }; }); @@ -77,7 +77,7 @@ this.SitePermissions = { /* Returns a list of objects representing all permissions that are currently * set for the given URI. See getPermissionItem for the content of each object. */ - getPermissionDetailsByURI(aURI) { + getPermissionDetailsByURI: function(aURI) { let permissions = []; for (let {state, id} of this.getAllByURI(aURI)) { permissions.push(this.getPermissionItem(id, state)); @@ -90,20 +90,20 @@ this.SitePermissions = { * URI. This excludes file URIs, for instance, as they don't have a host, * even though nsIPermissionManager can still handle them. */ - isSupportedURI(aURI) { + isSupportedURI: function(aURI) { return aURI.schemeIs("http") || aURI.schemeIs("https"); }, /* Returns an array of all permission IDs. */ - listPermissions() { + listPermissions: function() { return Object.keys(gPermissionObject); }, /* Returns an array of permission states to be exposed to the user for a * permission with the given ID. */ - getAvailableStates(aPermissionID) { + getAvailableStates: function(aPermissionID) { if (aPermissionID in gPermissionObject && gPermissionObject[aPermissionID].states) return gPermissionObject[aPermissionID].states; @@ -116,7 +116,7 @@ this.SitePermissions = { /* Returns the default state of a particular permission. */ - getDefault(aPermissionID) { + getDefault: function(aPermissionID) { if (aPermissionID in gPermissionObject && gPermissionObject[aPermissionID].getDefault) return gPermissionObject[aPermissionID].getDefault(); @@ -126,7 +126,7 @@ this.SitePermissions = { /* Returns the state of a particular permission for a given URI. */ - get(aURI, aPermissionID) { + get: function(aURI, aPermissionID) { if (!this.isSupportedURI(aURI)) return this.UNKNOWN; @@ -141,7 +141,7 @@ this.SitePermissions = { /* Sets the state of a particular permission for a given URI. */ - set(aURI, aPermissionID, aState) { + set: function(aURI, aPermissionID, aState) { if (!this.isSupportedURI(aURI)) return; @@ -155,7 +155,7 @@ this.SitePermissions = { /* Removes the saved state of a particular permission for a given URI. */ - remove(aURI, aPermissionID) { + remove: function(aURI, aPermissionID) { if (!this.isSupportedURI(aURI)) return; @@ -165,7 +165,7 @@ this.SitePermissions = { /* Returns the localized label for the permission with the given ID, to be * used in a UI for managing permissions. */ - getPermissionLabel(aPermissionID) { + getPermissionLabel: function(aPermissionID) { let labelID = gPermissionObject[aPermissionID].labelID || aPermissionID; return gStringBundle.GetStringFromName("permission." + labelID + ".label"); }, @@ -173,7 +173,7 @@ this.SitePermissions = { /* Returns the localized label for the given permission state, to be used in * a UI for managing permissions. */ - getStateLabel(aPermissionID, aState, aInUse = false) { + getStateLabel: function(aPermissionID, aState, aInUse = false) { switch (aState) { case this.UNKNOWN: if (aInUse) @@ -215,7 +215,7 @@ var gPermissionObject = { */ "image": { - getDefault() { + getDefault: function() { return Services.prefs.getIntPref("permissions.default.image") == 2 ? SitePermissions.BLOCK : SitePermissions.ALLOW; } @@ -223,7 +223,7 @@ var gPermissionObject = { "cookie": { states: [ SitePermissions.ALLOW, SitePermissions.SESSION, SitePermissions.BLOCK ], - getDefault() { + getDefault: function() { if (Services.prefs.getIntPref("network.cookie.cookieBehavior") == 2) return SitePermissions.BLOCK; @@ -246,14 +246,14 @@ var gPermissionObject = { }, "popup": { - getDefault() { + getDefault: function() { return Services.prefs.getBoolPref("dom.disable_open_during_load") ? SitePermissions.BLOCK : SitePermissions.ALLOW; } }, "install": { - getDefault() { + getDefault: function() { return Services.prefs.getBoolPref("xpinstall.whitelist.required") ? SitePermissions.BLOCK : SitePermissions.ALLOW; } diff --git a/browser/modules/Social.jsm b/browser/modules/Social.jsm index 510c2d4acf4d..25e9a6f41614 100644 --- a/browser/modules/Social.jsm +++ b/browser/modules/Social.jsm @@ -92,14 +92,14 @@ this.Social = { return deferred.promise; }, - _updateEnabledState(enable) { + _updateEnabledState: function(enable) { for (let p of Social.providers) { p.enabled = enable; } }, // Called to update our cache of providers and set the current provider - _updateProviderCache(providers) { + _updateProviderCache: function(providers) { this.providers = providers; Services.obs.notifyObservers(null, "social:providers-changed", null); }, @@ -108,7 +108,7 @@ this.Social = { return !this._disabledForSafeMode && this.providers.length > 0; }, - _getProviderFromOrigin(origin) { + _getProviderFromOrigin: function(origin) { for (let p of this.providers) { if (p.origin == origin) { return p; @@ -117,20 +117,20 @@ this.Social = { return null; }, - getManifestByOrigin(origin) { + getManifestByOrigin: function(origin) { return SocialService.getManifestByOrigin(origin); }, - installProvider(data, installCallback, options = {}) { + installProvider: function(data, installCallback, options = {}) { SocialService.installProvider(data, installCallback, options); }, - uninstallProvider(origin, aCallback) { + uninstallProvider: function(origin, aCallback) { SocialService.uninstallProvider(origin, aCallback); }, // Activation functionality - activateFromOrigin(origin, callback) { + activateFromOrigin: function(origin, callback) { // It's OK if the provider has already been activated - we still get called // back with it. SocialService.enableProvider(origin, callback); @@ -225,7 +225,7 @@ DynamicResizeWatcher.prototype = { this.OpenGraphBuilder = { - generateEndpointURL(URLTemplate, pageData) { + generateEndpointURL: function(URLTemplate, pageData) { // support for existing oexchange style endpoints by supporting their // querystring arguments. parse the query string template and do // replacements where necessary the query names may be different than ours, diff --git a/browser/modules/SocialService.jsm b/browser/modules/SocialService.jsm index c1dfce37fc20..2cc4255d1f00 100644 --- a/browser/modules/SocialService.jsm +++ b/browser/modules/SocialService.jsm @@ -58,7 +58,7 @@ var SocialServiceInternal = { get manifests() { return this.manifestsGenerator(); }, - getManifestPrefname(origin) { + getManifestPrefname: function(origin) { // Retrieve the prefname for a given origin/manifest. // If no existing pref, return a generated prefname. let MANIFEST_PREFS = Services.prefs.getBranch("social.manifest."); @@ -77,7 +77,7 @@ var SocialServiceInternal = { let originUri = Services.io.newURI(origin, null, null); return originUri.hostPort.replace('.', '-'); }, - orderedProviders(aCallback) { + orderedProviders: function(aCallback) { if (SocialServiceInternal.providerArray.length < 2) { schedule(function() { aCallback(SocialServiceInternal.providerArray); @@ -106,7 +106,7 @@ var SocialServiceInternal = { try { stmt.executeAsync({ - handleResult(aResultSet) { + handleResult: function(aResultSet) { let row; while ((row = aResultSet.getNextRow())) { let rh = row.getResultByName("host"); @@ -114,10 +114,10 @@ var SocialServiceInternal = { providers[rh].frecency = parseInt(frecency) || 0; } }, - handleError(aError) { + handleError: function(aError) { Cu.reportError(aError.message + " (Result = " + aError.result + ")"); }, - handleCompletion(aReason) { + handleCompletion: function(aReason) { // the query may not have returned all our providers, so we have // stamped the frecency on the provider and sort here. This makes sure // all enabled providers get sorted even with frecency zero. @@ -177,21 +177,21 @@ var ActiveProviders = { return this._providers; }, - has(origin) { + has: function(origin) { return (origin in this._providers); }, - add(origin) { + add: function(origin) { this._providers[origin] = 1; this._deferredTask.arm(); }, - delete(origin) { + delete: function(origin) { delete this._providers[origin]; this._deferredTask.arm(); }, - flush() { + flush: function() { this._deferredTask.disarm(); this._persist(); }, @@ -201,7 +201,7 @@ var ActiveProviders = { return this._deferredTask = new DeferredTask(this._persist.bind(this), 0); }, - _persist() { + _persist: function() { let string = Cc["@mozilla.org/supports-string;1"]. createInstance(Ci.nsISupportsString); string.data = JSON.stringify(this._providers); @@ -454,13 +454,13 @@ this.SocialService = { }, // Returns an unordered array of installed providers - getProviderList(onDone) { + getProviderList: function(onDone) { schedule(function() { onDone(SocialServiceInternal.providerArray); }); }, - getManifestByOrigin(origin) { + getManifestByOrigin: function(origin) { for (let manifest of SocialServiceInternal.manifests) { if (origin == manifest.origin) { return manifest; @@ -470,11 +470,11 @@ this.SocialService = { }, // Returns an array of installed providers, sorted by frecency - getOrderedProviderList(onDone) { + getOrderedProviderList: function(onDone) { SocialServiceInternal.orderedProviders(onDone); }, - getOriginActivationType(origin) { + getOriginActivationType: function(origin) { return getOriginActivationType(origin); }, @@ -486,7 +486,7 @@ this.SocialService = { this._providerListeners.delete(listener); }, - _notifyProviderListeners(topic, origin, providers) { + _notifyProviderListeners: function(topic, origin, providers) { for (let [listener, ] of this._providerListeners) { try { listener(topic, origin, providers); @@ -496,7 +496,7 @@ this.SocialService = { } }, - _manifestFromData(type, data, installOrigin) { + _manifestFromData: function(type, data, installOrigin) { let featureURLs = ['shareURL']; let resolveURLs = featureURLs.concat(['postActivationURL']); @@ -541,7 +541,7 @@ this.SocialService = { return data; }, - _showInstallNotification(data, aAddonInstaller) { + _showInstallNotification: function(data, aAddonInstaller) { let brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties"); let browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties"); @@ -560,7 +560,7 @@ this.SocialService = { let action = { label: browserBundle.GetStringFromName("service.install.ok.label"), accessKey: browserBundle.GetStringFromName("service.install.ok.accesskey"), - callback() { + callback: function() { aAddonInstaller.install(); }, }; @@ -576,7 +576,7 @@ this.SocialService = { action, [], options); }, - installProvider(data, installCallback, options = {}) { + installProvider: function(data, installCallback, options = {}) { data.installType = getOriginActivationType(data.origin); // if we get data, we MUST have a valid manifest generated from the data let manifest = this._manifestFromData(data.installType, data.manifest, data.origin); @@ -611,7 +611,7 @@ this.SocialService = { }.bind(this)); }, - _installProvider(data, options, installCallback) { + _installProvider: function(data, options, installCallback) { if (!data.manifest) throw new Error("Cannot install provider without manifest data"); @@ -633,7 +633,7 @@ this.SocialService = { this._showInstallNotification(data, installer); }, - createWrapper(manifest) { + createWrapper: function(manifest) { return new AddonWrapper(manifest); }, @@ -642,7 +642,7 @@ this.SocialService = { * have knowledge of the currently selected provider here, we will notify * the front end to deal with any reload. */ - updateProvider(aUpdateOrigin, aManifest) { + updateProvider: function(aUpdateOrigin, aManifest) { let installType = this.getOriginActivationType(aUpdateOrigin); // if we get data, we MUST have a valid manifest generated from the data let manifest = this._manifestFromData(installType, aManifest, aUpdateOrigin); @@ -670,7 +670,7 @@ this.SocialService = { }, - uninstallProvider(origin, aCallback) { + uninstallProvider: function(origin, aCallback) { let manifest = SocialService.getManifestByOrigin(origin); let addon = new AddonWrapper(manifest); addon.uninstall(aCallback); @@ -716,7 +716,7 @@ function SocialProvider(input) { } SocialProvider.prototype = { - reload() { + reload: function() { // calling terminate/activate does not set the enabled state whereas setting // enabled will call terminate/activate this.enabled = false; @@ -747,7 +747,7 @@ SocialProvider.prototype = { return SocialService.getManifestByOrigin(this.origin); }, - getPageSize(name) { + getPageSize: function(name) { let manifest = this.manifest; if (manifest && manifest.pageSize) return manifest.pageSize[name]; @@ -854,11 +854,11 @@ function AddonInstaller(sourceURI, aManifest, installCallback) { } var SocialAddonProvider = { - startup() {}, + startup: function() {}, - shutdown() {}, + shutdown: function() {}, - updateAddonAppDisabledStates() { + updateAddonAppDisabledStates: function() { // we wont bother with "enabling" services that are released from blocklist for (let manifest of SocialServiceInternal.manifests) { try { @@ -874,7 +874,7 @@ var SocialAddonProvider = { } }, - getAddonByID(aId, aCallback) { + getAddonByID: function(aId, aCallback) { for (let manifest of SocialServiceInternal.manifests) { if (aId == getAddonIDFromOrigin(manifest.origin)) { aCallback(new AddonWrapper(manifest)); @@ -884,7 +884,7 @@ var SocialAddonProvider = { aCallback(null); }, - getAddonsByTypes(aTypes, aCallback) { + getAddonsByTypes: function(aTypes, aCallback) { if (aTypes && aTypes.indexOf(ADDON_TYPE_SERVICE) == -1) { aCallback([]); return; @@ -892,7 +892,7 @@ var SocialAddonProvider = { aCallback([...SocialServiceInternal.manifests].map(a => new AddonWrapper(a))); }, - removeAddon(aAddon, aCallback) { + removeAddon: function(aAddon, aCallback) { AddonManagerPrivate.callAddonListeners("onUninstalling", aAddon, false); aAddon.pendingOperations |= AddonManager.PENDING_UNINSTALL; Services.prefs.clearUserPref(getPrefnameFromOrigin(aAddon.manifest.origin)); @@ -943,7 +943,7 @@ AddonWrapper.prototype = { return false; }, - isCompatibleWith(appVersion, platformVersion) { + isCompatibleWith: function(appVersion, platformVersion) { return true; }, @@ -993,7 +993,7 @@ AddonWrapper.prototype = { return permissions; }, - findUpdates(listener, reason, appVersion, platformVersion) { + findUpdates: function(listener, reason, appVersion, platformVersion) { if ("onNoCompatibilityUpdateAvailable" in listener) listener.onNoCompatibilityUpdateAvailable(this); if ("onNoUpdateAvailable" in listener) @@ -1069,7 +1069,7 @@ AddonWrapper.prototype = { return val; }, - uninstall(aCallback) { + uninstall: function(aCallback) { let prefName = getPrefnameFromOrigin(this.manifest.origin); if (Services.prefs.prefHasUserValue(prefName)) { if (ActiveProviders.has(this.manifest.origin)) { @@ -1084,7 +1084,7 @@ AddonWrapper.prototype = { } }, - cancelUninstall() { + cancelUninstall: function() { this._pending -= AddonManager.PENDING_UNINSTALL; AddonManagerPrivate.callAddonListeners("onOperationCancelled", this); } diff --git a/browser/modules/TransientPrefs.jsm b/browser/modules/TransientPrefs.jsm index a12c3c2c94d6..aa2bd20c9ab2 100644 --- a/browser/modules/TransientPrefs.jsm +++ b/browser/modules/TransientPrefs.jsm @@ -15,7 +15,7 @@ var prefVisibility = new Map; application. */ this.TransientPrefs = { - prefShouldBeVisible(prefName) { + prefShouldBeVisible: function(prefName) { if (Preferences.isSet(prefName)) prefVisibility.set(prefName, true); diff --git a/browser/modules/URLBarZoom.jsm b/browser/modules/URLBarZoom.jsm index c496c339bbbc..3e1c0f70761c 100644 --- a/browser/modules/URLBarZoom.jsm +++ b/browser/modules/URLBarZoom.jsm @@ -11,7 +11,7 @@ Components.utils.import("resource://gre/modules/Services.jsm"); var URLBarZoom = { - init(aWindow) { + init: function(aWindow) { // Register ourselves with the service so we know when the zoom prefs change. Services.obs.addObserver(updateZoomButton, "browser-fullZoom:zoomChange", false); Services.obs.addObserver(updateZoomButton, "browser-fullZoom:zoomReset", false); diff --git a/browser/modules/Windows8WindowFrameColor.jsm b/browser/modules/Windows8WindowFrameColor.jsm index 245ced4aea5e..911333747f6f 100644 --- a/browser/modules/Windows8WindowFrameColor.jsm +++ b/browser/modules/Windows8WindowFrameColor.jsm @@ -14,7 +14,7 @@ var Registry = Cu.import("resource://gre/modules/WindowsRegistry.jsm").WindowsRe var Windows8WindowFrameColor = { _windowFrameColor: null, - get() { + get: function() { if (this._windowFrameColor) return this._windowFrameColor; diff --git a/browser/modules/WindowsJumpLists.jsm b/browser/modules/WindowsJumpLists.jsm index 8f4088cf257f..fff70148690f 100644 --- a/browser/modules/WindowsJumpLists.jsm +++ b/browser/modules/WindowsJumpLists.jsm @@ -426,7 +426,7 @@ this.WinTaskbarJumpList = // Return the pending statement to the caller, to allow cancelation. return PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase) .asyncExecuteLegacyQueries([query], 1, options, { - handleResult(aResultSet) { + handleResult: function(aResultSet) { for (let row; (row = aResultSet.getNextRow());) { try { aCallback.call(aScope, @@ -436,11 +436,11 @@ this.WinTaskbarJumpList = } catch (e) {} } }, - handleError(aError) { + handleError: function(aError) { Components.utils.reportError( "Async execution error (" + aError.result + "): " + aError.message); }, - handleCompletion(aReason) { + handleCompletion: function(aReason) { aCallback.call(WinTaskbarJumpList, null); }, }); diff --git a/browser/modules/WindowsPreviewPerTab.jsm b/browser/modules/WindowsPreviewPerTab.jsm index 04d76feb4fbc..66488310f2eb 100644 --- a/browser/modules/WindowsPreviewPerTab.jsm +++ b/browser/modules/WindowsPreviewPerTab.jsm @@ -72,7 +72,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "PageThumbs", // nsIURI -> imgIContainer function _imageFromURI(uri, privateMode, callback) { let channel = NetUtil.newChannel({ - uri, + uri: uri, loadUsingSystemPrincipal: true, contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE }); @@ -158,7 +158,7 @@ PreviewController.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsITaskbarPreviewController, Ci.nsIDOMEventListener]), - destroy() { + destroy: function() { this.tab.removeEventListener("TabAttrModified", this, false); // Break cycles, otherwise we end up leaking the window with everything @@ -172,7 +172,7 @@ PreviewController.prototype = { }, // Resizes the canvasPreview to 0x0, essentially freeing its memory. - resetCanvasPreview() { + resetCanvasPreview: function() { this.canvasPreview.width = 0; this.canvasPreview.height = 0; }, @@ -180,7 +180,7 @@ PreviewController.prototype = { /** * Set the canvas dimensions. */ - resizeCanvasPreview(aRequestedWidth, aRequestedHeight) { + resizeCanvasPreview: function(aRequestedWidth, aRequestedHeight) { this.canvasPreview.width = aRequestedWidth; this.canvasPreview.height = aRequestedHeight; }, @@ -204,13 +204,13 @@ PreviewController.prototype = { return this.tab.linkedBrowser.getBoundingClientRect(); }, - cacheBrowserDims() { + cacheBrowserDims: function() { let dims = this.browserDims; this._cachedWidth = dims.width; this._cachedHeight = dims.height; }, - testCacheBrowserDims() { + testCacheBrowserDims: function() { let dims = this.browserDims; return this._cachedWidth == dims.width && this._cachedHeight == dims.height; @@ -220,7 +220,7 @@ PreviewController.prototype = { * Capture a new thumbnail image for this preview. Called by the controller * in response to a request for a new thumbnail image. */ - updateCanvasPreview(aFullScale, aCallback) { + updateCanvasPreview: function(aFullScale, aCallback) { // Update our cached browser dims so that delayed resize // events don't trigger another invalidation if this tab becomes active. this.cacheBrowserDims(); @@ -231,7 +231,7 @@ PreviewController.prototype = { AeroPeek.resetCacheTimer(); }, - updateTitleAndTooltip() { + updateTitleAndTooltip: function() { let title = this.win.tabbrowser.getWindowTitleForBrowser(this.linkedBrowser); this.preview.title = title; this.preview.tooltip = title; @@ -264,7 +264,7 @@ PreviewController.prototype = { * * @param aTaskbarCallback nsITaskbarPreviewCallback results callback */ - requestPreview(aTaskbarCallback) { + requestPreview: function(aTaskbarCallback) { // Grab a high res content preview this.resetCanvasPreview(); this.updateCanvasPreview(true, (aPreviewCanvas) => { @@ -312,7 +312,7 @@ PreviewController.prototype = { * @param aRequestedWidth width of the requested thumbnail * @param aRequestedHeight height of the requested thumbnail */ - requestThumbnail(aTaskbarCallback, aRequestedWidth, aRequestedHeight) { + requestThumbnail: function(aTaskbarCallback, aRequestedWidth, aRequestedHeight) { this.resizeCanvasPreview(aRequestedWidth, aRequestedHeight); this.updateCanvasPreview(false, (aThumbnailCanvas) => { aTaskbarCallback.done(aThumbnailCanvas, false); @@ -321,11 +321,11 @@ PreviewController.prototype = { // Event handling - onClose() { + onClose: function() { this.win.tabbrowser.removeTab(this.tab); }, - onActivate() { + onActivate: function() { this.win.tabbrowser.selectedTab = this.tab; // Accept activation - this will restore the browser window @@ -334,7 +334,7 @@ PreviewController.prototype = { }, // nsIDOMEventListener - handleEvent(evt) { + handleEvent: function(evt) { switch (evt.type) { case "TabAttrModified": this.updateTitleAndTooltip(); @@ -389,7 +389,7 @@ TabWindow.prototype = { tabEvents: ["TabOpen", "TabClose", "TabSelect", "TabMove"], winEvents: ["resize"], - destroy() { + destroy: function() { this._destroying = true; let tabs = this.tabbrowser.tabs; @@ -417,17 +417,17 @@ TabWindow.prototype = { return this.win.innerHeight; }, - cacheDims() { + cacheDims: function() { this._cachedWidth = this.width; this._cachedHeight = this.height; }, - testCacheDims() { + testCacheDims: function() { return this._cachedWidth == this.width && this._cachedHeight == this.height; }, // Invoked when the given tab is added to this window - newTab(tab) { + newTab: function(tab) { let controller = new PreviewController(this, tab); // It's OK to add the preview now while the favicon still loads. this.previews.set(tab, controller.preview); @@ -437,7 +437,7 @@ TabWindow.prototype = { controller.updateTitleAndTooltip(); }, - createTabPreview(controller) { + createTabPreview: function(controller) { let docShell = this.win .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) @@ -451,7 +451,7 @@ TabWindow.prototype = { }, // Invoked when the given tab is closed - removeTab(tab) { + removeTab: function(tab) { let preview = this.previewFromTab(tab); preview.active = false; preview.visible = false; @@ -478,11 +478,11 @@ TabWindow.prototype = { this.updateTabOrdering(); }, - previewFromTab(tab) { + previewFromTab: function(tab) { return this.previews.get(tab); }, - updateTabOrdering() { + updateTabOrdering: function() { let previews = this.previews; let tabs = this.tabbrowser.tabs; @@ -505,7 +505,7 @@ TabWindow.prototype = { }, // nsIDOMEventListener - handleEvent(evt) { + handleEvent: function(evt) { let tab = evt.originalTarget; switch (evt.type) { case "TabOpen": @@ -531,7 +531,7 @@ TabWindow.prototype = { }, // Set or reset a timer that will invalidate visible thumbnails soon. - setInvalidationTimer() { + setInvalidationTimer: function() { if (!this.invalidateTimer) { this.invalidateTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); } @@ -551,7 +551,7 @@ TabWindow.prototype = { }, 1000, Ci.nsITimer.TYPE_ONE_SHOT); }, - onResize() { + onResize: function() { // Specific to a window. // Call invalidate on each tab thumbnail so that Windows will request an @@ -569,7 +569,7 @@ TabWindow.prototype = { this.setInvalidationTimer(); }, - invalidateTabPreview(aBrowser) { + invalidateTabPreview: function(aBrowser) { for (let [tab, preview] of this.previews) { if (aBrowser == tab.linkedBrowser) { preview.invalidate(); @@ -580,13 +580,13 @@ TabWindow.prototype = { // Browser progress listener - onLocationChange(aBrowser) { + onLocationChange: function(aBrowser) { // I'm not sure we need this, onStateChange does a really good job // of picking up page changes. // this.invalidateTabPreview(aBrowser); }, - onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP && aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) { this.invalidateTabPreview(aBrowser); @@ -596,7 +596,7 @@ TabWindow.prototype = { directRequestProtocols: new Set([ "file", "chrome", "resource", "about" ]), - onLinkIconAvailable(aBrowser, aIconURL) { + onLinkIconAvailable: function(aBrowser, aIconURL) { let requestURL = null; if (aIconURL) { let shouldRequestFaviconURL = true; @@ -662,7 +662,7 @@ this.AeroPeek = { // Length of time in seconds that previews are cached cacheLifespan: 20, - initialize() { + initialize: function() { if (!(WINTASKBAR_CONTRACTID in Cc)) return; this.taskbar = Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar); @@ -752,25 +752,25 @@ this.AeroPeek = { } }, - addPreview(preview) { + addPreview: function(preview) { this.previews.push(preview); this.checkPreviewCount(); }, - removePreview(preview) { + removePreview: function(preview) { let idx = this.previews.indexOf(preview); this.previews.splice(idx, 1); this.checkPreviewCount(); }, - checkPreviewCount() { + checkPreviewCount: function() { if (!this._prefenabled) { return; } this.enabled = this.previews.length <= this.maxpreviews; }, - onOpenWindow(win) { + onOpenWindow: function(win) { // This occurs when the taskbar service is not available (xp, vista) if (!this.available || !this._prefenabled) return; @@ -778,7 +778,7 @@ this.AeroPeek = { win.gTaskbarTabGroup = new TabWindow(win); }, - onCloseWindow(win) { + onCloseWindow: function(win) { // This occurs when the taskbar service is not available (xp, vista) if (!this.available || !this._prefenabled) return; @@ -790,13 +790,13 @@ this.AeroPeek = { this.destroy(); }, - resetCacheTimer() { + resetCacheTimer: function() { this.cacheTimer.cancel(); this.cacheTimer.init(this, 1000 * this.cacheLifespan, Ci.nsITimer.TYPE_ONE_SHOT); }, // nsIObserver - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (aTopic == "nsPref:changed" && aData == TOGGLE_PREF_NAME) { this._prefenabled = this.prefs.getBoolPref(TOGGLE_PREF_NAME); } diff --git a/browser/modules/offlineAppCache.jsm b/browser/modules/offlineAppCache.jsm index cbf561943467..5d0e3481a713 100644 --- a/browser/modules/offlineAppCache.jsm +++ b/browser/modules/offlineAppCache.jsm @@ -10,7 +10,7 @@ const Cc = Components.classes; const Ci = Components.interfaces; this.OfflineAppCacheHelper = { - clear() { + clear: function() { var cacheService = Cc["@mozilla.org/netwerk/cache-storage-service;1"].getService(Ci.nsICacheStorageService); var appCacheStorage = cacheService.appCacheStorage(LoadContextInfo.default, null); try { diff --git a/browser/modules/test/browser_ContentSearch.js b/browser/modules/test/browser_ContentSearch.js index ae2f2b1b8dc8..22665f21bc18 100644 --- a/browser/modules/test/browser_ContentSearch.js +++ b/browser/modules/test/browser_ContentSearch.js @@ -97,7 +97,7 @@ add_task(function* search() { engine.getSubmission(data.searchString, "", data.whence).uri.spec; gMsgMan.sendAsyncMessage(TEST_MSG, { type: "Search", - data, + data: data, expectedURL: submissionURL, }); let msg = yield waitForTestMsg("loadStopped"); @@ -121,7 +121,7 @@ add_task(function* searchInBackgroundTab() { engine.getSubmission(data.searchString, "", data.whence).uri.spec; gMsgMan.sendAsyncMessage(TEST_MSG, { type: "Search", - data, + data: data, expectedURL: submissionURL, }); @@ -315,11 +315,11 @@ function waitForNewEngine(basename, numImages) { let addDeferred = Promise.defer(); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess(engine) { + onSuccess: function(engine) { info("Search engine added: " + basename); addDeferred.resolve(engine); }, - onError(errCode) { + onError: function(errCode) { ok(false, "addEngine failed with error code " + errCode); addDeferred.reject(); }, diff --git a/browser/modules/test/browser_PermissionUI.js b/browser/modules/test/browser_PermissionUI.js index f396217f7974..ddb8832ebfae 100644 --- a/browser/modules/test/browser_PermissionUI.js +++ b/browser/modules/test/browser_PermissionUI.js @@ -223,7 +223,7 @@ add_task(function* test_with_permission_key() { accessKey: "M", action: Ci.nsIPermissionManager.ALLOW_ACTION, expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION, - callback() { + callback: function() { allowed = true; } }; @@ -234,7 +234,7 @@ add_task(function* test_with_permission_key() { accessKey: "D", action: Ci.nsIPermissionManager.DENY_ACTION, expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION, - callback() { + callback: function() { denied = true; } }; @@ -376,7 +376,7 @@ add_task(function* test_no_request() { let mainAction = { label: "Allow", accessKey: "M", - callback() { + callback: function() { allowed = true; } }; @@ -385,7 +385,7 @@ add_task(function* test_no_request() { let secondaryAction = { label: "Deny", accessKey: "D", - callback() { + callback: function() { denied = true; } }; diff --git a/browser/modules/test/browser_ProcessHangNotifications.js b/browser/modules/test/browser_ProcessHangNotifications.js index 87a7c8811a8c..715801b35b66 100644 --- a/browser/modules/test/browser_ProcessHangNotifications.js +++ b/browser/modules/test/browser_ProcessHangNotifications.js @@ -44,7 +44,7 @@ let gTestHangReport = { TEST_CALLBACK_TERMPLUGIN: 3, _hangType: 1, - _tcb(aCallbackType) {}, + _tcb: function(aCallbackType) {}, get hangType() { return this._hangType; @@ -58,26 +58,26 @@ let gTestHangReport = { this._tcb = aValue; }, - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (aIID.equals(Components.interfaces.nsIHangReport) || aIID.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_NOINTERFACE; }, - userCanceled() { + userCanceled: function() { this._tcb(this.TEST_CALLBACK_CANCELED); }, - terminateScript() { + terminateScript: function() { this._tcb(this.TEST_CALLBACK_TERMSCRIPT); }, - terminatePlugin() { + terminatePlugin: function() { this._tcb(this.TEST_CALLBACK_TERMPLUGIN); }, - isReportForBrowser(aFrameLoader) { + isReportForBrowser: function(aFrameLoader) { return true; } }; diff --git a/browser/modules/test/contentSearch.js b/browser/modules/test/contentSearch.js index 8b2b498da7a8..fda68a7a4104 100644 --- a/browser/modules/test/contentSearch.js +++ b/browser/modules/test/contentSearch.js @@ -30,7 +30,7 @@ addMessageListener(TEST_MSG, msg => { waitForLoadAndStopIt(msg.data.expectedURL, url => { sendAsyncMessage(TEST_MSG, { type: "loadStopped", - url, + url: url, }); }); } @@ -41,7 +41,7 @@ function waitForLoadAndStopIt(expectedURL, callback) { let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); let listener = { - onStateChange(webProg, req, flags, status) { + onStateChange: function(webProg, req, flags, status) { if (req instanceof Ci.nsIChannel) { let url = req.originalURI.spec; dump("waitForLoadAndStopIt: onStateChange " + url + "\n"); diff --git a/browser/modules/test/unit/social/head.js b/browser/modules/test/unit/social/head.js index 0a94f536deec..b7f06d33b2d4 100644 --- a/browser/modules/test/unit/social/head.js +++ b/browser/modules/test/unit/social/head.js @@ -132,7 +132,7 @@ function AsyncRunner() { this._callbacks = { done: do_test_finished, - error(err) { + error: function(err) { // xpcshell test functions like do_check_eq throw NS_ERROR_ABORT on // failure. Ignore those so they aren't rethrown here. if (err !== Cr.NS_ERROR_ABORT) { @@ -143,7 +143,7 @@ function AsyncRunner() { do_throw(err); } }, - consoleError(scriptErr) { + consoleError: function(scriptErr) { // Try to ensure the error is related to the test. let filename = scriptErr.sourceName || scriptErr.toString() || ""; if (filename.indexOf("/toolkit/components/social/") >= 0) diff --git a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js index a72dbd492e4d..b74250fc69c4 100644 --- a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js +++ b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js @@ -247,7 +247,7 @@ function setTimeout(fun, timeout) { let timer = Components.classes["@mozilla.org/timer;1"] .createInstance(Components.interfaces.nsITimer); var event = { - notify() { + notify: function() { fun(); } }; @@ -1062,7 +1062,7 @@ add_task(function* test_DirectoryLinksProvider_getEnhancedLink() { do_check_eq(links.length, 0); // There are no directory links. function checkEnhanced(url, image) { - let enhanced = DirectoryLinksProvider.getEnhancedLink({url}); + let enhanced = DirectoryLinksProvider.getEnhancedLink({url: url}); do_check_eq(enhanced && enhanced.enhancedImageURI, image); } @@ -1487,7 +1487,7 @@ add_task(function* test_DirectoryLinksProvider_getFrequencyCapReportSiteAction() targetedSite: "foo.com", url: "bar.com" }, - isPinned() { return false; }, + isPinned: function() { return false; }, }], "view", 0); // read file content and ensure that view counters are updated @@ -1531,9 +1531,9 @@ add_task(function* test_DirectoryLinksProvider_ClickRemoval() { }] }, { - handleError() { do_check_true(false); }, - handleResult() {}, - handleCompletion() { resolve(); } + handleError: function() { do_check_true(false); }, + handleResult: function() {}, + handleCompletion: function() { resolve(); } } ); }); @@ -1827,7 +1827,7 @@ add_task(function* test_blockSuggestedTiles() { // block suggested tile in a regular way DirectoryLinksProvider.reportSitesAction([{ - isPinned() { return false; }, + isPinned: function() { return false; }, link: Object.assign({frecency: 1000}, suggestedLink) }], "block", 0); diff --git a/browser/modules/webrtcUI.jsm b/browser/modules/webrtcUI.jsm index fd40ca0cf1fb..4f818a6194d1 100644 --- a/browser/modules/webrtcUI.jsm +++ b/browser/modules/webrtcUI.jsm @@ -29,7 +29,7 @@ this.webrtcUI = { peerConnectionBlockers: new Set(), emitter: new EventEmitter(), - init() { + init: function() { Services.obs.addObserver(maybeAddMenuIndicator, "browser-delayed-startup-finished", false); let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] @@ -47,7 +47,7 @@ this.webrtcUI = { mm.addMessageListener("webrtc:UpdateBrowserIndicators", this); }, - uninit() { + uninit: function() { Services.obs.removeObserver(maybeAddMenuIndicator, "browser-delayed-startup-finished"); let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] @@ -113,7 +113,7 @@ this.webrtcUI = { _streams: [], // The boolean parameters indicate which streams should be included in the result. - getActiveStreams(aCamera, aMicrophone, aScreen) { + getActiveStreams: function(aCamera, aMicrophone, aScreen) { return webrtcUI._streams.filter(aStream => { let state = aStream.state; return aCamera && state.camera || @@ -127,22 +127,22 @@ this.webrtcUI = { let browserWindow = browser.ownerGlobal; let tab = browserWindow.gBrowser && browserWindow.gBrowser.getTabForBrowser(browser); - return {uri: state.documentURI, tab, browser, types}; + return {uri: state.documentURI, tab: tab, browser: browser, types: types}; }); }, - swapBrowserForNotification(aOldBrowser, aNewBrowser) { + swapBrowserForNotification: function(aOldBrowser, aNewBrowser) { for (let stream of this._streams) { if (stream.browser == aOldBrowser) stream.browser = aNewBrowser; } }, - forgetStreamsFromBrowser(aBrowser) { + forgetStreamsFromBrowser: function(aBrowser) { this._streams = this._streams.filter(stream => stream.browser != aBrowser); }, - showSharingDoorhanger(aActiveStream) { + showSharingDoorhanger: function(aActiveStream) { let browserWindow = aActiveStream.browser.ownerGlobal; if (aActiveStream.tab) { browserWindow.gBrowser.selectedTab = aActiveStream.tab; @@ -165,7 +165,7 @@ this.webrtcUI = { identityBox.click(); }, - updateWarningLabel(aMenuList) { + updateWarningLabel: function(aMenuList) { let type = aMenuList.selectedItem.getAttribute("devicetype"); let document = aMenuList.ownerDocument; document.getElementById("webRTC-all-windows-shared").hidden = type != "Screen"; @@ -195,23 +195,23 @@ this.webrtcUI = { // is canceled. (This would typically be used in // conjunction with a blocking handler to cancel // a user prompt or other work done by the handler) - addPeerConnectionBlocker(aCallback) { + addPeerConnectionBlocker: function(aCallback) { this.peerConnectionBlockers.add(aCallback); }, - removePeerConnectionBlocker(aCallback) { + removePeerConnectionBlocker: function(aCallback) { this.peerConnectionBlockers.delete(aCallback); }, - on(...args) { + on: function(...args) { return this.emitter.on(...args); }, - off(...args) { + off: function(...args) { return this.emitter.off(...args); }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { switch (aMessage.name) { case "rtcpeer:Request": { @@ -348,14 +348,14 @@ function prompt(aBrowser, aRequest) { // The real callback will be set during the "showing" event. The // empty function here is so that PopupNotifications.show doesn't // reject the action. - callback() {} + callback: function() {} }; let secondaryActions = [ { label: stringBundle.getString("getUserMedia.dontAllow.label"), accessKey: stringBundle.getString("getUserMedia.dontAllow.accesskey"), - callback(aState) { + callback: function(aState) { denyRequest(notification.browser, aRequest); if (aState && aState.checkboxChecked) { let perms = Services.perms; @@ -393,7 +393,7 @@ function prompt(aBrowser, aRequest) { [productName]) } : undefined, }, - eventCallback(aTopic, aNewBrowser) { + eventCallback: function(aTopic, aNewBrowser) { if (aTopic == "swapping") return true; @@ -746,11 +746,11 @@ function getGlobalIndicator() { _statusBar: Cc["@mozilla.org/widget/macsystemstatusbar;1"] .getService(Ci.nsISystemStatusBar), - _command(aEvent) { + _command: function(aEvent) { webrtcUI.showSharingDoorhanger(aEvent.target.stream); }, - _popupShowing(aEvent) { + _popupShowing: function(aEvent) { let type = this.getAttribute("type"); let activeStreams; if (type == "Camera") { @@ -809,12 +809,12 @@ function getGlobalIndicator() { return true; }, - _popupHiding(aEvent) { + _popupHiding: function(aEvent) { while (this.firstChild) this.firstChild.remove(); }, - _setIndicatorState(aName, aState) { + _setIndicatorState: function(aName, aState) { let field = "_" + aName.toLowerCase(); if (aState && !this[field]) { let menu = this._hiddenDoc.createElement("menu"); @@ -840,12 +840,12 @@ function getGlobalIndicator() { this[field] = null } }, - updateIndicatorState() { + updateIndicatorState: function() { this._setIndicatorState("Camera", webrtcUI.showCameraIndicator); this._setIndicatorState("Microphone", webrtcUI.showMicrophoneIndicator); this._setIndicatorState("Screen", webrtcUI.showScreenSharingIndicator); }, - close() { + close: function() { this._setIndicatorState("Camera", false); this._setIndicatorState("Microphone", false); this._setIndicatorState("Screen", false); diff --git a/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm b/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm index 5feb7bd17093..557b867b9bf1 100644 --- a/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm +++ b/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm @@ -150,7 +150,7 @@ this.TestRunner = { // helpers - *_performCombo(combo) { + _performCombo: function*(combo) { let paddedComboIndex = padLeft(this.currentComboIndex + 1, String(this.combos.length).length); log.info("Combination " + paddedComboIndex + "/" + this.combos.length + ": " + this._comboName(combo).substring(1)); diff --git a/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm b/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm index f501ea140422..97d8354d5b0a 100644 --- a/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm +++ b/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm @@ -64,7 +64,7 @@ this.Buttons = { function createWidget() { let id = "screenshot-widget"; let spec = { - id, + id: id, label: "My Button", removable: true, tooltiptext: "", diff --git a/storage/test/unit/head_storage.js b/storage/test/unit/head_storage.js index ab05e10b593b..27a4749eda18 100644 --- a/storage/test/unit/head_storage.js +++ b/storage/test/unit/head_storage.js @@ -316,15 +316,15 @@ function openAsyncDatabase(file, options) { function executeAsync(statement, onResult) { let deferred = Promise.defer(); statement.executeAsync({ - handleError(error) { + handleError: function(error) { deferred.reject(error); }, - handleResult(result) { + handleResult: function(result) { if (onResult) { onResult(result); } }, - handleCompletion(result) { + handleCompletion: function(result) { deferred.resolve(result); } }); @@ -334,15 +334,15 @@ function executeAsync(statement, onResult) { function executeMultipleStatementsAsync(db, statements, onResult) { let deferred = Promise.defer(); db.executeAsync(statements, statements.length, { - handleError(error) { + handleError: function(error) { deferred.reject(error); }, - handleResult(result) { + handleResult: function(result) { if (onResult) { onResult(result); } }, - handleCompletion(result) { + handleCompletion: function(result) { deferred.resolve(result); } }); diff --git a/toolkit/.eslintrc.js b/toolkit/.eslintrc.js index 5eec2b565574..c79d8702d966 100644 --- a/toolkit/.eslintrc.js +++ b/toolkit/.eslintrc.js @@ -163,9 +163,6 @@ module.exports = { // No using with "no-with": "error", - // Require object-literal shorthand with ES6 method syntax - "object-shorthand": ["error", "always", { "avoidQuotes": true }], - // No spacing inside rest or spread expressions "rest-spread-spacing": "error", diff --git a/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js b/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js index 091a8a6750db..4cbd141f7662 100644 --- a/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js +++ b/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js @@ -114,7 +114,7 @@ function loadData() { if (destIndex == 0) { // create the initial frame renderData.push({ - timestamp, + timestamp: timestamp, rects: {}, }); } else if (renderData[destIndex - 1].timestamp == timestamp) { diff --git a/toolkit/components/aboutmemory/content/aboutMemory.js b/toolkit/components/aboutmemory/content/aboutMemory.js index 7856aa9feb57..c62416dc5427 100644 --- a/toolkit/components/aboutmemory/content/aboutMemory.js +++ b/toolkit/components/aboutmemory/content/aboutMemory.js @@ -498,7 +498,7 @@ function dumpGCLogAndCCLog(aVerbose) dumper.dumpGCAndCCLogsToFile("", aVerbose, /* dumpChildProcesses = */ true, { onDump: displayInfo, - onFinish() { + onFinish: function() { inProgress.remove(); } }); @@ -657,12 +657,12 @@ function loadMemoryReportsFromFile(aFilename, aTitleNote, aFn) let converter = new nsGzipConverter(); converter.asyncConvertData("gzip", "uncompressed", { data: [], - onStartRequest(aR, aC) {}, - onDataAvailable(aR, aC, aStream, aO, aCount) { + onStartRequest: function(aR, aC) {}, + onDataAvailable: function(aR, aC, aStream, aO, aCount) { let bi = new nsBinaryStream(aStream); this.data.push(bi.readBytes(aCount)); }, - onStopRequest(aR, aC, aStatusCode) { + onStopRequest: function(aR, aC, aStatusCode) { try { if (!Components.isSuccessCode(aStatusCode)) { throw new Components.Exception("Error while reading gzip file", aStatusCode); @@ -746,7 +746,7 @@ function DReport(aKind, aUnits, aAmount, aDescription, aNMerged, aPresence) } DReport.prototype = { - assertCompatible(aKind, aUnits) + assertCompatible: function(aKind, aUnits) { assert(this._kind == aKind, "Mismatched kinds"); assert(this._units == aUnits, "Mismatched units"); @@ -767,13 +767,13 @@ DReport.prototype = { // the descriptions to differ seems reasonable.) }, - merge(aJr) { + merge: function(aJr) { this.assertCompatible(aJr.kind, aJr.units); this._amount += aJr.amount; this._nMerged++; }, - toJSON(aProcess, aPath, aAmount) { + toJSON: function(aProcess, aPath, aAmount) { return { process: aProcess, path: aPath, @@ -1126,7 +1126,7 @@ function TreeNode(aUnsafeName, aUnits, aIsDegenerate) } TreeNode.prototype = { - findKid(aUnsafeName) { + findKid: function(aUnsafeName) { if (this._kids) { for (let i = 0; i < this._kids.length; i++) { if (this._kids[i]._unsafeName === aUnsafeName) { @@ -1143,7 +1143,7 @@ TreeNode.prototype = { // things. So for a non-leaf node, instead of just looking at _amount, we // instead look at the maximum absolute value of the node and all of its // descendants. - maxAbsDescendant() { + maxAbsDescendant: function() { if (!this._kids) { // No kids? Just return the absolute value of the amount. return Math.abs(this._amount); @@ -1163,7 +1163,7 @@ TreeNode.prototype = { return max; }, - toString() { + toString: function() { switch (this._units) { case UNITS_BYTES: return formatBytes(this._amount); case UNITS_COUNT: diff --git a/toolkit/components/aboutperformance/content/aboutPerformance.js b/toolkit/components/aboutperformance/content/aboutPerformance.js index f1b04df719df..862d3cf0e249 100644 --- a/toolkit/components/aboutperformance/content/aboutPerformance.js +++ b/toolkit/components/aboutperformance/content/aboutPerformance.js @@ -72,7 +72,7 @@ const MODE_GLOBAL = "global"; const MODE_RECENT = "recent"; let tabFinder = { - update() { + update: function() { this._map = new Map(); let windows = Services.wm.getEnumerator("navigator:browser"); while (windows.hasMoreElements()) { @@ -97,7 +97,7 @@ let tabFinder = { * @return {{tabbrowser: , tab: }} The * tabbrowser and tab if the latter could be found. */ - get(id) { + get: function(id) { let browser = this._map.get(id); if (!browser) { return null; @@ -106,7 +106,7 @@ let tabFinder = { return {tabbrowser, tab:tabbrowser.getTabForBrowser(browser)}; }, - getAny(ids) { + getAny: function(ids) { for (let id of ids) { let result = this.get(id); if (result) { @@ -258,7 +258,7 @@ Delta.prototype = { /** * Initialize, asynchronously. */ - promiseInit() { + promiseInit: function() { if (this.kind == "webpages") { return this._initWebpage(); } else if (this.kind == "addons") { @@ -266,7 +266,7 @@ Delta.prototype = { } throw new TypeError(); }, - _initWebpage() { + _initWebpage: function() { this._initialized = true; let found = tabFinder.getAny(this.diff.windowIds); if (!found || found.tab.linkedBrowser.contentTitle == null) { @@ -296,7 +296,7 @@ Delta.prototype = { this._show = found; this.fullName = this.diff.addonId; }), - toString() { + toString: function() { return `[Delta] ${this.diff.key} => ${this.readableName}, ${this.fullName}`; } }; @@ -444,14 +444,14 @@ var State = { /** * @return {Promise} */ - promiseDeltaSinceStartOfTime() { + promiseDeltaSinceStartOfTime: function() { return this._promiseDeltaSince(this._oldest); }, /** * @return {Promise} */ - promiseDeltaSinceStartOfBuffer() { + promiseDeltaSinceStartOfBuffer: function() { return this._promiseDeltaSince(this._buffer[0]); }, @@ -528,10 +528,10 @@ var View = { * @return {null} If the `deltaKey` doesn't have a component cached yet. * Otherwise, the value stored with `set`. */ - get(deltaKey) { + get: function(deltaKey) { return this._map.get(deltaKey); }, - set(deltaKey, value) { + set: function(deltaKey, value) { this._map.set(deltaKey, value); }, /** @@ -539,7 +539,7 @@ var View = { * * @param {Set} set a set of deltaKey. */ - trimTo(set) { + trimTo: function(set) { let remove = []; for (let key of this._map.keys()) { if (!set.has(key)) { @@ -560,7 +560,7 @@ var View = { * @param {string} nature The nature of the subset. One of "addons", "webpages" or "system". * @param {string} currentMode The current display mode. One of MODE_GLOBAL or MODE_RECENT. */ - updateCategory(subset, id, nature, currentMode) { + updateCategory: function(subset, id, nature, currentMode) { subset = subset.slice().sort(Delta.revCompare); let watcherAlerts = null; @@ -657,7 +657,7 @@ var View = { this._insertElements(toAdd, id); }, - _insertElements(elements, id) { + _insertElements: function(elements, id) { let eltContainer = document.getElementById(id); eltContainer.classList.remove("measuring"); eltContainer.eltVisibleContent.innerHTML = ""; @@ -681,7 +681,7 @@ var View = { eltContainer.textContent = "Nothing"; } }, - _setupStructure(id) { + _setupStructure: function(id) { let eltContainer = document.getElementById(id); if (!eltContainer.eltVisibleContent) { eltContainer.eltVisibleContent = document.createElement("ul"); @@ -712,7 +712,7 @@ var View = { return eltContainer; }, - _grabOrCreateElements(delta, nature) { + _grabOrCreateElements: function(delta, nature) { let cachedElements = this.DOMCache.get(delta.key); if (cachedElements) { if (cachedElements.eltRoot.parentElement) { @@ -857,7 +857,7 @@ var View = { }; var Control = { - init() { + init: function() { this._initAutorefresh(); this._initDisplayMode(); }, @@ -886,7 +886,7 @@ var Control = { // Inform watchers Services.obs.notifyObservers(null, UPDATE_COMPLETE_TOPIC, mode); }), - _setOptions(options) { + _setOptions: function(options) { dump(`about:performance _setOptions ${JSON.stringify(options)}\n`); let eltRefresh = document.getElementById("check-autorefresh"); if ((options.autoRefresh > 0) != eltRefresh.checked) { @@ -897,7 +897,7 @@ var Control = { eltCheckRecent.click(); } }, - _initAutorefresh() { + _initAutorefresh: function() { let onRefreshChange = (shouldUpdateNow = false) => { if (eltRefresh.checked == !!this._autoRefreshInterval) { // Nothing to change. @@ -920,7 +920,7 @@ var Control = { onRefreshChange(false); }, _autoRefreshInterval: null, - _initDisplayMode() { + _initDisplayMode: function() { let onModeChange = (shouldUpdateNow) => { if (eltCheckRecent.checked) { this._displayMode = MODE_RECENT; @@ -956,7 +956,7 @@ var SubprocessMonitor = { * Init will start the process of updating the table if the page is not hidden, * and set up an event listener for handling visibility changes. */ - init() { + init: function() { if (!document.hidden) { SubprocessMonitor.updateTable(); } @@ -967,7 +967,7 @@ var SubprocessMonitor = { * This function updates the table after an interval if the page is visible * and clears the interval otherwise. */ - handleVisibilityChange() { + handleVisibilityChange: function() { if (!document.hidden) { SubprocessMonitor.queueUpdate(); } else { @@ -980,7 +980,7 @@ var SubprocessMonitor = { * This function queues a timer to request the next summary using updateTable * after some delay. */ - queueUpdate() { + queueUpdate: function() { this._timeout = setTimeout(() => this.updateTable(), UPDATE_INTERVAL_MS); }, @@ -990,7 +990,7 @@ var SubprocessMonitor = { * @param {object} summaries The object with the updated RSS and USS values. * @param {string} pid The pid represented by the row for which we update. */ - updateRow(row, summaries, pid) { + updateRow: function(row, summaries, pid) { row.cells[0].textContent = pid; let RSSval = DownloadUtils.convertByteUnits(summaries[pid].rss); row.cells[1].textContent = RSSval.join(" "); @@ -1002,7 +1002,7 @@ var SubprocessMonitor = { * This function adds a row to the subprocess-performance table for every new pid * and populates and regularly updates it with RSS/USS measurements. */ - updateTable() { + updateTable: function() { if (!document.hidden) { Memory.summary().then((summaries) => { if (!(Object.keys(summaries).length)) { diff --git a/toolkit/components/addoncompat/CompatWarning.jsm b/toolkit/components/addoncompat/CompatWarning.jsm index 2e9fd5ad6be7..b32409a46b6b 100644 --- a/toolkit/components/addoncompat/CompatWarning.jsm +++ b/toolkit/components/addoncompat/CompatWarning.jsm @@ -27,7 +27,7 @@ var CompatWarning = { // might only want to warn about it if the listener actually // fires. However, we want the warning to show a stack for the // registration site. - delayedWarning(msg, addon, warning) { + delayedWarning: function(msg, addon, warning) { function isShimLayer(filename) { return filename.indexOf("CompatWarning.jsm") != -1 || filename.indexOf("RemoteAddonsParent.jsm") != -1 || @@ -86,7 +86,7 @@ var CompatWarning = { }; }, - warn(msg, addon, warning) { + warn: function(msg, addon, warning) { let delayed = this.delayedWarning(msg, addon, warning); delayed(); }, diff --git a/toolkit/components/addoncompat/Prefetcher.jsm b/toolkit/components/addoncompat/Prefetcher.jsm index 3dd59e1f1609..2d836690cc23 100644 --- a/toolkit/components/addoncompat/Prefetcher.jsm +++ b/toolkit/components/addoncompat/Prefetcher.jsm @@ -314,7 +314,7 @@ function Database(trigger, addons) Database.prototype = { // Add an object to a table. - add(table, obj) { + add: function(table, obj) { if (!this.tables.has(table)) { this.tables.set(table, new Set()); } @@ -327,13 +327,13 @@ Database.prototype = { this.todo.push([table, obj]); }, - cache(...args) { + cache: function(...args) { this.cached.push(args); }, // Run a fixed-point iteration that adds objects to table based on // this.rules until there are no more objects to add. - process() { + process: function() { while (this.todo.length) { let [table, obj] = this.todo.pop(); let rules = this.rules.get(table); @@ -348,7 +348,7 @@ Database.prototype = { }; var Prefetcher = { - init() { + init: function() { // Give an index to each rule and store it in this.ruleMap based // on the index. The index is used to serialize and deserialize // data from content to chrome. @@ -368,7 +368,7 @@ var Prefetcher = { Services.obs.addObserver(this, "xpcom-shutdown", false); }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { if (topic == "xpcom-shutdown") { Services.prefs.removeObserver(PREF_PREFETCHING_ENABLED, this); Services.obs.removeObserver(this, "xpcom-shutdown"); @@ -381,7 +381,7 @@ var Prefetcher = { // described by the trigger string. |addons| is a list of addons // that have listeners installed for the event. |args| is // event-specific data (such as the event object). - prefetch(trigger, addons, args) { + prefetch: function(trigger, addons, args) { if (!this.prefetchingEnabled) { return [[], []]; } @@ -425,7 +425,7 @@ var Prefetcher = { // Generate a two-level mapping based on cached data received from // the content process. - generateCache(prefetched, cpows) { + generateCache: function(prefetched, cpows) { let cache = new Map(); for (let item of prefetched) { // Replace anything of the form {cpow: } with the actual @@ -446,7 +446,7 @@ var Prefetcher = { // Run |func|, using the prefetched data in |prefetched| and |cpows| // as a cache. - withPrefetching(prefetched, cpows, func) { + withPrefetching: function(prefetched, cpows, func) { if (!this.prefetchingEnabled) { return func(); } @@ -466,7 +466,7 @@ var Prefetcher = { // Called by shim code in the chrome process to check if target.prop // is cached. - lookupInCache(addon, target, prop) { + lookupInCache: function(addon, target, prop) { if (!this.cache || !Cu.isCrossProcessWrapper(target)) { return null; } diff --git a/toolkit/components/addoncompat/RemoteAddonsChild.jsm b/toolkit/components/addoncompat/RemoteAddonsChild.jsm index 9e430a44e90e..1aacc7f7abf3 100644 --- a/toolkit/components/addoncompat/RemoteAddonsChild.jsm +++ b/toolkit/components/addoncompat/RemoteAddonsChild.jsm @@ -45,7 +45,7 @@ function setDefault(dict, key, default_) // In the child, clients can watch for changes to all paths that start // with a given component. var NotificationTracker = { - init() { + init: function() { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); cpmm.addMessageListener("Addons:ChangeNotification", this); @@ -54,7 +54,7 @@ var NotificationTracker = { this._watchers = {}; }, - receiveMessage(msg) { + receiveMessage: function(msg) { let path = msg.data.path; let count = msg.data.count; @@ -72,7 +72,7 @@ var NotificationTracker = { } }, - runCallback(watcher, path, count) { + runCallback: function(watcher, path, count) { let pathString = path.join("/"); let registeredSet = this._registered.get(watcher); let registered = registeredSet.has(pathString); @@ -85,7 +85,7 @@ var NotificationTracker = { } }, - findPaths(prefix) { + findPaths: function(prefix) { if (!this._paths) { return []; } @@ -117,12 +117,12 @@ var NotificationTracker = { return result; }, - findSuffixes(prefix) { + findSuffixes: function(prefix) { let paths = this.findPaths(prefix); return paths.map(([path, count]) => path[path.length - 1]); }, - watch(component1, watcher) { + watch: function(component1, watcher) { setDefault(this._watchers, component1, []).push(watcher); this._registered.set(watcher, new Set()); @@ -132,7 +132,7 @@ var NotificationTracker = { } }, - unwatch(component1, watcher) { + unwatch: function(component1, watcher) { let watchers = this._watchers[component1]; let index = watchers.lastIndexOf(watcher); if (index > -1) { @@ -156,7 +156,7 @@ var ContentPolicyChild = { _classID: Components.ID("6e869130-635c-11e2-bcfd-0800200c9a66"), _contractID: "@mozilla.org/addon-child/policy;1", - init() { + init: function() { let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); registrar.registerFactory(this._classID, this._classDescription, this._contractID, this); @@ -167,7 +167,7 @@ var ContentPolicyChild = { Ci.nsIChannelEventSink, Ci.nsIFactory, Ci.nsISupportsWeakReference]), - track(path, register) { + track: function(path, register) { let catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager); if (register) { catMan.addCategoryEntry("content-policy", this._contractID, this._contractID, false, true); @@ -176,7 +176,7 @@ var ContentPolicyChild = { } }, - shouldLoad(contentType, contentLocation, requestOrigin, + shouldLoad: function(contentType, contentLocation, requestOrigin, node, mimeTypeGuess, extra, requestPrincipal) { let addons = NotificationTracker.findSuffixes(["content-policy"]); let [prefetched, cpows] = Prefetcher.prefetch("ContentPolicy.shouldLoad", @@ -186,12 +186,12 @@ var ContentPolicyChild = { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); let rval = cpmm.sendRpcMessage("Addons:ContentPolicy:Run", { - contentType, + contentType: contentType, contentLocation: contentLocation.spec, requestOrigin: requestOrigin ? requestOrigin.spec : null, - mimeTypeGuess, - requestPrincipal, - prefetched, + mimeTypeGuess: mimeTypeGuess, + requestPrincipal: requestPrincipal, + prefetched: prefetched, }, cpows); if (rval.length != 1) { return Ci.nsIContentPolicy.ACCEPT; @@ -200,11 +200,11 @@ var ContentPolicyChild = { return rval[0]; }, - shouldProcess(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) { + shouldProcess: function(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) { return Ci.nsIContentPolicy.ACCEPT; }, - createInstance(outer, iid) { + createInstance: function(outer, iid) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -235,7 +235,7 @@ AboutProtocolChannel.prototype = { name: null, status: Cr.NS_OK, - asyncOpen(listener, context) { + asyncOpen: function(listener, context) { // Ask the parent to synchronously read all the data from the channel. let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); @@ -277,33 +277,33 @@ AboutProtocolChannel.prototype = { Services.tm.currentThread.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL); }, - asyncOpen2(listener) { + asyncOpen2: function(listener) { // throws an error if security checks fail var outListener = contentSecManager.performSecurityCheck(this, listener); this.asyncOpen(outListener, null); }, - open() { + open: function() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - open2() { + open2: function() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - isPending() { + isPending: function() { return false; }, - cancel() { + cancel: function() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - suspend() { + suspend: function() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - resume() { + resume: function() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, @@ -318,7 +318,7 @@ function AboutProtocolInstance(contractID) } AboutProtocolInstance.prototype = { - createInstance(outer, iid) { + createInstance: function(outer, iid) { if (outer != null) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -326,7 +326,7 @@ AboutProtocolInstance.prototype = { return this.QueryInterface(iid); }, - getURIFlags(uri) { + getURIFlags: function(uri) { // Cache the result to avoid the extra IPC. if (this._uriFlags !== undefined) { return this._uriFlags; @@ -354,7 +354,7 @@ AboutProtocolInstance.prototype = { // available to CPOWs. Consequently, we return a shim channel that, // when opened, asks the parent to open the channel and read out all // the data. - newChannel(uri, loadInfo) { + newChannel: function(uri, loadInfo) { return new AboutProtocolChannel(uri, this._contractID, loadInfo); }, @@ -364,7 +364,7 @@ AboutProtocolInstance.prototype = { var AboutProtocolChild = { _classDescription: "Addon shim about: protocol handler", - init() { + init: function() { // Maps contractIDs to instances this._instances = new Map(); // Maps contractIDs to classIDs @@ -372,7 +372,7 @@ var AboutProtocolChild = { NotificationTracker.watch("about-protocol", this); }, - track(path, register) { + track: function(path, register) { let contractID = path[1]; let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); if (register) { @@ -397,11 +397,11 @@ var AboutProtocolChild = { // This code registers observers in the child whenever an add-on in // the parent asks for notifications on the given topic. var ObserverChild = { - init() { + init: function() { NotificationTracker.watch("observer", this); }, - track(path, register) { + track: function(path, register) { let topic = path[1]; if (register) { Services.obs.addObserver(this, topic, false); @@ -410,13 +410,13 @@ var ObserverChild = { } }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); cpmm.sendRpcMessage("Addons:Observer:Run", {}, { - topic, - subject, - data + topic: topic, + subject: subject, + data: data }); } }; @@ -433,11 +433,11 @@ function EventTargetChild(childGlobal) } EventTargetChild.prototype = { - uninit() { + uninit: function() { NotificationTracker.unwatch("event", this); }, - track(path, register) { + track: function(path, register) { let eventType = path[1]; let useCapture = path[2]; let listener = useCapture ? this.capturingHandler : this.nonCapturingHandler; @@ -448,7 +448,7 @@ EventTargetChild.prototype = { } }, - handleEvent(capturing, event) { + handleEvent: function(capturing, event) { let addons = NotificationTracker.findSuffixes(["event", event.type, capturing]); let [prefetched, cpows] = Prefetcher.prefetch("EventTarget.handleEvent", addons, @@ -459,9 +459,9 @@ EventTargetChild.prototype = { this._childGlobal.sendRpcMessage("Addons:Event:Run", {type: event.type, - capturing, + capturing: capturing, isTrusted: event.isTrusted, - prefetched}, + prefetched: prefetched}, cpows); } }; @@ -481,34 +481,34 @@ function SandboxChild(chromeGlobal) } SandboxChild.prototype = { - uninit() { + uninit: function() { this.clearSandboxes(); }, - addListener() { + addListener: function() { let webProgress = this.chromeGlobal.docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); webProgress.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION); }, - removeListener() { + removeListener: function() { let webProgress = this.chromeGlobal.docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); webProgress.removeProgressListener(this); }, - onLocationChange(webProgress, request, location, flags) { + onLocationChange: function(webProgress, request, location, flags) { this.clearSandboxes(); }, - addSandbox(sandbox) { + addSandbox: function(sandbox) { if (this.sandboxes.length == 0) { this.addListener(); } this.sandboxes.push(sandbox); }, - clearSandboxes() { + clearSandboxes: function() { if (this.sandboxes.length) { this.removeListener(); } @@ -522,7 +522,7 @@ SandboxChild.prototype = { var RemoteAddonsChild = { _ready: false, - makeReady() { + makeReady: function() { let shims = [ Prefetcher, NotificationTracker, @@ -540,7 +540,7 @@ var RemoteAddonsChild = { } }, - init(global) { + init: function(global) { if (!this._ready) { if (!Services.cpmm.initialProcessData.remoteAddonsParentInitted) { @@ -551,7 +551,7 @@ var RemoteAddonsChild = { this._ready = true; } - global.sendAsyncMessage("Addons:RegisterGlobal", {}, {global}); + global.sendAsyncMessage("Addons:RegisterGlobal", {}, {global: global}); let sandboxChild = new SandboxChild(global); global.addSandbox = sandboxChild.addSandbox.bind(sandboxChild); @@ -560,7 +560,7 @@ var RemoteAddonsChild = { return [new EventTargetChild(global), sandboxChild]; }, - uninit(perTabShims) { + uninit: function(perTabShims) { for (let shim of perTabShims) { try { shim.uninit(); diff --git a/toolkit/components/addoncompat/RemoteAddonsParent.jsm b/toolkit/components/addoncompat/RemoteAddonsParent.jsm index 5f409a832896..ec2d49758ccf 100644 --- a/toolkit/components/addoncompat/RemoteAddonsParent.jsm +++ b/toolkit/components/addoncompat/RemoteAddonsParent.jsm @@ -50,13 +50,13 @@ var NotificationTracker = { // given path are present in _paths. _paths: {}, - init() { + init: function() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.initialProcessData.remoteAddonsNotificationPaths = this._paths; }, - add(path) { + add: function(path) { let tracked = this._paths; for (let component of path) { tracked = setDefault(tracked, component, {}); @@ -67,10 +67,10 @@ var NotificationTracker = { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); - ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path, count}); + ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path: path, count: count}); }, - remove(path) { + remove: function(path) { let tracked = this._paths; for (let component of path) { tracked = setDefault(tracked, component, {}); @@ -79,7 +79,7 @@ var NotificationTracker = { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); - ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path, count: tracked._count}); + ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path: path, count: tracked._count}); }, }; NotificationTracker.init(); @@ -106,7 +106,7 @@ function Interposition(name, base) // content policy is added or removed. It also runs all the registered // add-on content policies when the child asks it to do so. var ContentPolicyParent = { - init() { + init: function() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:ContentPolicy:Run", this); @@ -114,17 +114,17 @@ var ContentPolicyParent = { this._policies = new Map(); }, - addContentPolicy(addon, name, cid) { + addContentPolicy: function(addon, name, cid) { this._policies.set(name, cid); NotificationTracker.add(["content-policy", addon]); }, - removeContentPolicy(addon, name) { + removeContentPolicy: function(addon, name) { this._policies.delete(name); NotificationTracker.remove(["content-policy", addon]); }, - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { switch (aMessage.name) { case "Addons:ContentPolicy:Run": return this.shouldLoad(aMessage.data, aMessage.objects); @@ -132,7 +132,7 @@ var ContentPolicyParent = { return undefined; }, - shouldLoad(aData, aObjects) { + shouldLoad: function(aData, aObjects) { for (let policyCID of this._policies.values()) { let policy; try { @@ -196,7 +196,7 @@ CategoryManagerInterposition.methods.deleteCategoryEntry = // protocol handler in the parent and we want the child to be able to // use it. This code is pretty specific to Adblock's usage. var AboutProtocolParent = { - init() { + init: function() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:AboutProtocol:GetURIFlags", this); @@ -204,12 +204,12 @@ var AboutProtocolParent = { this._protocols = []; }, - registerFactory(addon, class_, className, contractID, factory) { - this._protocols.push({contractID, factory}); + registerFactory: function(addon, class_, className, contractID, factory) { + this._protocols.push({contractID: contractID, factory: factory}); NotificationTracker.add(["about-protocol", contractID, addon]); }, - unregisterFactory(addon, class_, factory) { + unregisterFactory: function(addon, class_, factory) { for (let i = 0; i < this._protocols.length; i++) { if (this._protocols[i].factory == factory) { NotificationTracker.remove(["about-protocol", this._protocols[i].contractID, addon]); @@ -219,7 +219,7 @@ var AboutProtocolParent = { } }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "Addons:AboutProtocol:GetURIFlags": return this.getURIFlags(msg); @@ -229,7 +229,7 @@ var AboutProtocolParent = { return undefined; }, - getURIFlags(msg) { + getURIFlags: function(msg) { let uri = BrowserUtils.makeURI(msg.data.uri); let contractID = msg.data.contractID; let module = Cc[contractID].getService(Ci.nsIAboutModule); @@ -243,10 +243,10 @@ var AboutProtocolParent = { // We immediately read all the data out of the channel here and // return it to the child. - openChannel(msg) { + openChannel: function(msg) { function wrapGetInterface(cpow) { return { - getInterface(intf) { return cpow.getInterface(intf); } + getInterface: function(intf) { return cpow.getInterface(intf); } }; } @@ -292,7 +292,7 @@ var AboutProtocolParent = { let stream = channel.open2(); let data = NetUtil.readInputStreamToString(stream, stream.available(), {}); return { - data, + data: data, contentType: channel.contentType }; } catch (e) { @@ -334,23 +334,23 @@ ComponentRegistrarInterposition.methods.unregisterFactory = // in the parent because there might be non-add-on T observers that // won't expect to get notified in this case. var ObserverParent = { - init() { + init: function() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:Observer:Run", this); }, - addObserver(addon, observer, topic, ownsWeak) { + addObserver: function(addon, observer, topic, ownsWeak) { Services.obs.addObserver(observer, "e10s-" + topic, ownsWeak); NotificationTracker.add(["observer", topic, addon]); }, - removeObserver(addon, observer, topic) { + removeObserver: function(addon, observer, topic) { Services.obs.removeObserver(observer, "e10s-" + topic); NotificationTracker.remove(["observer", topic, addon]); }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "Addons:Observer:Run": this.notify(msg.objects.subject, msg.objects.topic, msg.objects.data); @@ -358,7 +358,7 @@ var ObserverParent = { } }, - notify(subject, topic, data) { + notify: function(subject, topic, data) { let e = Services.obs.enumerateObservers("e10s-" + topic); while (e.hasMoreElements()) { let obs = e.getNext().QueryInterface(Ci.nsIObserver); @@ -410,7 +410,7 @@ ObserverInterposition.methods.removeObserver = // This object is responsible for forwarding events from the child to // the parent. var EventTargetParent = { - init() { + init: function() { // The _listeners map goes from targets (either elements // or windows) to a dictionary from event types to listeners. this._listeners = new WeakMap(); @@ -426,7 +426,7 @@ var EventTargetParent = { // (the or elements), then we return the // . If it's some generic element, then we return the // window itself. - redirectEventTarget(target) { + redirectEventTarget: function(target) { if (Cu.isCrossProcessWrapper(target)) { return null; } @@ -456,12 +456,12 @@ var EventTargetParent = { // When a given event fires in the child, we fire it on the // element and the window since those are the two possible // results of redirectEventTarget. - getTargets(browser) { + getTargets: function(browser) { let window = browser.ownerDocument.defaultView; return [browser, window]; }, - addEventListener(addon, target, type, listener, useCapture, wantsUntrusted, delayedWarning) { + addEventListener: function(addon, target, type, listener, useCapture, wantsUntrusted, delayedWarning) { let newTarget = this.redirectEventTarget(target); if (!newTarget) { return; @@ -489,14 +489,14 @@ var EventTargetParent = { } } - forType.push({listener, - target, - wantsUntrusted, - useCapture, - delayedWarning}); + forType.push({listener: listener, + target: target, + wantsUntrusted: wantsUntrusted, + useCapture: useCapture, + delayedWarning: delayedWarning}); }, - removeEventListener(addon, target, type, listener, useCapture) { + removeEventListener: function(addon, target, type, listener, useCapture) { let newTarget = this.redirectEventTarget(target); if (!newTarget) { return; @@ -521,7 +521,7 @@ var EventTargetParent = { } }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "Addons:Event:Run": this.dispatch(msg.target, msg.data.type, msg.data.capturing, @@ -530,7 +530,7 @@ var EventTargetParent = { } }, - dispatch(browser, type, capturing, isTrusted, prefetched, cpows) { + dispatch: function(browser, type, capturing, isTrusted, prefetched, cpows) { let event = cpows.event; let eventTarget = cpows.eventTarget; let targets = this.getTargets(browser); @@ -554,7 +554,7 @@ var EventTargetParent = { for (let [handler, target] of handlers) { let EventProxy = { - get(knownProps, name) { + get: function(knownProps, name) { if (knownProps.hasOwnProperty(name)) return knownProps[name]; return event[name]; @@ -563,8 +563,8 @@ var EventTargetParent = { let proxyEvent = new Proxy({ currentTarget: target, target: eventTarget, - type, - QueryInterface(iid) { + type: type, + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIDOMEventTarget)) return proxyEvent; @@ -698,7 +698,7 @@ function chromeGlobalForContentWindow(window) var SandboxParent = { componentsMap: new WeakMap(), - makeContentSandbox(addon, chromeGlobal, principals, ...rest) { + makeContentSandbox: function(addon, chromeGlobal, principals, ...rest) { CompatWarning.warn("This sandbox should be created from the child process.", addon, CompatWarning.warnings.sandboxes); if (rest.length) { @@ -733,7 +733,7 @@ var SandboxParent = { return sandbox; }, - evalInSandbox(code, sandbox, ...rest) { + evalInSandbox: function(code, sandbox, ...rest) { let cu = this.componentsMap.get(sandbox); return cu.evalInSandbox(code, sandbox, ...rest); } @@ -933,7 +933,7 @@ function wrapProgressListener(kind, listener) } let ListenerHandler = { - get(target, name) { + get: function(target, name) { if (name.startsWith("on")) { return function(...args) { listener[name].apply(listener, RemoteWebProgressManager.argumentsForAddonListener(kind, args)); @@ -1026,7 +1026,7 @@ RemoteWebNavigationInterposition.getters.sessionHistory = function(addon, target } var RemoteAddonsParent = { - init() { + init: function() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Addons:RegisterGlobal", this); @@ -1036,7 +1036,7 @@ var RemoteAddonsParent = { this.browserToGlobal = new WeakMap(); }, - getInterfaceInterpositions() { + getInterfaceInterpositions: function() { let result = {}; function register(intf, interp) { @@ -1052,7 +1052,7 @@ var RemoteAddonsParent = { return result; }, - getTaggedInterpositions() { + getTaggedInterpositions: function() { let result = {}; function register(tag, interp) { @@ -1069,7 +1069,7 @@ var RemoteAddonsParent = { return result; }, - receiveMessage(msg) { + receiveMessage: function(msg) { switch (msg.name) { case "Addons:RegisterGlobal": this.browserToGlobal.set(msg.target, msg.objects.global); diff --git a/toolkit/components/addoncompat/ShimWaiver.jsm b/toolkit/components/addoncompat/ShimWaiver.jsm index 67db8f60f5aa..402ab4c32247 100644 --- a/toolkit/components/addoncompat/ShimWaiver.jsm +++ b/toolkit/components/addoncompat/ShimWaiver.jsm @@ -5,7 +5,7 @@ this.EXPORTED_SYMBOLS = ["ShimWaiver"]; this.ShimWaiver = { - getProperty(obj, prop) { + getProperty: function(obj, prop) { let rv = obj[prop]; if (rv instanceof Function) { rv = rv.bind(obj); diff --git a/toolkit/components/addoncompat/defaultShims.js b/toolkit/components/addoncompat/defaultShims.js index c7675cad5135..a786efed7d39 100644 --- a/toolkit/components/addoncompat/defaultShims.js +++ b/toolkit/components/addoncompat/defaultShims.js @@ -22,15 +22,15 @@ DefaultInterpositionService.prototype = { classID: Components.ID("{50bc93ce-602a-4bef-bf3a-61fc749c4caf}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonInterposition, Ci.nsISupportsWeakReference]), - getWhitelist() { + getWhitelist: function() { return []; }, - interposeProperty(addon, target, iid, prop) { + interposeProperty: function(addon, target, iid, prop) { return null; }, - interposeCall(addonId, originalFunc, originalThis, args) { + interposeCall: function(addonId, originalFunc, originalThis, args) { args.splice(0, 0, addonId); return originalFunc.apply(originalThis, args); }, diff --git a/toolkit/components/addoncompat/multiprocessShims.js b/toolkit/components/addoncompat/multiprocessShims.js index 1e5ea4f72752..8b252a0c484a 100644 --- a/toolkit/components/addoncompat/multiprocessShims.js +++ b/toolkit/components/addoncompat/multiprocessShims.js @@ -102,13 +102,13 @@ AddonInterpositionService.prototype = { classID: Components.ID("{1363d5f0-d95e-11e3-9c1a-0800200c9a66}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonInterposition, Ci.nsISupportsWeakReference]), - getWhitelist() { + getWhitelist: function() { return this._whitelist; }, // When the interface is not known for a method call, this code // determines the type of the target object. - getObjectTag(target) { + getObjectTag: function(target) { if (Cu.isCrossProcessWrapper(target)) { return Cu.getCrossProcessWrapperTag(target); } @@ -134,7 +134,7 @@ AddonInterpositionService.prototype = { return "generic"; }, - interposeProperty(addon, target, iid, prop) { + interposeProperty: function(addon, target, iid, prop) { let interp; if (iid) { interp = this._interfaceInterpositions[iid]; @@ -173,7 +173,7 @@ AddonInterpositionService.prototype = { return Prefetcher.lookupInCache(addon, target, prop); }, - interposeCall(addonId, originalFunc, originalThis, args) { + interposeCall: function(addonId, originalFunc, originalThis, args) { args.splice(0, 0, addonId); return originalFunc.apply(originalThis, args); }, diff --git a/toolkit/components/addoncompat/tests/addon/bootstrap.js b/toolkit/components/addoncompat/tests/addon/bootstrap.js index 1364346bfed7..5e69fee22cf9 100644 --- a/toolkit/components/addoncompat/tests/addon/bootstrap.js +++ b/toolkit/components/addoncompat/tests/addon/bootstrap.js @@ -283,7 +283,7 @@ function testAboutModuleRegistration() } TestChannel.prototype = { - asyncOpen(listener, context) { + asyncOpen: function(listener, context) { let stream = this.open(); let runnable = { run: () => { @@ -301,13 +301,13 @@ function testAboutModuleRegistration() Services.tm.currentThread.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL); }, - asyncOpen2(listener) { + asyncOpen2: function(listener) { // throws an error if security checks fail var outListener = contentSecManager.performSecurityCheck(this, listener); return this.asyncOpen(outListener, null); }, - open() { + open: function() { function getWindow(channel) { try { @@ -334,22 +334,22 @@ function testAboutModuleRegistration() return stream; }, - open2() { + open2: function() { // throws an error if security checks fail contentSecManager.performSecurityCheck(this, null); return this.open(); }, - isPending() { + isPending: function() { return false; }, - cancel() { + cancel: function() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - suspend() { + suspend: function() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - resume() { + resume: function() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, @@ -391,7 +391,7 @@ function testAboutModuleRegistration() }; let factory = { - createInstance(outer, iid) { + createInstance: function(outer, iid) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -519,7 +519,7 @@ function testProgressListener() let sawTabsLocChange = false; let globalListener = { - onLocationChange(webProgress, request, uri) { + onLocationChange: function(webProgress, request, uri) { if (uri.spec == url) { sawGlobalLocChange = true; ok(request instanceof Ci.nsIHttpChannel, "Global listener channel is an HTTP channel"); @@ -528,7 +528,7 @@ function testProgressListener() }; let tabsListener = { - onLocationChange(browser, webProgress, request, uri) { + onLocationChange: function(browser, webProgress, request, uri) { if (uri.spec == url) { sawTabsLocChange = true; ok(request instanceof Ci.nsIHttpChannel, "Tab listener channel is an HTTP channel"); diff --git a/toolkit/components/addoncompat/tests/browser/browser_addonShims.js b/toolkit/components/addoncompat/tests/browser/browser_addonShims.js index d2326ac16206..ca28782cd0c6 100644 --- a/toolkit/components/addoncompat/tests/browser/browser_addonShims.js +++ b/toolkit/components/addoncompat/tests/browser/browser_addonShims.js @@ -14,7 +14,7 @@ function addAddon(url) AddonManager.getInstallForURL(url, installer => { installer.install(); let listener = { - onInstallEnded(addon, addonInstall) { + onInstallEnded: function(addon, addonInstall) { installer.removeListener(listener); // Wait for add-on's startup scripts to execute. See bug 997408 @@ -36,7 +36,7 @@ function removeAddon(addon) return new Promise(function(resolve, reject) { let listener = { - onUninstalled(uninstalledAddon) { + onUninstalled: function(uninstalledAddon) { if (uninstalledAddon != addon) { return; } @@ -53,12 +53,12 @@ add_task(function* test_addon_shims() { yield SpecialPowers.pushPrefEnv({set: [["dom.ipc.shims.enabledWarnings", true]]}); let addon = yield addAddon(ADDON_URL); - yield window.runAddonShimTests({ok, is, info}); + yield window.runAddonShimTests({ok: ok, is: is, info: info}); yield removeAddon(addon); if (Services.appinfo.browserTabsRemoteAutostart) { addon = yield addAddon(COMPAT_ADDON_URL); - yield window.runAddonTests({ok, is, info}); + yield window.runAddonTests({ok: ok, is: is, info: info}); yield removeAddon(addon); } }); diff --git a/toolkit/components/alerts/test/test_alerts.html b/toolkit/components/alerts/test/test_alerts.html index b210af4b6d9a..2e55aa5ffa8a 100644 --- a/toolkit/components/alerts/test/test_alerts.html +++ b/toolkit/components/alerts/test/test_alerts.html @@ -21,7 +21,7 @@ var observer = { alertShow: false, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { is(aData, "foobarcookie", "Checking whether the alert cookie was passed correctly"); if (aTopic == "alertclickcallback") { todo(false, "Did someone click the notification while running mochitests? (Please don't.)"); diff --git a/toolkit/components/asyncshutdown/AsyncShutdown.jsm b/toolkit/components/asyncshutdown/AsyncShutdown.jsm index 755cffbf1a01..8a341edb1ba4 100644 --- a/toolkit/components/asyncshutdown/AsyncShutdown.jsm +++ b/toolkit/components/asyncshutdown/AsyncShutdown.jsm @@ -53,7 +53,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task", XPCOMUtils.defineLazyServiceGetter(this, "gDebug", "@mozilla.org/xpcom/debug;1", "nsIDebug2"); Object.defineProperty(this, "gCrashReporter", { - get() { + get: function() { delete this.gCrashReporter; try { let reporter = Cc["@mozilla.org/xre/app-info;1"]. @@ -116,7 +116,7 @@ PromiseSet.prototype = { * @return {Promise} Resolved once all Promise have been resolved or removed, * or rejected after at least one Promise has rejected. */ - wait() { + wait: function() { // Pick an arbitrary element in the map, if any exists. let entry = this._indirections.entries().next(); if (entry.done) { @@ -139,7 +139,7 @@ PromiseSet.prototype = { * Calls to wait (including ongoing calls) will only return once * `key` has either resolved or been removed. */ - add(key) { + add: function(key) { this._ensurePromise(key); let indirection = PromiseUtils.defer(); key.then( @@ -163,7 +163,7 @@ PromiseSet.prototype = { * Calls to wait (including ongoing calls) will ignore this promise, * unless it is added again. */ - delete(key) { + delete: function(key) { this._ensurePromise(key); let value = this._indirections.get(key); if (!value) { @@ -174,7 +174,7 @@ PromiseSet.prototype = { return true; }, - _ensurePromise(key) { + _ensurePromise: function(key) { if (!key || typeof key != "object") { throw new Error("Expected an object"); } @@ -335,9 +335,9 @@ function getOrigin(topFrame, filename = null, lineNumber = null, stack = null) { } return { - filename, - lineNumber, - stack, + filename: filename, + lineNumber: lineNumber, + stack: stack, }; } catch (ex) { return { @@ -436,7 +436,7 @@ function getPhase(topic) { * // No specific guarantee about completion of profileBeforeChange * }); */ - addBlocker(name, condition, details = null) { + addBlocker: function(name, condition, details = null) { spinner.addBlocker(name, condition, details); }, /** @@ -451,7 +451,7 @@ function getPhase(topic) { * the blocker has never been installed or that the phase has * completed and the blocker has already been resolved. */ - removeBlocker(condition) { + removeBlocker: function(condition) { return spinner.removeBlocker(condition); }, @@ -499,7 +499,7 @@ Spinner.prototype = { * See the documentation of `addBlocker` in property `client` * of instances of `Barrier`. */ - addBlocker(name, condition, details) { + addBlocker: function(name, condition, details) { this._barrier.client.addBlocker(name, condition, details); }, /** @@ -513,7 +513,7 @@ Spinner.prototype = { * the blocker has never been installed or that the phase has * completed and the blocker has already been resolved. */ - removeBlocker(condition) { + removeBlocker: function(condition) { return this._barrier.client.removeBlocker(condition); }, @@ -522,7 +522,7 @@ Spinner.prototype = { }, // nsIObserver.observe - observe() { + observe: function() { let topic = this._topic; debug(`Starting phase ${ topic }`); Services.obs.removeObserver(this, topic); @@ -751,10 +751,10 @@ function Barrier(name) { } let blocker = { - trigger, - promise, - name, - fetchState, + trigger: trigger, + promise: promise, + name: name, + fetchState: fetchState, getOrigin: () => getOrigin(topFrame, filename, lineNumber, stack), }; @@ -810,11 +810,11 @@ Barrier.prototype = Object.freeze({ let {name, fetchState} = blocker; let {stack, filename, lineNumber} = blocker.getOrigin(); frozen.push({ - name, + name: name, state: safeGetState(fetchState), - filename, - lineNumber, - stack + filename: filename, + lineNumber: lineNumber, + stack: stack }); } return frozen; @@ -842,14 +842,14 @@ Barrier.prototype = Object.freeze({ * * @return {Promise} A promise satisfied once all blockers are complete. */ - wait(options = {}) { + wait: function(options = {}) { // This method only implements caching on top of _wait() if (this._promise) { return this._promise; } return this._promise = this._wait(options); }, - _wait(options) { + _wait: function(options) { // Sanity checks if (this._isStarted) { @@ -990,7 +990,7 @@ Barrier.prototype = Object.freeze({ return promise; }, - _removeBlocker(condition) { + _removeBlocker: function(condition) { if (!this._waitForMe || !this._promiseToBlocker || !this._conditionToPromise) { // We have already cleaned up everything. return false; diff --git a/toolkit/components/asyncshutdown/nsAsyncShutdown.js b/toolkit/components/asyncshutdown/nsAsyncShutdown.js index 349fd175d3a3..bd2c9a2fdf3a 100644 --- a/toolkit/components/asyncshutdown/nsAsyncShutdown.js +++ b/toolkit/components/asyncshutdown/nsAsyncShutdown.js @@ -27,7 +27,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task", */ var PropertyBagConverter = { // From nsIPropertyBag to JS - toObject(bag) { + toObject: function(bag) { if (!(bag instanceof Ci.nsIPropertyBag)) { throw new TypeError("Not a property bag"); } @@ -40,7 +40,7 @@ var PropertyBagConverter = { } return result; }, - toValue(property) { + toValue: function(property) { if (typeof property != "object") { return property; } @@ -54,7 +54,7 @@ var PropertyBagConverter = { }, // From JS to nsIPropertyBag - fromObject(obj) { + fromObject: function(obj) { if (obj == null || typeof obj != "object") { throw new TypeError("Invalid object: " + obj); } @@ -66,7 +66,7 @@ var PropertyBagConverter = { } return bag; }, - fromValue(value) { + fromValue: function(value) { if (typeof value == "function") { return null; // Emulating the behavior of JSON.stringify with functions } @@ -100,7 +100,7 @@ function nsAsyncShutdownClient(moduleClient) { this._byName = new Map(); } nsAsyncShutdownClient.prototype = { - _getPromisified(xpcomBlocker) { + _getPromisified: function(xpcomBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate) { return null; @@ -110,7 +110,7 @@ nsAsyncShutdownClient.prototype = { } return null; }, - _setPromisified(xpcomBlocker, moduleBlocker) { + _setPromisified: function(xpcomBlocker, moduleBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate) { this._byName.set(xpcomBlocker.name, {xpcom: xpcomBlocker, @@ -122,7 +122,7 @@ nsAsyncShutdownClient.prototype = { } throw new Error("We have already registered a distinct blocker with the same name: " + xpcomBlocker.name); }, - _deletePromisified(xpcomBlocker) { + _deletePromisified: function(xpcomBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate || candidate.xpcom !== xpcomBlocker) { return false; @@ -136,7 +136,7 @@ nsAsyncShutdownClient.prototype = { get name() { return this._moduleClient.name; }, - addBlocker(/* nsIAsyncShutdownBlocker*/ xpcomBlocker, + addBlocker: function(/* nsIAsyncShutdownBlocker*/ xpcomBlocker, fileName, lineNumber, stack) { // We need a Promise-based function with the same behavior as // `xpcomBlocker`. Furthermore, to support `removeBlocker`, we @@ -171,12 +171,12 @@ nsAsyncShutdownClient.prototype = { return null; }, filename: fileName, - lineNumber, - stack, + lineNumber: lineNumber, + stack: stack, }); }, - removeBlocker(xpcomBlocker) { + removeBlocker: function(xpcomBlocker) { let moduleBlocker = this._getPromisified(xpcomBlocker); if (!moduleBlocker) { return false; @@ -210,7 +210,7 @@ nsAsyncShutdownBarrier.prototype = { get client() { return this._client; }, - wait(onReady) { + wait: function(onReady) { this._moduleBarrier.wait().then(() => { onReady.done(); }); @@ -242,7 +242,7 @@ function nsAsyncShutdownService() { let k = _k; Object.defineProperty(this, k, { configurable: true, - get() { + get: function() { delete this[k]; let wrapped = AsyncShutdown[k]; // May be undefined, if we're on the wrong process. let result = wrapped ? new nsAsyncShutdownClient(wrapped) : undefined; @@ -260,7 +260,7 @@ function nsAsyncShutdownService() { }; } nsAsyncShutdownService.prototype = { - makeBarrier(name) { + makeBarrier: function(name) { return new nsAsyncShutdownBarrier(new AsyncShutdown.Barrier(name)); }, diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/head.js b/toolkit/components/asyncshutdown/tests/xpcshell/head.js index 735dea9fa5fc..9de489808d91 100644 --- a/toolkit/components/asyncshutdown/tests/xpcshell/head.js +++ b/toolkit/components/asyncshutdown/tests/xpcshell/head.js @@ -37,13 +37,13 @@ function makeLock(kind) { let topic = "test-Phase-" + ++makeLock.counter; let phase = AsyncShutdown._getPhase(topic); return { - addBlocker(...args) { + addBlocker: function(...args) { return phase.addBlocker(...args); }, - removeBlocker(blocker) { + removeBlocker: function(blocker) { return phase.removeBlocker(blocker); }, - wait() { + wait: function() { Services.obs.notifyObservers(null, topic, null); return Promise.resolve(); } @@ -54,7 +54,7 @@ function makeLock(kind) { return { addBlocker: barrier.client.addBlocker, removeBlocker: barrier.client.removeBlocker, - wait() { + wait: function() { return barrier.wait(); } }; @@ -62,7 +62,7 @@ function makeLock(kind) { let name = "test-xpcom-Barrier-" + ++makeLock.counter; let barrier = asyncShutdownService.makeBarrier(name); return { - addBlocker(blockerName, condition, state) { + addBlocker: function(blockerName, condition, state) { if (condition == null) { // Slight trick as `null` or `undefined` cannot be used as keys // for `xpcomMap`. Note that this has no incidence on the result @@ -74,8 +74,8 @@ function makeLock(kind) { if (!blocker) { blocker = { name: blockerName, - state, - blockShutdown(aBarrierClient) { + state: state, + blockShutdown: function(aBarrierClient) { return Task.spawn(function*() { try { if (typeof condition == "function") { @@ -94,14 +94,14 @@ function makeLock(kind) { let {fileName, lineNumber, stack} = (new Error()); return barrier.client.addBlocker(blocker, fileName, lineNumber, stack); }, - removeBlocker(condition) { + removeBlocker: function(condition) { let blocker = makeLock.xpcomMap.get(condition); if (!blocker) { return; } barrier.client.removeBlocker(blocker); }, - wait() { + wait: function() { return new Promise(resolve => { barrier.wait(resolve); }); @@ -114,7 +114,7 @@ function makeLock(kind) { return { addBlocker: client.addBlocker, removeBlocker: client.removeBlocker, - wait() { + wait: function() { return new Promise(resolve => { barrier.wait(resolve); }); diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js index 9df2425ba26a..33da1f53fbd4 100644 --- a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js +++ b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js @@ -27,7 +27,7 @@ add_task(function* test_phase_simple_async() { throw new Error("State BOOM"); }], [function() { return { - toJSON() { + toJSON: function() { throw new Error("State.toJSON BOOM"); } }; diff --git a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js index 581ca77a8d81..478f4d4d13f0 100644 --- a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js +++ b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js @@ -37,7 +37,7 @@ AutoCompleteInputBase.prototype = { get selectionEnd() { return this._selEnd; }, - selectTextRange(aStart, aEnd) { + selectTextRange: function(aStart, aEnd) { this._selStart = aStart; this._selEnd = aEnd; }, @@ -46,12 +46,12 @@ AutoCompleteInputBase.prototype = { return this.searches.length; }, - getSearchAt(aIndex) { + getSearchAt: function(aIndex) { return this.searches[aIndex]; }, - onSearchBegin() {}, - onSearchComplete() {}, + onSearchBegin: function() {}, + onSearchComplete: function() {}, popupOpen: false, @@ -89,31 +89,31 @@ AutoCompleteResultBase.prototype = { return this._values.length; }, - getValueAt(aIndex) { + getValueAt: function(aIndex) { return this._values[aIndex]; }, - getLabelAt(aIndex) { + getLabelAt: function(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt(aIndex) { + getCommentAt: function(aIndex) { return this._comments[aIndex]; }, - getStyleAt(aIndex) { + getStyleAt: function(aIndex) { return this._styles[aIndex]; }, - getImageAt(aIndex) { + getImageAt: function(aIndex) { return ""; }, - getFinalCompleteValueAt(aIndex) { + getFinalCompleteValueAt: function(aIndex) { return this._finalCompleteValues[aIndex] || this._values[aIndex]; }, - removeValueAt(aRowIndex, aRemoveFromDb) {}, + removeValueAt: function(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteResult]) @@ -135,7 +135,7 @@ AutoCompleteSearchBase.prototype = { // AutoCompleteResult _result: null, - startSearch(aSearchString, + startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) { @@ -145,14 +145,14 @@ AutoCompleteSearchBase.prototype = { aListener.onSearchResult(this, result); }, - stopSearch() {}, + stopSearch: function() {}, // nsISupports implementation QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory, Ci.nsIAutoCompleteSearch]), // nsIFactory implementation - createInstance(outer, iid) { + createInstance: function(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_330578.js b/toolkit/components/autocomplete/tests/unit/test_330578.js index 29b368269aab..c422dbb6a0c8 100644 --- a/toolkit/components/autocomplete/tests/unit/test_330578.js +++ b/toolkit/components/autocomplete/tests/unit/test_330578.js @@ -9,7 +9,7 @@ var gResultListener = { _lastValue: "", _lastRemoveFromDb: false, - onValueRemoved(aResult, aValue, aRemoveFromDb) { + onValueRemoved: function(aResult, aValue, aRemoveFromDb) { this._lastResult = aResult; this._lastValue = aValue; this._lastRemoveFromDb = aRemoveFromDb; diff --git a/toolkit/components/autocomplete/tests/unit/test_378079.js b/toolkit/components/autocomplete/tests/unit/test_378079.js index b5ac52e0ac80..b8b734884187 100644 --- a/toolkit/components/autocomplete/tests/unit/test_378079.js +++ b/toolkit/components/autocomplete/tests/unit/test_378079.js @@ -37,21 +37,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt(aIndex) { + getSearchAt: function(aIndex) { return this.searches[aIndex]; }, - onSearchBegin() {}, - onSearchComplete() {}, + onSearchBegin: function() {}, + onSearchComplete: function() {}, popupOpen: false, popup: { - setSelectedIndex(aIndex) {}, - invalidate() {}, + setSelectedIndex: function(aIndex) {}, + invalidate: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -61,7 +61,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -103,34 +103,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt(aIndex) { + getValueAt: function(aIndex) { return this._values[aIndex]; }, - getLabelAt(aIndex) { + getLabelAt: function(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt(aIndex) { + getCommentAt: function(aIndex) { return this._comments[aIndex]; }, - getStyleAt(aIndex) { + getStyleAt: function(aIndex) { return this._styles[aIndex]; }, - getImageAt(aIndex) { + getImageAt: function(aIndex) { return ""; }, - getFinalCompleteValueAt(aIndex) { + getFinalCompleteValueAt: function(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt(aRowIndex, aRemoveFromDb) {}, + removeValueAt: function(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -162,7 +162,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch(aSearchString, + startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch() {}, + stopSearch: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance(outer, iid) { + createInstance: function(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_393191.js b/toolkit/components/autocomplete/tests/unit/test_393191.js index ce32b4261787..750bcbd9abb4 100644 --- a/toolkit/components/autocomplete/tests/unit/test_393191.js +++ b/toolkit/components/autocomplete/tests/unit/test_393191.js @@ -36,21 +36,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt(aIndex) { + getSearchAt: function(aIndex) { return this.searches[aIndex]; }, - onSearchBegin() {}, - onSearchComplete() {}, + onSearchBegin: function() {}, + onSearchComplete: function() {}, popupOpen: false, popup: { - setSelectedIndex(aIndex) {}, - invalidate() {}, + setSelectedIndex: function(aIndex) {}, + invalidate: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -60,7 +60,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -102,34 +102,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt(aIndex) { + getValueAt: function(aIndex) { return this._values[aIndex]; }, - getLabelAt(aIndex) { + getLabelAt: function(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt(aIndex) { + getCommentAt: function(aIndex) { return this._comments[aIndex]; }, - getStyleAt(aIndex) { + getStyleAt: function(aIndex) { return this._styles[aIndex]; }, - getImageAt(aIndex) { + getImageAt: function(aIndex) { return ""; }, - getFinalCompleteValueAt(aIndex) { + getFinalCompleteValueAt: function(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt(aRowIndex, aRemoveFromDb) {}, + removeValueAt: function(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -161,7 +161,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch(aSearchString, + startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -169,10 +169,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch() {}, + stopSearch: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -182,7 +182,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance(outer, iid) { + createInstance: function(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_440866.js b/toolkit/components/autocomplete/tests/unit/test_440866.js index 558ac78b7d29..e42dd8831c90 100644 --- a/toolkit/components/autocomplete/tests/unit/test_440866.js +++ b/toolkit/components/autocomplete/tests/unit/test_440866.js @@ -35,21 +35,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt(aIndex) { + getSearchAt: function(aIndex) { return this.searches[aIndex]; }, - onSearchBegin() {}, - onSearchComplete() {}, + onSearchBegin: function() {}, + onSearchComplete: function() {}, popupOpen: false, popup: { - setSelectedIndex(aIndex) {}, - invalidate() {}, + setSelectedIndex: function(aIndex) {}, + invalidate: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -59,7 +59,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -101,34 +101,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt(aIndex) { + getValueAt: function(aIndex) { return this._values[aIndex]; }, - getLabelAt(aIndex) { + getLabelAt: function(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt(aIndex) { + getCommentAt: function(aIndex) { return this._comments[aIndex]; }, - getStyleAt(aIndex) { + getStyleAt: function(aIndex) { return this._styles[aIndex]; }, - getImageAt(aIndex) { + getImageAt: function(aIndex) { return ""; }, - getFinalCompleteValueAt(aIndex) { + getFinalCompleteValueAt: function(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt(aRowIndex, aRemoveFromDb) {}, + removeValueAt: function(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -160,7 +160,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch(aSearchString, + startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -168,10 +168,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch() {}, + stopSearch: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -181,7 +181,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance(outer, iid) { + createInstance: function(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js index 6186df34d8f4..15274140fcd4 100644 --- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js +++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js @@ -30,21 +30,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt(aIndex) { + getSearchAt: function(aIndex) { return this.searches[aIndex]; }, - onSearchBegin() {}, - onSearchComplete() {}, + onSearchBegin: function() {}, + onSearchComplete: function() {}, popupOpen: false, popup: { - setSelectedIndex(aIndex) {}, - invalidate() {}, + setSelectedIndex: function(aIndex) {}, + invalidate: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -54,7 +54,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -90,34 +90,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt(aIndex) { + getValueAt: function(aIndex) { return this._values[aIndex]; }, - getLabelAt(aIndex) { + getLabelAt: function(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt(aIndex) { + getCommentAt: function(aIndex) { return this._comments[aIndex]; }, - getStyleAt(aIndex) { + getStyleAt: function(aIndex) { return this._styles[aIndex]; }, - getImageAt(aIndex) { + getImageAt: function(aIndex) { return ""; }, - getFinalCompleteValueAt(aIndex) { + getFinalCompleteValueAt: function(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt(aRowIndex, aRemoveFromDb) {}, + removeValueAt: function(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -149,7 +149,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch(aSearchString, + startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, result); }, - stopSearch() {}, + stopSearch: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance(outer, iid) { + createInstance: function(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_previousResult.js b/toolkit/components/autocomplete/tests/unit/test_previousResult.js index 0367f782de14..a9c6da31a4b2 100644 --- a/toolkit/components/autocomplete/tests/unit/test_previousResult.js +++ b/toolkit/components/autocomplete/tests/unit/test_previousResult.js @@ -36,21 +36,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt(aIndex) { + getSearchAt: function(aIndex) { return this.searches[aIndex]; }, - onSearchBegin() {}, - onSearchComplete() {}, + onSearchBegin: function() {}, + onSearchComplete: function() {}, popupOpen: false, popup: { - setSelectedIndex(aIndex) {}, - invalidate() {}, + setSelectedIndex: function(aIndex) {}, + invalidate: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -60,7 +60,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -101,34 +101,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt(aIndex) { + getValueAt: function(aIndex) { return this._values[aIndex]; }, - getLabelAt(aIndex) { + getLabelAt: function(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt(aIndex) { + getCommentAt: function(aIndex) { return this._comments[aIndex]; }, - getStyleAt(aIndex) { + getStyleAt: function(aIndex) { return this._styles[aIndex]; }, - getImageAt(aIndex) { + getImageAt: function(aIndex) { return ""; }, - getFinalCompleteValueAt(aIndex) { + getFinalCompleteValueAt: function(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt(aRowIndex, aRemoveFromDb) {}, + removeValueAt: function(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -161,7 +161,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch(aSearchString, + startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch() {}, + stopSearch: function() {}, // nsISupports implementation - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance(outer, iid) { + createInstance: function(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js index 4ef0294b73bc..0972092bb63e 100644 --- a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js +++ b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js @@ -32,14 +32,14 @@ AutoCompleteInput.prototype = { set popupOpen(val) { return val; }, // ignore get popupOpen() { return false; }, get searchCount() { return this.searches.length; }, - getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin() {}, - onSearchComplete() {}, - onTextReverted() {}, - onTextEntered() {}, + getSearchAt: function(aIndex) { return this.searches[aIndex]; }, + onSearchBegin: function() {}, + onSearchComplete: function() {}, + onTextReverted: function() {}, + onTextEntered: function() {}, popup: { - selectBy() {}, - invalidate() {}, + selectBy: function() {}, + invalidate: function() {}, set selectedIndex(val) { return val; }, // ignore get selectedIndex() { return -1 }, QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup]) @@ -58,13 +58,13 @@ function AutoCompleteSearch(aName) AutoCompleteSearch.prototype = { constructor: AutoCompleteSearch, stopSearchInvoked: true, - startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) + startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) { print("Check stop search has been called"); do_check_true(this.stopSearchInvoked); this.stopSearchInvoked = false; }, - stopSearch() + stopSearch: function() { this.stopSearchInvoked = true; }, @@ -72,7 +72,7 @@ AutoCompleteSearch.prototype = { Ci.nsIFactory , Ci.nsIAutoCompleteSearch ]), - createInstance(outer, iid) + createInstance: function(outer, iid) { return this.QueryInterface(iid); } diff --git a/toolkit/components/captivedetect/captivedetect.js b/toolkit/components/captivedetect/captivedetect.js index 4362f8e790d7..f347736b39aa 100644 --- a/toolkit/components/captivedetect/captivedetect.js +++ b/toolkit/components/captivedetect/captivedetect.js @@ -66,9 +66,9 @@ function URLFetcher(url, timeout) { URLFetcher.prototype = { _isAborted: false, - ontimeout() {}, - onerror() {}, - abort() { + ontimeout: function() {}, + onerror: function() {}, + abort: function() { if (!this._isAborted) { this._isAborted = true; this._xhr.abort(); @@ -339,7 +339,7 @@ CaptivePortalDetector.prototype = { let id = this._allocateRequestId(); let details = { type: kOpenCaptivePortalLoginEvent, - id, + id: id, url: this._canonicalSiteURL, }; this._loginObserver.attach(); diff --git a/toolkit/components/contentprefs/ContentPrefService2.jsm b/toolkit/components/contentprefs/ContentPrefService2.jsm index 69180fe13101..5d4287897024 100644 --- a/toolkit/components/contentprefs/ContentPrefService2.jsm +++ b/toolkit/components/contentprefs/ContentPrefService2.jsm @@ -418,7 +418,7 @@ ContentPrefService2.prototype = { }, // Deletes settings and groups that are no longer used. - _settingsAndGroupsCleanupStmts() { + _settingsAndGroupsCleanupStmts: function() { // The NOTNULL term in the subquery of the second statment is needed because of // SQLite's weird IN behavior vis-a-vis NULLs. See http://sqlite.org/lang_expr.html. return [ diff --git a/toolkit/components/contentprefs/ContentPrefServiceChild.jsm b/toolkit/components/contentprefs/ContentPrefServiceChild.jsm index cad1c71caf67..ea1f969dfd64 100644 --- a/toolkit/components/contentprefs/ContentPrefServiceChild.jsm +++ b/toolkit/components/contentprefs/ContentPrefServiceChild.jsm @@ -31,18 +31,18 @@ function CallbackCaller(callback) { } CallbackCaller.prototype = { - handleResult(contentPref) { + handleResult: function(contentPref) { cbHandleResult(this._callback, new ContentPref(contentPref.domain, contentPref.name, contentPref.value)); }, - handleError(result) { + handleError: function(result) { cbHandleError(this._callback, result); }, - handleCompletion(reason) { + handleCompletion: function(reason) { cbHandleCompletion(this._callback, reason); }, }; @@ -56,7 +56,7 @@ var ContentPrefServiceChild = { _mm: Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsIMessageSender), - _getRandomId() { + _getRandomId: function() { return Cc["@mozilla.org/uuid-generator;1"] .getService(Ci.nsIUUIDGenerator).generateUUID().toString(); }, @@ -64,13 +64,13 @@ var ContentPrefServiceChild = { // Map from random ID string -> CallbackCaller, per request _requests: new Map(), - init() { + init: function() { this._mm.addMessageListener("ContentPrefs:HandleResult", this); this._mm.addMessageListener("ContentPrefs:HandleError", this); this._mm.addMessageListener("ContentPrefs:HandleCompletion", this); }, - receiveMessage(msg) { + receiveMessage: function(msg) { let data = msg.data; let callback; switch (msg.name) { @@ -104,34 +104,34 @@ var ContentPrefServiceChild = { } }, - _callFunction(call, args, callback) { + _callFunction: function(call, args, callback) { let requestId = this._getRandomId(); - let data = { call, args, requestId }; + let data = { call: call, args: args, requestId: requestId }; this._mm.sendAsyncMessage("ContentPrefs:FunctionCall", data); this._requests.set(requestId, new CallbackCaller(callback)); }, - getByName(name, context, callback) { + getByName: function(name, context, callback) { return this._callFunction("getByName", [ name, contextArg(context) ], callback); }, - getByDomainAndName(domain, name, context, callback) { + getByDomainAndName: function(domain, name, context, callback) { return this._callFunction("getByDomainAndName", [ domain, name, contextArg(context) ], callback); }, - getBySubdomainAndName(domain, name, context, callback) { + getBySubdomainAndName: function(domain, name, context, callback) { return this._callFunction("getBySubdomainAndName", [ domain, name, contextArg(context) ], callback); }, - getGlobal(name, context, callback) { + getGlobal: function(name, context, callback) { return this._callFunction("getGlobal", [ name, contextArg(context) ], callback); @@ -141,59 +141,59 @@ var ContentPrefServiceChild = { getCachedBySubdomainAndName: NYI, getCachedGlobal: NYI, - set(domain, name, value, context, callback) { + set: function(domain, name, value, context, callback) { this._callFunction("set", [ domain, name, value, contextArg(context) ], callback); }, - setGlobal(name, value, context, callback) { + setGlobal: function(name, value, context, callback) { this._callFunction("setGlobal", [ name, value, contextArg(context) ], callback); }, - removeByDomainAndName(domain, name, context, callback) { + removeByDomainAndName: function(domain, name, context, callback) { this._callFunction("removeByDomainAndName", [ domain, name, contextArg(context) ], callback); }, - removeBySubdomainAndName(domain, name, context, callback) { + removeBySubdomainAndName: function(domain, name, context, callback) { this._callFunction("removeBySubdomainAndName", [ domain, name, contextArg(context) ], callback); }, - removeGlobal(name, context, callback) { + removeGlobal: function(name, context, callback) { this._callFunction("removeGlobal", [ name, contextArg(context) ], callback); }, - removeByDomain(domain, context, callback) { + removeByDomain: function(domain, context, callback) { this._callFunction("removeByDomain", [ domain, contextArg(context) ], callback); }, - removeBySubdomain(domain, context, callback) { + removeBySubdomain: function(domain, context, callback) { this._callFunction("removeBySubdomain", [ domain, contextArg(context) ], callback); }, - removeByName(name, context, callback) { + removeByName: function(name, context, callback) { this._callFunction("removeByName", [ name, value, contextArg(context) ], callback); }, - removeAllDomains(context, callback) { + removeAllDomains: function(context, callback) { this._callFunction("removeAllDomains", [ contextArg(context) ], callback); }, - removeAllGlobals(context, callback) { + removeAllGlobals: function(context, callback) { this._callFunction("removeAllGlobals", [ contextArg(context) ], callback); }, - addObserverForName(name, observer) { + addObserverForName: function(name, observer) { let set = this._observers.get(name); if (!set) { set = new Set(); @@ -204,14 +204,14 @@ var ContentPrefServiceChild = { // This is the first observer for this name. Start listening for changes // to it. - this._mm.sendAsyncMessage("ContentPrefs:AddObserverForName", { name }); + this._mm.sendAsyncMessage("ContentPrefs:AddObserverForName", { name: name }); this._observers.set(name, set); } set.add(observer); }, - removeObserverForName(name, observer) { + removeObserverForName: function(name, observer) { let set = this._observers.get(name); if (!set) return; @@ -219,7 +219,7 @@ var ContentPrefServiceChild = { set.delete(observer); if (set.size === 0) { // This was the last observer for this name. Stop listening for changes. - this._mm.sendAsyncMessage("ContentPrefs:RemoveObserverForName", { name }); + this._mm.sendAsyncMessage("ContentPrefs:RemoveObserverForName", { name: name }); this._observers.delete(name); if (this._observers.size === 0) { diff --git a/toolkit/components/contentprefs/ContentPrefServiceParent.jsm b/toolkit/components/contentprefs/ContentPrefServiceParent.jsm index e0cb15e58491..f4b02f018ace 100644 --- a/toolkit/components/contentprefs/ContentPrefServiceParent.jsm +++ b/toolkit/components/contentprefs/ContentPrefServiceParent.jsm @@ -14,7 +14,7 @@ const Cu = Components.utils; var ContentPrefServiceParent = { _cps2: null, - init() { + init: function() { let globalMM = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageListenerManager); @@ -32,7 +32,7 @@ var ContentPrefServiceParent = { // Map from message manager -> content pref observer. _observers: new Map(), - handleObserverChange(msg) { + handleObserverChange: function(msg) { let observer = this._observers.get(msg.target); if (msg.name === "child-process-shutdown") { // If we didn't have any observers for this child process, don't do @@ -54,15 +54,15 @@ var ContentPrefServiceParent = { // observers for the same name. if (!observer) { observer = { - onContentPrefSet(group, name, value, isPrivate) { + onContentPrefSet: function(group, name, value, isPrivate) { msg.target.sendAsyncMessage("ContentPrefs:NotifyObservers", - { name, callback: "onContentPrefSet", + { name: name, callback: "onContentPrefSet", args: [ group, name, value, isPrivate ] }); }, - onContentPrefRemoved(group, name, isPrivate) { + onContentPrefRemoved: function(group, name, isPrivate) { msg.target.sendAsyncMessage("ContentPrefs:NotifyObservers", - { name, callback: "onContentPrefRemoved", + { name: name, callback: "onContentPrefRemoved", args: [ group, name, isPrivate ] }); }, @@ -92,16 +92,16 @@ var ContentPrefServiceParent = { } }, - receiveMessage(msg) { + receiveMessage: function(msg) { let data = msg.data; let args = data.args; let requestId = data.requestId; let listener = { - handleResult(pref) { + handleResult: function(pref) { msg.target.sendAsyncMessage("ContentPrefs:HandleResult", - { requestId, + { requestId: requestId, contentPref: { domain: pref.domain, name: pref.name, @@ -110,15 +110,15 @@ var ContentPrefServiceParent = { }); }, - handleError(error) { + handleError: function(error) { msg.target.sendAsyncMessage("ContentPrefs:HandleError", - { requestId, - error }); + { requestId: requestId, + error: error }); }, - handleCompletion(reason) { + handleCompletion: function(reason) { msg.target.sendAsyncMessage("ContentPrefs:HandleCompletion", - { requestId, - reason }); + { requestId: requestId, + reason: reason }); } }; diff --git a/toolkit/components/contentprefs/nsContentPrefService.js b/toolkit/components/contentprefs/nsContentPrefService.js index 8e92432e9f2c..4f5726e6ea44 100644 --- a/toolkit/components/contentprefs/nsContentPrefService.js +++ b/toolkit/components/contentprefs/nsContentPrefService.js @@ -580,7 +580,7 @@ ContentPrefService.prototype = { return this.__stmtSelectPref; }, - _scheduleCallback(func) { + _scheduleCallback: function(func) { let tm = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); tm.mainThread.dispatch(func, Ci.nsIThread.DISPATCH_NORMAL); }, @@ -602,7 +602,7 @@ ContentPrefService.prototype = { if (aCallback) { let cache = this._cache; - new AsyncStatement(this._stmtSelectPref).execute({onResult(aResult) { + new AsyncStatement(this._stmtSelectPref).execute({onResult: function(aResult) { cache.set(aGroup, aSetting, aResult); aCallback.onResult(aResult); }}); @@ -651,7 +651,7 @@ ContentPrefService.prototype = { if (aCallback) { let cache = this._cache; - new AsyncStatement(this._stmtSelectGlobalPref).execute({onResult(aResult) { + new AsyncStatement(this._stmtSelectGlobalPref).execute({onResult: function(aResult) { cache.set(null, aName, aResult); aCallback.onResult(aResult); }}); @@ -1309,19 +1309,19 @@ AsyncStatement.prototype = { stmt.executeAsync({ _callback: aCallback, _hadResult: false, - handleResult(aResult) { + handleResult: function(aResult) { this._hadResult = true; if (this._callback) { let row = aResult.getNextRow(); this._callback.onResult(row.getResultByName("value")); } }, - handleCompletion(aReason) { + handleCompletion: function(aReason) { if (!this._hadResult && this._callback && aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) this._callback.onResult(undefined); }, - handleError(aError) {} + handleError: function(aError) {} }); } }; diff --git a/toolkit/components/contentprefs/tests/unit/test_bug679784.js b/toolkit/components/contentprefs/tests/unit/test_bug679784.js index 123c8712acb7..97251d87ba9c 100644 --- a/toolkit/components/contentprefs/tests/unit/test_bug679784.js +++ b/toolkit/components/contentprefs/tests/unit/test_bug679784.js @@ -5,11 +5,11 @@ var prefObserver = { setCalledNum: 0, - onContentPrefSet(aGroup, aName, aValue) { + onContentPrefSet: function(aGroup, aName, aValue) { this.setCalledNum++; }, removedCalledNum: 0, - onContentPrefRemoved(aGroup, aName) { + onContentPrefRemoved: function(aGroup, aName) { this.removedCalledNum++; } }; diff --git a/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js b/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js index 826619ed740d..27d239f793f5 100644 --- a/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js +++ b/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js @@ -18,7 +18,7 @@ function run_test() { function testCallbackObj() { cps.getPref(uri, "asynctest", { - onResult(aValue) { + onResult: function(aValue) { do_check_eq(aValue, "pie"); cps.removePref(uri, "asynctest"); testNoResult(); diff --git a/toolkit/components/contentprefs/tests/unit_cps2/head.js b/toolkit/components/contentprefs/tests/unit_cps2/head.js index 50cc9ae37622..6ce75d997753 100644 --- a/toolkit/components/contentprefs/tests/unit_cps2/head.js +++ b/toolkit/components/contentprefs/tests/unit_cps2/head.js @@ -25,7 +25,7 @@ function runAsyncTests(tests, dontResetBefore = false) { Cu.import("resource://test/AsyncRunner.jsm", s); asyncRunner = new s.AsyncRunner({ done: do_test_finished, - error(err) { + error: function(err) { // xpcshell test functions like equal throw NS_ERROR_ABORT on // failure. Ignore those and catch only uncaught exceptions. if (err !== Cr.NS_ERROR_ABORT) { @@ -36,7 +36,7 @@ function runAsyncTests(tests, dontResetBefore = false) { do_throw(err); } }, - consoleError(scriptErr) { + consoleError: function(scriptErr) { // Previously, this code checked for console errors related to the test, // and treated them as failures. This was problematic, because our current // very-broken exception reporting machinery in XPCWrappedJSClass reports @@ -138,10 +138,10 @@ function setWithDate(group, name, val, timestamp, context) { stmt.params.group = group; stmt.executeAsync({ - handleCompletion(reason) { + handleCompletion: function(reason) { next(); }, - handleError(err) { + handleError: function(err) { do_throw(err); } }); @@ -164,14 +164,14 @@ function getDate(group, name, context) { let res; stmt.executeAsync({ - handleResult(results) { + handleResult: function(results) { let row = results.getNextRow(); res = row.getResultByName("timestamp"); }, - handleCompletion(reason) { + handleCompletion: function(reason) { next(res * 1000); }, - handleError(err) { + handleError: function(err) { do_throw(err); } }); @@ -336,17 +336,17 @@ function dbOK(expectedRows) { let cols = ["grp", "name", "value"]; db.executeAsync([stmt], 1, { - handleCompletion(reason) { + handleCompletion: function(reason) { arraysOfArraysOK(actualRows, expectedRows); next(); }, - handleResult(results) { + handleResult: function(results) { let row = null; while (row = results.getNextRow()) { actualRows.push(cols.map(c => row.getResultByName(c))); } }, - handleError(err) { + handleError: function(err) { do_throw(err); } }); @@ -355,7 +355,7 @@ function dbOK(expectedRows) { function on(event, names, dontRemove) { let args = { - reset() { + reset: function() { for (let prop in this) { if (Array.isArray(this[prop])) this[prop].splice(0, this[prop].length); diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js b/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js index 546ff0b2bd2b..0fdc3b7adf32 100644 --- a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js +++ b/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js @@ -143,7 +143,7 @@ var tests = [ // (3) Set the pref to a new value but don't wait for it to finish. cps.set("a.com", "foo", 2, null, { - handleCompletion() { + handleCompletion: function() { // (6) The pref should be cached after setting it. getCachedOK(["a.com", "foo"], true, 2); }, @@ -155,10 +155,10 @@ var tests = [ // (5) Call getByDomainAndName. var fetchedPref; cps.getByDomainAndName("a.com", "foo", null, { - handleResult(pref) { + handleResult: function(pref) { fetchedPref = pref; }, - handleCompletion() { + handleCompletion: function() { // (7) Finally, this callback should be called after set's above. do_check_true(!!fetchedPref); do_check_eq(fetchedPref.value, 2); diff --git a/toolkit/components/crashes/CrashManager.jsm b/toolkit/components/crashes/CrashManager.jsm index 65216391c8d8..1df8ed739db9 100644 --- a/toolkit/components/crashes/CrashManager.jsm +++ b/toolkit/components/crashes/CrashManager.jsm @@ -262,7 +262,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return Promise */ - pendingDumps() { + pendingDumps: function() { return this._getDirectoryEntries(this._pendingDumpsDir, this.DUMP_REGEX); }, @@ -286,7 +286,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return Promise */ - submittedDumps() { + submittedDumps: function() { return this._getDirectoryEntries(this._submittedDumpsDir, this.SUBMITTED_REGEX); }, @@ -306,7 +306,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return promise The number of event files that were examined. */ - aggregateEventsFiles() { + aggregateEventsFiles: function() { if (this._aggregatePromise) { return this._aggregatePromise; } @@ -389,7 +389,7 @@ this.CrashManager.prototype = Object.freeze({ * (Date) The cutoff point for pruning. Crashes without data newer * than this will be pruned. */ - pruneOldCrashes(date) { + pruneOldCrashes: function(date) { return Task.spawn(function* () { let store = yield this._getStore(); store.pruneOldCrashes(date); @@ -400,7 +400,7 @@ this.CrashManager.prototype = Object.freeze({ /** * Run tasks that should be periodically performed. */ - runMaintenanceTasks() { + runMaintenanceTasks: function() { return Task.spawn(function* () { yield this.aggregateEventsFiles(); @@ -415,7 +415,7 @@ this.CrashManager.prototype = Object.freeze({ * @param delay * (integer) Delay in milliseconds when maintenance should occur. */ - scheduleMaintenance(delay) { + scheduleMaintenance: function(delay) { let deferred = PromiseUtils.defer(); setTimeout(() => { @@ -439,7 +439,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return promise Resolved when the store has been saved. */ - addCrash(processType, crashType, id, date, metadata) { + addCrash: function(processType, crashType, id, date, metadata) { let promise = Task.spawn(function* () { let store = yield this._getStore(); if (store.addCrash(processType, crashType, id, date, metadata)) { @@ -561,7 +561,7 @@ this.CrashManager.prototype = Object.freeze({ * * The promise-resolved array is sorted by file mtime, oldest to newest. */ - _getUnprocessedEventsFiles() { + _getUnprocessedEventsFiles: function() { return Task.spawn(function* () { let entries = []; @@ -578,7 +578,7 @@ this.CrashManager.prototype = Object.freeze({ }, // See docs/crash-events.rst for the file format specification. - _processEventFile(entry) { + _processEventFile: function(entry) { return Task.spawn(function* () { let data = yield OS.File.read(entry.path); let store = yield this._getStore(); @@ -617,7 +617,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - _filterAnnotations(annotations) { + _filterAnnotations: function(annotations) { let filteredAnnotations = {}; for (let line in annotations) { @@ -629,7 +629,7 @@ this.CrashManager.prototype = Object.freeze({ return filteredAnnotations; }, - _sendCrashPing(crashId, type, date, metadata = {}) { + _sendCrashPing: function(crashId, type, date, metadata = {}) { // If we have a saved environment, use it. Otherwise report // the current environment. let reportMeta = Cu.cloneInto(metadata, myScope); @@ -646,10 +646,10 @@ this.CrashManager.prototype = Object.freeze({ { version: 1, crashDate: date.toISOString().slice(0, 10), // YYYY-MM-DD - sessionId, - crashId, + sessionId: sessionId, + crashId: crashId, processType: type, - stackTraces, + stackTraces: stackTraces, metadata: reportMeta, hasCrashEnvironment: (crashEnvironment !== null), }, @@ -662,7 +662,7 @@ this.CrashManager.prototype = Object.freeze({ ); }, - _handleEventFilePayload(store, entry, type, date, payload) { + _handleEventFilePayload: function(store, entry, type, date, payload) { // The payload types and formats are documented in docs/crash-events.rst. // Do not change the format of an existing type. Instead, invent a new // type. @@ -720,7 +720,7 @@ this.CrashManager.prototype = Object.freeze({ * id -- regexp.match()[1] (likely the crash ID) * date -- Date mtime of the file */ - _getDirectoryEntries(path, re) { + _getDirectoryEntries: function(path, re) { return Task.spawn(function* () { try { yield OS.File.stat(path); @@ -763,7 +763,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - _getStore() { + _getStore: function() { if (this._getStoreTask) { return this._getStoreTask; } @@ -823,7 +823,7 @@ this.CrashManager.prototype = Object.freeze({ * * Returns an array of CrashRecord instances. Instances are read-only. */ - getCrashes() { + getCrashes: function() { return Task.spawn(function* () { let store = yield this._getStore(); @@ -831,7 +831,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - getCrashCountsByDay() { + getCrashCountsByDay: function() { return Task.spawn(function* () { let store = yield this._getStore(); @@ -908,7 +908,7 @@ CrashStore.prototype = Object.freeze({ * * @return Promise */ - load() { + load: function() { return Task.spawn(function* () { // Loading replaces data. this.reset(); @@ -1008,7 +1008,7 @@ CrashStore.prototype = Object.freeze({ * * @return Promise */ - save() { + save: function() { return Task.spawn(function* () { if (!this._data) { return; @@ -1078,7 +1078,7 @@ CrashStore.prototype = Object.freeze({ * We convert these to milliseconds since epoch on output and back to * Date on input. */ - _normalize(o) { + _normalize: function(o) { let normalized = {}; for (let k in o) { @@ -1096,7 +1096,7 @@ CrashStore.prototype = Object.freeze({ /** * Convert a serialized object back to its native form. */ - _denormalize(o) { + _denormalize: function(o) { let n = {}; for (let k in o) { @@ -1122,7 +1122,7 @@ CrashStore.prototype = Object.freeze({ * (Date) The cutoff at which data will be pruned. If an entry * doesn't have data newer than this, it will be pruned. */ - pruneOldCrashes(date) { + pruneOldCrashes: function(date) { for (let crash of this.crashes) { let newest = crash.newestDate; if (!newest || newest.getTime() < date.getTime()) { @@ -1167,7 +1167,7 @@ CrashStore.prototype = Object.freeze({ * A CrashRecord will be returned if the crash exists. null will be returned * if the crash is unknown. */ - getCrash(id) { + getCrash: function(id) { for (let crash of this.crashes) { if (crash.id == id) { return crash; @@ -1177,7 +1177,7 @@ CrashStore.prototype = Object.freeze({ return null; }, - _ensureCountsForDay(day) { + _ensureCountsForDay: function(day) { if (!this._countsByDay.has(day)) { this._countsByDay.set(day, new Map()); } @@ -1202,7 +1202,7 @@ CrashStore.prototype = Object.freeze({ * * @return null | object crash record */ - _ensureCrashRecord(processType, crashType, id, date, metadata) { + _ensureCrashRecord: function(processType, crashType, id, date, metadata) { if (!id) { // Crashes are keyed on ID, so it's not really helpful to store crashes // without IDs. @@ -1232,13 +1232,13 @@ CrashStore.prototype = Object.freeze({ } this._data.crashes.set(id, { - id, + id: id, remoteID: null, - type, + type: type, crashDate: date, submissions: new Map(), classifications: [], - metadata, + metadata: metadata, }); } @@ -1260,14 +1260,14 @@ CrashStore.prototype = Object.freeze({ * * @return boolean True if the crash was recorded and false if not. */ - addCrash(processType, crashType, id, date, metadata) { + addCrash: function(processType, crashType, id, date, metadata) { return !!this._ensureCrashRecord(processType, crashType, id, date, metadata); }, /** * @return boolean True if the remote ID was recorded and false if not. */ - setRemoteCrashID(crashID, remoteID) { + setRemoteCrashID: function(crashID, remoteID) { let crash = this._data.crashes.get(crashID); if (!crash || !remoteID) { return false; @@ -1277,7 +1277,7 @@ CrashStore.prototype = Object.freeze({ return true; }, - getCrashesOfType(processType, crashType) { + getCrashesOfType: function(processType, crashType) { let crashes = []; for (let crash of this.crashes) { if (crash.isOfType(processType, crashType)) { @@ -1292,7 +1292,7 @@ CrashStore.prototype = Object.freeze({ * Ensure the submission record is present in storage. * @returns [submission, crash] */ - _ensureSubmissionRecord(crashID, submissionID) { + _ensureSubmissionRecord: function(crashID, submissionID) { let crash = this._data.crashes.get(crashID); if (!crash || !submissionID) { return null; @@ -1312,7 +1312,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the attempt was recorded. */ - addSubmissionAttempt(crashID, submissionID, date) { + addSubmissionAttempt: function(crashID, submissionID, date) { let [submission, crash] = this._ensureSubmissionRecord(crashID, submissionID); if (!submission) { @@ -1328,7 +1328,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the response was recorded. */ - addSubmissionResult(crashID, submissionID, date, result) { + addSubmissionResult: function(crashID, submissionID, date, result) { let crash = this._data.crashes.get(crashID); if (!crash || !submissionID) { return false; @@ -1348,7 +1348,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the classifications were set. */ - setCrashClassifications(crashID, classifications) { + setCrashClassifications: function(crashID, classifications) { let crash = this._data.crashes.get(crashID); if (!crash) { return false; @@ -1407,7 +1407,7 @@ CrashRecord.prototype = Object.freeze({ return this._o.type; }, - isOfType(processType, crashType) { + isOfType: function(processType, crashType) { return processType + "-" + crashType == this.type; }, diff --git a/toolkit/components/crashes/CrashManagerTest.jsm b/toolkit/components/crashes/CrashManagerTest.jsm index f7fa11d8e0cf..e55da45468fd 100644 --- a/toolkit/components/crashes/CrashManagerTest.jsm +++ b/toolkit/components/crashes/CrashManagerTest.jsm @@ -57,7 +57,7 @@ this.TestingCrashManager = function(options) { this.TestingCrashManager.prototype = { __proto__: CrashManager.prototype, - createDummyDump(submitted = false, date = new Date(), hr = false) { + createDummyDump: function(submitted = false, date = new Date(), hr = false) { let uuid = Cc["@mozilla.org/uuid-generator;1"] .getService(Ci.nsIUUIDGenerator) .generateUUID() @@ -89,7 +89,7 @@ this.TestingCrashManager.prototype = { }); }, - createIgnoredDumpFile(filename, submitted = false) { + createIgnoredDumpFile: function(filename, submitted = false) { let path; if (submitted) { path = OS.Path.join(this._submittedDumpsDir, filename); @@ -104,7 +104,7 @@ this.TestingCrashManager.prototype = { }); }, - createEventsFile(filename, type, date, content, index = 0) { + createEventsFile: function(filename, type, date, content, index = 0) { let path = OS.Path.join(this._eventsDirs[index], filename); let data = type + "\n" + @@ -124,7 +124,7 @@ this.TestingCrashManager.prototype = { * * We can probably delete this once we have actual events defined. */ - _handleEventFilePayload(store, entry, type, date, payload) { + _handleEventFilePayload: function(store, entry, type, date, payload) { if (type == "test.1") { if (payload == "malformed") { return this.EVENT_FILE_ERROR_MALFORMED; diff --git a/toolkit/components/crashes/CrashService.js b/toolkit/components/crashes/CrashService.js index 76713524b81b..72f804fc079d 100644 --- a/toolkit/components/crashes/CrashService.js +++ b/toolkit/components/crashes/CrashService.js @@ -57,7 +57,7 @@ CrashService.prototype = Object.freeze({ Ci.nsIObserver, ]), - addCrash(processType, crashType, id) { + addCrash: function(processType, crashType, id) { switch (processType) { case Ci.nsICrashService.PROCESS_TYPE_MAIN: processType = Services.crashmanager.PROCESS_TYPE_MAIN; @@ -98,7 +98,7 @@ CrashService.prototype = Object.freeze({ ); }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case "profile-after-change": // Side-effect is the singleton is instantiated. diff --git a/toolkit/components/crashmonitor/CrashMonitor.jsm b/toolkit/components/crashmonitor/CrashMonitor.jsm index 2ee173527507..6540d516fc2b 100644 --- a/toolkit/components/crashmonitor/CrashMonitor.jsm +++ b/toolkit/components/crashmonitor/CrashMonitor.jsm @@ -93,7 +93,7 @@ var CrashMonitorInternal = { * * @return {Promise} A promise that resolves/rejects once loading is complete */ - loadPreviousCheckpoints() { + loadPreviousCheckpoints: function() { this.previousCheckpoints = Task.spawn(function*() { let data; try { @@ -155,7 +155,7 @@ this.CrashMonitor = { * * @return {Promise} */ - init() { + init: function() { if (CrashMonitorInternal.initialized) { throw new Error("CrashMonitor.init() must only be called once!"); } @@ -185,7 +185,7 @@ this.CrashMonitor = { * * Update checkpoint file for every new notification received. */ - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { if (!(aTopic in CrashMonitorInternal.checkpoints)) { // If this is the first time this notification is received, // remember it and write it to file diff --git a/toolkit/components/crashmonitor/nsCrashMonitor.js b/toolkit/components/crashmonitor/nsCrashMonitor.js index d53fecd6d067..fe29a9c8eaea 100644 --- a/toolkit/components/crashmonitor/nsCrashMonitor.js +++ b/toolkit/components/crashmonitor/nsCrashMonitor.js @@ -18,7 +18,7 @@ CrashMonitor.prototype = { QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]), - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { switch (aTopic) { case "profile-after-change": MonitorAPI.init(); diff --git a/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js b/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js index 7163e2755415..eec85025b5c5 100644 --- a/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js +++ b/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js @@ -13,7 +13,7 @@ var Components = { caller: null }, utils: { - import() { } + import: function() { } } }; @@ -72,7 +72,7 @@ FileFaker.prototype = { this._path = this._path.substring(0, lastSlash); return this; }, - append(leaf) { + append: function(leaf) { this._path = this._path + "/" + leaf; } }; diff --git a/toolkit/components/ctypes/tests/unit/head.js b/toolkit/components/ctypes/tests/unit/head.js index e2c2ea4683c0..4e51b22a2ab5 100644 --- a/toolkit/components/ctypes/tests/unit/head.js +++ b/toolkit/components/ctypes/tests/unit/head.js @@ -44,7 +44,7 @@ function ResourceTester(start, stop) { this._stop = stop; } ResourceTester.prototype = { - launch(size, test, args) { + launch: function(size, test, args) { trigger_gc(); let cleaner = new ResourceCleaner(); this._start(size); diff --git a/toolkit/components/ctypes/tests/unit/test_finalizer.js b/toolkit/components/ctypes/tests/unit/test_finalizer.js index d19c82eed1fc..d50437da6eb5 100644 --- a/toolkit/components/ctypes/tests/unit/test_finalizer.js +++ b/toolkit/components/ctypes/tests/unit/test_finalizer.js @@ -34,8 +34,8 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status, - released + status: status, + released: released }); samples.push( { @@ -53,8 +53,8 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status, - released + status: status, + released: released }); samples.push( { @@ -72,8 +72,8 @@ function run_test() ctypes.bool, ctypes.int32_t, ctypes.int32_t), - status, - released + status: status, + released: released } ); samples.push( @@ -92,8 +92,8 @@ function run_test() ctypes.bool, ctypes.int64_t, ctypes.int64_t), - status, - released + status: status, + released: released } ); samples.push( @@ -112,8 +112,8 @@ function run_test() ctypes.bool, ctypes.void_t.ptr, ctypes.void_t.ptr), - status, - released + status: status, + released: released } ); samples.push( @@ -132,8 +132,8 @@ function run_test() ctypes.bool, ctypes.char.ptr, ctypes.char.ptr), - status, - released + status: status, + released: released } ); const rect_t = new ctypes.StructType("myRECT", @@ -157,8 +157,8 @@ function run_test() ctypes.bool, rect_t, rect_t), - status, - released + status: status, + released: released } ); samples.push( @@ -177,7 +177,7 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status, + status: status, released: function released_eq(i, witness) { return i == witness; } @@ -199,7 +199,7 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status, + status: status, released: function released_rect_eq(i, witness) { return witness.top == i && witness.bottom == i @@ -228,7 +228,7 @@ function run_test() ctypes.bool, ctypes.void_t.ptr, ctypes.void_t.ptr), - released + released: released } ); @@ -397,8 +397,8 @@ function test_executing_forget(size, tc, cleanup) let finalizer = ctypes.CDataFinalizer(original, tc.release); ref.push( { - original, - finalizer + original: original, + finalizer: finalizer } ); cleanup.add(finalizer); diff --git a/toolkit/components/ctypes/tests/unit/test_jsctypes.js b/toolkit/components/ctypes/tests/unit/test_jsctypes.js index f91f40992d24..18861a185c3c 100644 --- a/toolkit/components/ctypes/tests/unit/test_jsctypes.js +++ b/toolkit/components/ctypes/tests/unit/test_jsctypes.js @@ -413,8 +413,8 @@ function run_Int64_tests() { ctypes.UInt64("0x8000000000000000"), Infinity, -Infinity, NaN, 0.1, 5.68e21, null, undefined, "", {}, [], new Number(16), - {toString() { return 7; }}, - {valueOf() { return 7; }}]; + {toString: function() { return 7; }}, + {valueOf: function() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { ctypes.Int64(vals[i]); }, TypeError); @@ -563,8 +563,8 @@ function run_UInt64_tests() { let vals = [-1, 0x10000000000000000, "-1", "-0x1", ctypes.Int64("-1"), Infinity, -Infinity, NaN, 0.1, 5.68e21, null, undefined, "", {}, [], new Number(16), - {toString() { return 7; }}, - {valueOf() { return 7; }}]; + {toString: function() { return 7; }}, + {valueOf: function() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { ctypes.UInt64(vals[i]); }, TypeError); @@ -778,8 +778,8 @@ function run_bool_tests(library) { let vals = [-1, 2, Infinity, -Infinity, NaN, 0.1, ctypes.Int64(0), ctypes.UInt64(0), null, undefined, "", "0", {}, [], new Number(16), - {toString() { return 7; }}, - {valueOf() { return 7; }}]; + {toString: function() { return 7; }}, + {valueOf: function() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -858,8 +858,8 @@ function run_integer_tests(library, t, name, size, signed, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "0", {}, [], new Number(16), - {toString() { return 7; }}, - {valueOf() { return 7; }}]; + {toString: function() { return 7; }}, + {valueOf: function() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -945,8 +945,8 @@ function run_float_tests(library, t, name, size) { // don't convert anything else let vals = [true, false, null, undefined, "", "0", {}, [], new Number(16), - {toString() { return 7; }}, - {valueOf() { return 7; }}]; + {toString: function() { return 7; }}, + {valueOf: function() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1045,8 +1045,8 @@ function run_wrapped_integer_tests(library, t, name, size, signed, w, wname, lim // don't convert anything else let vals = [limits[2], limits[3], Infinity, -Infinity, NaN, 0.1, null, undefined, "", "0", {}, [], new Number(16), - {toString() { return 7; }}, - {valueOf() { return 7; }}]; + {toString: function() { return 7; }}, + {valueOf: function() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1128,8 +1128,8 @@ function run_char_tests(library, t, name, size, signed, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "aa", {}, [], new Number(16), - {toString() { return 7; }}, - {valueOf() { return 7; }}]; + {toString: function() { return 7; }}, + {valueOf: function() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1220,8 +1220,8 @@ function run_char16_tests(library, t, name, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "aa", {}, [], new Number(16), - {toString() { return 7; }}, - {valueOf() { return 7; }}]; + {toString: function() { return 7; }}, + {valueOf: function() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -2223,7 +2223,7 @@ function run_string_tests(library) { do_check_eq(test_ansi_len("hello world"), 11); // don't convert anything else to a string - let vals = [true, 0, 1 / 3, undefined, {}, {toString() { return "bad"; }}, []]; + let vals = [true, 0, 1 / 3, undefined, {}, {toString: function() { return "bad"; }}, []]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { test_ansi_len(vals[i]); }, TypeError); diff --git a/toolkit/components/downloads/test/unit/test_app_rep_windows.js b/toolkit/components/downloads/test/unit/test_app_rep_windows.js index 44fd26999830..49d89751bc83 100644 --- a/toolkit/components/downloads/test/unit/test_app_rep_windows.js +++ b/toolkit/components/downloads/test/unit/test_app_rep_windows.js @@ -119,8 +119,8 @@ function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) { copier.init(inputStream, aSaverOutputStream, null, false, true, 0x8000, true, aCloseWhenDone); copier.asyncCopy({ - onStartRequest() { }, - onStopRequest(aRequest, aContext, aStatusCode) + onStartRequest: function() { }, + onStopRequest: function(aRequest, aContext, aStatusCode) { if (Components.isSuccessCode(aStatusCode)) { deferred.resolve(); diff --git a/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js b/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js index f1f32995fa5f..7e9c715f69a1 100644 --- a/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js +++ b/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js @@ -513,6 +513,7 @@ add_task(function* ensureKeysFor_posts_new_keys() { const newBody = yield assertPostedEncryptedKeys(newPost); ok(newBody.keys.collections[extensionId], `keys object should have a key for ${extensionId}`); ok(newBody.keys.collections[extensionId2], `keys object should have a key for ${extensionId2}`); + }); }); }); diff --git a/toolkit/components/exthelper/extApplication.js b/toolkit/components/exthelper/extApplication.js index b592e8cdc782..ff17f37e5234 100644 --- a/toolkit/components/exthelper/extApplication.js +++ b/toolkit/components/exthelper/extApplication.js @@ -663,7 +663,7 @@ extApplication.prototype = { return this.prefs; }, - getExtensions(callback) { + getExtensions: function(callback) { AddonManager.getAddonsByTypes(["extension"], function(addons) { callback.callback(new Extensions(addons)); }); diff --git a/toolkit/components/feeds/test/test_xml.js b/toolkit/components/feeds/test/test_xml.js index 5a6f350ef011..5bc0d759d12a 100644 --- a/toolkit/components/feeds/test/test_xml.js +++ b/toolkit/components/feeds/test/test_xml.js @@ -32,7 +32,7 @@ function FeedListener(testcase) { } FeedListener.prototype = { - handleResult(result) { + handleResult: function(result) { var feed = result.doc; try { do_print("Testing feed " + this.testcase.file.path); diff --git a/toolkit/components/filepicker/content/filepicker.js b/toolkit/components/filepicker/content/filepicker.js index 1069a7b2cfa4..7dc0a936e616 100644 --- a/toolkit/components/filepicker/content/filepicker.js +++ b/toolkit/components/filepicker/content/filepicker.js @@ -368,11 +368,11 @@ var gFilesEnumerator = { mFiles: null, mIndex: 0, - hasMoreElements() + hasMoreElements: function() { return (this.mIndex < this.mFiles.length); }, - getNext() + getNext: function() { if (this.mIndex >= this.mFiles.length) throw Components.results.NS_ERROR_FAILURE; diff --git a/toolkit/components/filepicker/nsFilePicker.js b/toolkit/components/filepicker/nsFilePicker.js index f40b0562765d..97bb78e7631f 100644 --- a/toolkit/components/filepicker/nsFilePicker.js +++ b/toolkit/components/filepicker/nsFilePicker.js @@ -68,7 +68,7 @@ function nsFilePicker() nsFilePicker.prototype = { classID: Components.ID("{54ae32f8-1dd2-11b2-a209-df7c505370f8}"), - QueryInterface(iid) { + QueryInterface: function(iid) { if (iid.equals(nsIFilePicker) || iid.equals(nsISupports)) return this; @@ -113,11 +113,11 @@ nsFilePicker.prototype = { mFiles: [], mIndex: 0, - hasMoreElements() { + hasMoreElements: function() { return (this.mIndex < this.mFiles.length); }, - getNext() { + getNext: function() { if (this.mIndex >= this.mFiles.length) { throw Components.results.NS_ERROR_FAILURE; } @@ -176,13 +176,13 @@ nsFilePicker.prototype = { mParentWindow: null, /* methods */ - init(parent, title, mode) { + init: function(parent, title, mode) { this.mParentWindow = parent; this.mTitle = title; this.mMode = mode; }, - appendFilters(filterMask) { + appendFilters: function(filterMask) { if (filterMask & nsIFilePicker.filterHTML) { this.appendFilter(titleBundle.GetStringFromName("htmlTitle"), filterBundle.GetStringFromName("htmlFilter")); @@ -223,12 +223,12 @@ nsFilePicker.prototype = { } }, - appendFilter(title, extensions) { + appendFilter: function(title, extensions) { this.mFilterTitles.push(title); this.mFilters.push(extensions); }, - open(aFilePickerShownCallback) { + open: function(aFilePickerShownCallback) { var tm = Components.classes["@mozilla.org/thread-manager;1"] .getService(Components.interfaces.nsIThreadManager); tm.mainThread.dispatch(function() { @@ -243,7 +243,7 @@ nsFilePicker.prototype = { }.bind(this), Components.interfaces.nsIThread.DISPATCH_NORMAL); }, - show() { + show: function() { var o = {}; o.title = this.mTitle; o.mode = this.mMode; diff --git a/toolkit/components/filepicker/test/unit/test_filecomplete.js b/toolkit/components/filepicker/test/unit/test_filecomplete.js index 8e15f4ac2bbf..d1e18d533748 100644 --- a/toolkit/components/filepicker/test/unit/test_filecomplete.js +++ b/toolkit/components/filepicker/test/unit/test_filecomplete.js @@ -19,7 +19,7 @@ dir.append("test_dir"); dir.create(dir.DIRECTORY_TYPE, -1); var gListener = { - onSearchResult(aSearch, aResult) { + onSearchResult: function(aSearch, aResult) { // Check that we got same search string back. do_check_eq(aResult.searchString, "test"); // Check that the search succeeded. diff --git a/toolkit/components/formautofill/FormAutofillContentService.js b/toolkit/components/formautofill/FormAutofillContentService.js index 1de839f54d63..2b64e19663a3 100644 --- a/toolkit/components/formautofill/FormAutofillContentService.js +++ b/toolkit/components/formautofill/FormAutofillContentService.js @@ -76,7 +76,7 @@ FormHandler.prototype = { ? new this.window.Event("autocomplete", { bubbles: true }) : new this.window.AutocompleteErrorEvent("autocompleteerror", { bubbles: true, - reason }); + reason: reason }); yield this.waitForTick(); this.form.dispatchEvent(event); }), @@ -143,7 +143,7 @@ FormHandler.prototype = { * interface, or null if the operation failed because the constraints * on the allowed fields were not honored. */ - collectFormFields() { + collectFormFields: function() { let autofillData = { sections: [], }; @@ -173,7 +173,7 @@ FormHandler.prototype = { addressType: info.addressType, contactType: info.contactType, fieldName: info.fieldName, - element, + element: element, }); // The first level is the custom section. @@ -225,7 +225,7 @@ FormHandler.prototype = { * ], * } */ - autofillFormFields(aAutofillResult) { + autofillFormFields: function(aAutofillResult) { for (let field of aAutofillResult.fields) { // Get the field details, if it was processed by the user interface. let fieldDetail = this.fieldDetails @@ -244,7 +244,7 @@ FormHandler.prototype = { /** * Waits for one tick of the event loop before resolving the returned promise. */ - waitForTick() { + waitForTick: function() { return new Promise(function(resolve) { Services.tm.currentThread.dispatch(resolve, Ci.nsIThread.DISPATCH_NORMAL); }); @@ -263,7 +263,7 @@ FormAutofillContentService.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIFormAutofillContentService]), // nsIFormAutofillContentService - requestAutocomplete(aForm, aWindow) { + requestAutocomplete: function(aForm, aWindow) { new FormHandler(aForm, aWindow).handleRequestAutocomplete() .catch(Cu.reportError); }, diff --git a/toolkit/components/formautofill/FormAutofillStartup.js b/toolkit/components/formautofill/FormAutofillStartup.js index b459bc67fa61..a2c3b125774f 100644 --- a/toolkit/components/formautofill/FormAutofillStartup.js +++ b/toolkit/components/formautofill/FormAutofillStartup.js @@ -31,7 +31,7 @@ FormAutofillStartup.prototype = { ]), // nsIObserver - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { // This method is called by the "profile-after-change" category on startup, // which is called before any web page loads. At this time, we need to // register a global message listener in the parent process preemptively, @@ -44,7 +44,7 @@ FormAutofillStartup.prototype = { }, // nsIFrameMessageListener - receiveMessage(aMessage) { + receiveMessage: function(aMessage) { // Process the "FormAutofill:RequestAutocomplete" message. Any exception // raised in the parent process is caught and serialized into the reply // message that is sent to the requesting child process. diff --git a/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm b/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm index 23743f49e056..f2f2ddded104 100644 --- a/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm +++ b/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm @@ -40,7 +40,7 @@ this.RequestAutocompleteUI.prototype = { // Wrap the callback function so that it survives XPCOM. let args = { - resolveFn, + resolveFn: resolveFn, autofillData: this._autofillData, }; args.wrappedJSObject = args; diff --git a/toolkit/components/formautofill/content/requestAutocomplete.js b/toolkit/components/formautofill/content/requestAutocomplete.js index 269018d8ffb9..5dbbdc9c182d 100644 --- a/toolkit/components/formautofill/content/requestAutocomplete.js +++ b/toolkit/components/formautofill/content/requestAutocomplete.js @@ -22,7 +22,7 @@ const RequestAutocompleteDialog = { resolveFn: null, autofillData: null, - onLoad() { + onLoad: function() { Task.spawn(function* () { let args = window.arguments[0].wrappedJSObject; this.resolveFn = args.resolveFn; @@ -35,7 +35,7 @@ const RequestAutocompleteDialog = { }.bind(this)).catch(Cu.reportError); }, - onAccept() { + onAccept: function() { // TODO: Replace with autofill storage module (bug 1018304). const dummyDB = { "": { @@ -65,7 +65,7 @@ const RequestAutocompleteDialog = { result.fields.push({ section: section.name, - addressType, + addressType: addressType, contactType: field.contactType, fieldName: field.fieldName, value: dummyDB[addressType][fieldName], @@ -78,7 +78,7 @@ const RequestAutocompleteDialog = { this.resolveFn(result); }, - onCancel() { + onCancel: function() { window.close(); this.resolveFn({ canceled: true }); }, diff --git a/toolkit/components/formautofill/test/chrome/loader.js b/toolkit/components/formautofill/test/chrome/loader.js index 4cdc3cd6ed59..556211e3df30 100644 --- a/toolkit/components/formautofill/test/chrome/loader.js +++ b/toolkit/components/formautofill/test/chrome/loader.js @@ -33,7 +33,7 @@ var testUrl = location.href.replace(/\.\w+$/, ".js"); var promiseParentInitFinished = new Promise(function(resolve) { parentScript.addMessageListener("finish_load_in_parent", resolve); }); -parentScript.sendAsyncMessage("start_load_in_parent", { testUrl }); +parentScript.sendAsyncMessage("start_load_in_parent", { testUrl: testUrl }); // Define output functions so they look the same across all frameworks. var Output = { diff --git a/toolkit/components/formautofill/test/head_common.js b/toolkit/components/formautofill/test/head_common.js index 87a23f0756a1..f3fec4293929 100644 --- a/toolkit/components/formautofill/test/head_common.js +++ b/toolkit/components/formautofill/test/head_common.js @@ -42,7 +42,7 @@ var TestUtils = { * @resolves When pending events have been processed. * @rejects Never. */ - waitForTick() { + waitForTick: function() { return new Promise(resolve => executeSoon(resolve)); }, @@ -58,7 +58,7 @@ var TestUtils = { * @resolves When the specified time has passed. * @rejects Never. */ - waitMs(aTimeMs) { + waitMs: function(aTimeMs) { return new Promise(resolve => setTimeout(resolve, aTimeMs)); }, @@ -72,7 +72,7 @@ var TestUtils = { * @resolves The array [aSubject, aData] from the observed notification. * @rejects Never. */ - waitForNotification(aTopic) { + waitForNotification: function(aTopic) { Output.print("Waiting for notification: '" + aTopic + "'."); return new Promise(resolve => Services.obs.addObserver( @@ -96,7 +96,7 @@ var TestUtils = { * @resolves The arguments from the observed event. * @rejects Never. */ - waitForEvent(aTarget, aEventName, aUseCapture = false) { + waitForEvent: function(aTarget, aEventName, aUseCapture = false) { Output.print("Waiting for event: '" + aEventName + "' on " + aTarget + "."); return new Promise(resolve => aTarget.addEventListener(aEventName, @@ -183,7 +183,7 @@ var FormAutofillTest = { // The window is the subject of the observer notification. return { uiWindow: (yield promiseUIWindow)[0], - promiseResult, + promiseResult: promiseResult, }; }), }; diff --git a/toolkit/components/formautofill/test/loader_common.js b/toolkit/components/formautofill/test/loader_common.js index 33a838b4a31b..3f5fae5b2f49 100644 --- a/toolkit/components/formautofill/test/loader_common.js +++ b/toolkit/components/formautofill/test/loader_common.js @@ -104,12 +104,12 @@ function getTaskId(stackFrame) { // This is a shared helper for mochitest-chrome and mochitest-browser. var _mochitestAssert = { - ok(actual) { + ok: function(actual) { let stack = Components.stack.caller; ok(actual, "[" + stack.name + " : " + stack.lineNumber + "] " + actual + " == true"); }, - equal(actual, expected) { + equal: function(actual, expected) { let stack = Components.stack.caller; is(actual, expected, "[" + stack.name + " : " + stack.lineNumber + "] " + actual + " == " + expected); diff --git a/toolkit/components/gfx/SanityTest.js b/toolkit/components/gfx/SanityTest.js index 3f43202cd163..f600d2bd4e56 100644 --- a/toolkit/components/gfx/SanityTest.js +++ b/toolkit/components/gfx/SanityTest.js @@ -153,7 +153,7 @@ var listener = { "gfxSanity:ContentLoaded", ], - scheduleTest(win) { + scheduleTest: function(win) { this.win = win; this.win.onload = this.onWindowLoaded.bind(this); this.utils = this.win.QueryInterface(Ci.nsIInterfaceRequestor) @@ -166,7 +166,7 @@ var listener = { }); }, - runSanityTest() { + runSanityTest: function() { this.canvas = this.win.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); this.canvas.setAttribute("width", PAGE_WIDTH); this.canvas.setAttribute("height", PAGE_HEIGHT); @@ -187,7 +187,7 @@ var listener = { } }, - onWindowLoaded() { + onWindowLoaded: function() { let browser = this.win.document.createElementNS(XUL_NS, "browser"); browser.setAttribute("type", "content"); @@ -208,7 +208,7 @@ var listener = { this.mm.loadFrameScript(FRAME_SCRIPT_URL, false); }, - endTest() { + endTest: function() { if (!this.win) { return; } @@ -240,7 +240,7 @@ SanityTest.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - shouldRunTest() { + shouldRunTest: function() { // Only test gfx features if firefox has updated, or if the user has a new // gpu or drivers. var buildId = Services.appinfo.platformBuildID; @@ -286,7 +286,7 @@ SanityTest.prototype = { return true; }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { if (topic != "profile-after-change") return; // profile-after-change fires only at startup, so we won't need diff --git a/toolkit/components/gfx/content/gfxFrameScript.js b/toolkit/components/gfx/content/gfxFrameScript.js index eaac257ceff7..4b48dc11ac7e 100644 --- a/toolkit/components/gfx/content/gfxFrameScript.js +++ b/toolkit/components/gfx/content/gfxFrameScript.js @@ -3,7 +3,7 @@ var { classes: Cc, interfaces: Ci, utils: Cu } = Components; const gfxFrameScript = { domUtils: null, - init() { + init: function() { let webNav = docShell.QueryInterface(Ci.nsIWebNavigation); let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); @@ -18,7 +18,7 @@ const gfxFrameScript = { }, - handleEvent(aEvent) { + handleEvent: function(aEvent) { switch (aEvent.type) { case "MozAfterPaint": sendAsyncMessage('gfxSanity:ContentLoaded'); @@ -27,7 +27,7 @@ const gfxFrameScript = { } }, - isSanityTest(aUri) { + isSanityTest: function(aUri) { if (!aUri) { return false; } @@ -35,7 +35,7 @@ const gfxFrameScript = { return aUri.endsWith("/sanitytest.html"); }, - onStateChange(webProgress, req, flags, status) { + onStateChange: function(webProgress, req, flags, status) { if (webProgress.isTopLevel && (flags & Ci.nsIWebProgressListener.STATE_STOP) && this.isSanityTest(req.name)) { diff --git a/toolkit/components/jsdownloads/src/DownloadCore.jsm b/toolkit/components/jsdownloads/src/DownloadCore.jsm index ef10dec742b9..043f20cc18e9 100644 --- a/toolkit/components/jsdownloads/src/DownloadCore.jsm +++ b/toolkit/components/jsdownloads/src/DownloadCore.jsm @@ -622,7 +622,7 @@ this.Download.prototype = { * @resolves When the Download has been unblocked and succeeded. * @rejects JavaScript exception if any of the operations failed. */ - unblock() { + unblock: function() { if (this._promiseUnblock) { return this._promiseUnblock; } @@ -666,7 +666,7 @@ this.Download.prototype = { * @resolves When the Download's data has been removed. * @rejects JavaScript exception if any of the operations failed. */ - confirmBlock() { + confirmBlock: function() { if (this._promiseConfirmBlock) { return this._promiseConfirmBlock; } @@ -711,7 +711,7 @@ this.Download.prototype = { * @rejects JavaScript exception if there was an error trying to launch * the file. */ - launch() { + launch: function() { if (!this.succeeded) { return Promise.reject( new Error("launch can only be called if the download succeeded") @@ -845,7 +845,7 @@ this.Download.prototype = { * @resolves When the partial data has been successfully removed. * @rejects JavaScript exception if the operation could not be completed. */ - removePartialData() + removePartialData: function() { if (!this.canceled && !this.error) { return Promise.resolve(); @@ -920,7 +920,7 @@ this.Download.prototype = { * @resolves When the operation has completed. * @rejects Never. */ - refresh() + refresh: function() { return Task.spawn(function* () { if (!this.stopped || this._finalized) { @@ -999,7 +999,7 @@ this.Download.prototype = { * @rejects JavaScript exception if an error occurred while removing the * partially downloaded data. */ - finalize(aRemovePartialData) + finalize: function(aRemovePartialData) { // Prevents the download from starting again after having been stopped. this._finalized = true; @@ -1096,7 +1096,7 @@ this.Download.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable() + toSerializable: function() { let serializable = { source: this.source.toSerializable(), @@ -1148,7 +1148,7 @@ this.Download.prototype = { * * @return String representing the relevant download state. */ - getSerializationHash() + getSerializationHash: function() { // The "succeeded", "canceled", "error", and startTime properties are not // taken into account because they all change before the "stopped" property @@ -1296,7 +1296,7 @@ this.DownloadSource.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable() + toSerializable: function() { if (this.adjustChannel) { // If the callback was used, we can't reproduce this across sessions. @@ -1452,7 +1452,7 @@ this.DownloadTarget.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable() + toSerializable: function() { // Simplify the representation if we don't have other details. if (!this.partFilePath && !this._unknownProperties) { @@ -1654,7 +1654,7 @@ this.DownloadError.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable() + toSerializable: function() { let serializable = { result: this.result, @@ -1769,7 +1769,7 @@ this.DownloadSaver.prototype = { * started, to add it to the browsing history. This method has no effect if * the download is private. */ - addToHistory() + addToHistory: function() { if (this.download.source.isPrivate) { return; @@ -1806,7 +1806,7 @@ this.DownloadSaver.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable() + toSerializable: function() { throw new Error("Not implemented."); }, @@ -1814,12 +1814,12 @@ this.DownloadSaver.prototype = { /** * Returns the SHA-256 hash of the downloaded file, if it exists. */ - getSha256Hash() + getSha256Hash: function() { throw new Error("Not implemented."); }, - getSignatureInfo() + getSignatureInfo: function() { throw new Error("Not implemented."); }, @@ -1968,7 +1968,7 @@ this.DownloadCopySaver.prototype = { // When the operation completes, reflect the status in the promise // returned by this download execution function. backgroundFileSaver.observer = { - onTargetChange() { }, + onTargetChange: function() { }, onSaveComplete: (aSaver, aStatus) => { // Send notifications now that we can restart if needed. if (Components.isSuccessCode(aStatus)) { @@ -2033,7 +2033,7 @@ this.DownloadCopySaver.prototype = { aSetProgressBytesFn(currentBytes, totalBytes, aProgress > 0 && partFilePath && keepPartialData); }, - onStatus() { }, + onStatus: function() { }, }; // If the callback was set, handle it now before opening the channel. @@ -2257,7 +2257,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.removePartialData". */ - removePartialData() + removePartialData: function() { return Task.spawn(function* task_DCS_removePartialData() { if (this.download.target.partFilePath) { @@ -2275,7 +2275,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable() + toSerializable: function() { // Simplify the representation if we don't have other details. if (!this.entityID && !this._unknownProperties) { @@ -2291,7 +2291,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.getSha256Hash" */ - getSha256Hash() + getSha256Hash: function() { return this._sha256Hash; }, @@ -2299,7 +2299,7 @@ this.DownloadCopySaver.prototype = { /* * Implements DownloadSaver.getSignatureInfo. */ - getSignatureInfo() + getSignatureInfo: function() { return this._signatureInfo; }, @@ -2307,7 +2307,7 @@ this.DownloadCopySaver.prototype = { /* * Implements DownloadSaver.getRedirects. */ - getRedirects() + getRedirects: function() { return this._redirects; } @@ -2440,7 +2440,7 @@ this.DownloadLegacySaver.prototype = { * download is added to the browsing history here. Private downloads * are never added to history even if this parameter is false. */ - onTransferStarted(aRequest, aAlreadyAddedToHistory) + onTransferStarted: function(aRequest, aAlreadyAddedToHistory) { // Store the entity ID to use for resuming if required. if (this.download.tryToKeepPartialData && @@ -2603,7 +2603,7 @@ this.DownloadLegacySaver.prototype = { }.bind(this)); }, - _checkReputationAndMove() { + _checkReputationAndMove: function() { return DownloadCopySaver.prototype._checkReputationAndMove .apply(this, arguments); }, @@ -2629,7 +2629,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.removePartialData". */ - removePartialData() + removePartialData: function() { // DownloadCopySaver and DownloadLeagcySaver use the same logic for removing // partially downloaded data, though this implementation isn't shared by @@ -2640,7 +2640,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable() + toSerializable: function() { // This object depends on legacy components that are created externally, // thus it cannot be rebuilt during deserialization. To support resuming @@ -2652,7 +2652,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getSha256Hash". */ - getSha256Hash() + getSha256Hash: function() { if (this.copySaver) { return this.copySaver.getSha256Hash(); @@ -2663,7 +2663,7 @@ this.DownloadLegacySaver.prototype = { /** * Called by the nsITransfer implementation when the hash is available. */ - setSha256Hash(hash) + setSha256Hash: function(hash) { this._sha256Hash = hash; }, @@ -2671,7 +2671,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getSignatureInfo". */ - getSignatureInfo() + getSignatureInfo: function() { if (this.copySaver) { return this.copySaver.getSignatureInfo(); @@ -2682,7 +2682,7 @@ this.DownloadLegacySaver.prototype = { /** * Called by the nsITransfer implementation when the hash is available. */ - setSignatureInfo(signatureInfo) + setSignatureInfo: function(signatureInfo) { this._signatureInfo = signatureInfo; }, @@ -2690,7 +2690,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getRedirects". */ - getRedirects() + getRedirects: function() { if (this.copySaver) { return this.copySaver.getRedirects(); @@ -2702,7 +2702,7 @@ this.DownloadLegacySaver.prototype = { * Called by the nsITransfer implementation when the redirect chain is * available. */ - setRedirects(redirects) + setRedirects: function(redirects) { this._redirects = redirects; }, @@ -2746,7 +2746,7 @@ this.DownloadPDFSaver.prototype = { /** * Implements "DownloadSaver.execute". */ - execute(aSetProgressBytesFn, aSetPropertiesFn) + execute: function(aSetProgressBytesFn, aSetPropertiesFn) { return Task.spawn(function* task_DCS_execute() { if (!this.download.source.windowRef) { @@ -2801,7 +2801,7 @@ this.DownloadPDFSaver.prototype = { try { yield new Promise((resolve, reject) => { this._webBrowserPrint.print(printSettings, { - onStateChange(webProgress, request, stateFlags, status) { + onStateChange: function(webProgress, request, stateFlags, status) { if (stateFlags & Ci.nsIWebProgressListener.STATE_STOP) { if (!Components.isSuccessCode(status)) { reject(new DownloadError({ result: status, @@ -2811,14 +2811,14 @@ this.DownloadPDFSaver.prototype = { } } }, - onProgressChange(webProgress, request, curSelfProgress, + onProgressChange: function(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) { aSetProgressBytesFn(curTotalProgress, maxTotalProgress, false); }, - onLocationChange() {}, - onStatusChange() {}, - onSecurityChange() {}, + onLocationChange: function() {}, + onStatusChange: function() {}, + onSecurityChange: function() {}, }); }); } finally { @@ -2845,7 +2845,7 @@ this.DownloadPDFSaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable() + toSerializable: function() { if (this.download.succeeded) { return DownloadCopySaver.prototype.toSerializable.call(this); diff --git a/toolkit/components/jsdownloads/src/DownloadImport.jsm b/toolkit/components/jsdownloads/src/DownloadImport.jsm index fec2348fe499..c1c81cc6e617 100644 --- a/toolkit/components/jsdownloads/src/DownloadImport.jsm +++ b/toolkit/components/jsdownloads/src/DownloadImport.jsm @@ -68,7 +68,7 @@ this.DownloadImport.prototype = { * from the previous database has been read and added to * the DownloadList) */ - import() { + import: function() { return Task.spawn(function* task_DI_import() { let connection = yield Sqlite.openConnection({ path: this.path }); @@ -142,7 +142,7 @@ this.DownloadImport.prototype = { let downloadOptions = { source: { url: source, - referrer + referrer: referrer }, target: { path: targetPath, @@ -150,13 +150,13 @@ this.DownloadImport.prototype = { }, saver: { type: "copy", - entityID + entityID: entityID }, startTime: new Date(startTime / 1000), totalBytes: maxBytes, hasPartialData: !!tempPath, tryToKeepPartialData: true, - launchWhenSucceeded, + launchWhenSucceeded: launchWhenSucceeded, contentType: mimeType, launcherPath: preferredApplication }; diff --git a/toolkit/components/jsdownloads/src/DownloadLegacy.js b/toolkit/components/jsdownloads/src/DownloadLegacy.js index 368215524eaf..c9bcbdd82e15 100644 --- a/toolkit/components/jsdownloads/src/DownloadLegacy.js +++ b/toolkit/components/jsdownloads/src/DownloadLegacy.js @@ -166,7 +166,7 @@ DownloadLegacyTransfer.prototype = { aMaxTotalProgress); }, - onLocationChange() { }, + onLocationChange: function() { }, onStatusChange: function DLT_onStatusChange(aWebProgress, aRequest, aStatus, aMessage) @@ -184,7 +184,7 @@ DownloadLegacyTransfer.prototype = { } }, - onSecurityChange() { }, + onSecurityChange: function() { }, // nsIWebProgressListener2 @@ -237,9 +237,9 @@ DownloadLegacyTransfer.prototype = { target: { path: aTarget.QueryInterface(Ci.nsIFileURL).file.path, partFilePath: aTempFile && aTempFile.path }, saver: "legacy", - launchWhenSucceeded, - contentType, - launcherPath + launchWhenSucceeded: launchWhenSucceeded, + contentType: contentType, + launcherPath: launcherPath }).then(function DLT_I_onDownload(aDownload) { // Legacy components keep partial data when they use a ".part" file. if (aTempFile) { @@ -257,17 +257,17 @@ DownloadLegacyTransfer.prototype = { }.bind(this)).then(null, Cu.reportError); }, - setSha256Hash(hash) + setSha256Hash: function(hash) { this._sha256Hash = hash; }, - setSignatureInfo(signatureInfo) + setSignatureInfo: function(signatureInfo) { this._signatureInfo = signatureInfo; }, - setRedirects(redirects) + setRedirects: function(redirects) { this._redirects = redirects; }, diff --git a/toolkit/components/jsdownloads/src/DownloadList.jsm b/toolkit/components/jsdownloads/src/DownloadList.jsm index 32fbfe5966bf..4ab42e18648a 100644 --- a/toolkit/components/jsdownloads/src/DownloadList.jsm +++ b/toolkit/components/jsdownloads/src/DownloadList.jsm @@ -204,7 +204,7 @@ this.DownloadList.prototype = { * @param aDownload * The Download object that changed. */ - _notifyAllViews(aMethodName, aDownload) { + _notifyAllViews: function(aMethodName, aDownload) { for (let view of this._views) { try { if (aMethodName in view) { @@ -305,7 +305,7 @@ this.DownloadCombinedList.prototype = { * @resolves When the download has been added. * @rejects JavaScript exception. */ - add(aDownload) + add: function(aDownload) { if (aDownload.source.isPrivate) { return this._privateList.add(aDownload); @@ -329,7 +329,7 @@ this.DownloadCombinedList.prototype = { * @resolves When the download has been removed. * @rejects JavaScript exception. */ - remove(aDownload) + remove: function(aDownload) { if (aDownload.source.isPrivate) { return this._privateList.remove(aDownload); @@ -339,18 +339,18 @@ this.DownloadCombinedList.prototype = { // DownloadList view - onDownloadAdded(aDownload) + onDownloadAdded: function(aDownload) { this._downloads.push(aDownload); this._notifyAllViews("onDownloadAdded", aDownload); }, - onDownloadChanged(aDownload) + onDownloadChanged: function(aDownload) { this._notifyAllViews("onDownloadChanged", aDownload); }, - onDownloadRemoved(aDownload) + onDownloadRemoved: function(aDownload) { let index = this._downloads.indexOf(aDownload); if (index != -1) { @@ -396,7 +396,7 @@ this.DownloadSummary.prototype = { * @resolves When the view on the underlying list has been registered. * @rejects JavaScript exception. */ - bindToList(aList) + bindToList: function(aList) { if (this._list) { throw new Error("bindToList may be called only once."); @@ -432,7 +432,7 @@ this.DownloadSummary.prototype = { * notification has been sent. * @rejects JavaScript exception. */ - addView(aView) + addView: function(aView) { this._views.add(aView); @@ -458,7 +458,7 @@ this.DownloadSummary.prototype = { * will not receive any more notifications. * @rejects JavaScript exception. */ - removeView(aView) + removeView: function(aView) { this._views.delete(aView); @@ -494,7 +494,7 @@ this.DownloadSummary.prototype = { * and will recalculate the summary and notify the views in case the * aggregated properties are different. */ - _onListChanged() { + _onListChanged: function() { let allHaveStopped = true; let progressTotalBytes = 0; let progressCurrentBytes = 0; @@ -535,7 +535,7 @@ this.DownloadSummary.prototype = { // DownloadList view - onDownloadAdded(aDownload) + onDownloadAdded: function(aDownload) { this._downloads.push(aDownload); if (this._list) { @@ -543,12 +543,12 @@ this.DownloadSummary.prototype = { } }, - onDownloadChanged(aDownload) + onDownloadChanged: function(aDownload) { this._onListChanged(); }, - onDownloadRemoved(aDownload) + onDownloadRemoved: function(aDownload) { let index = this._downloads.indexOf(aDownload); if (index != -1) { diff --git a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm index 9eb05dd6367d..6e85d0b04b25 100644 --- a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm +++ b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm @@ -63,7 +63,7 @@ this.DownloadUIHelper = { * * @return A DownloadPrompter object. */ - getPrompter(aParent) + getPrompter: function(aParent) { return new DownloadPrompter(aParent || null); }, @@ -139,7 +139,7 @@ this.DownloadPrompter.prototype = { * @resolves Boolean indicating whether the launch operation can continue. * @rejects JavaScript exception. */ - confirmLaunchExecutable(aPath) + confirmLaunchExecutable: function(aPath) { const kPrefAlertOnEXEOpen = "browser.download.manager.alertOnEXEOpen"; diff --git a/toolkit/components/jsdownloads/src/Downloads.jsm b/toolkit/components/jsdownloads/src/Downloads.jsm index cbbb79a6309b..174f807a5977 100644 --- a/toolkit/components/jsdownloads/src/Downloads.jsm +++ b/toolkit/components/jsdownloads/src/Downloads.jsm @@ -139,7 +139,7 @@ this.Downloads = { * @resolves When the download has finished successfully. * @rejects JavaScript exception if the download failed. */ - fetch(aSource, aTarget, aOptions) { + fetch: function(aSource, aTarget, aOptions) { return this.createDownload({ source: aSource, target: aTarget, @@ -170,7 +170,7 @@ this.Downloads = { * @resolves The requested DownloadList or DownloadCombinedList object. * @rejects JavaScript exception. */ - getList(aType) + getList: function(aType) { if (!this._promiseListsInitialized) { this._promiseListsInitialized = Task.spawn(function* () { @@ -232,7 +232,7 @@ this.Downloads = { * @resolves The requested DownloadList or DownloadCombinedList object. * @rejects JavaScript exception. */ - getSummary(aType) + getSummary: function(aType) { if (aType != Downloads.PUBLIC && aType != Downloads.PRIVATE && aType != Downloads.ALL) { diff --git a/toolkit/components/jsdownloads/test/unit/common_test_Download.js b/toolkit/components/jsdownloads/test/unit/common_test_Download.js index 1b0ad82c32c0..3310eef05a19 100644 --- a/toolkit/components/jsdownloads/test/unit/common_test_Download.js +++ b/toolkit/components/jsdownloads/test/unit/common_test_Download.js @@ -200,7 +200,7 @@ add_task(function* test_basic() // When testing DownloadLegacySaver, the download is already started when it // is created, thus we must check its basic properties while in progress. download = yield promiseStartLegacyDownload(null, - { targetFile }); + { targetFile: targetFile }); do_check_eq(download.source.url, httpUrl("source.txt")); do_check_eq(download.target.path, targetFile.path); @@ -1391,7 +1391,7 @@ add_task(function* test_error_target() // the "error" property checked by promiseDownloadStopped. This happens // because we don't have control over when the download is started. download = yield promiseStartLegacyDownload(null, - { targetFile }); + { targetFile: targetFile }); yield promiseDownloadStopped(download); } do_throw("The download should have failed."); @@ -1438,7 +1438,7 @@ add_task(function* test_error_restart() download.start().catch(() => {}); } else { download = yield promiseStartLegacyDownload(null, - { targetFile }); + { targetFile: targetFile }); } yield promiseDownloadStopped(download); do_throw("The download should have failed."); @@ -2167,7 +2167,7 @@ add_task(function* test_launch() { download = yield Downloads.createDownload({ source: httpUrl("source.txt"), target: getTempFile(TEST_TARGET_FILE_NAME).path, - launcherPath, + launcherPath: launcherPath, launchWhenSucceeded: true }); @@ -2185,7 +2185,7 @@ add_task(function* test_launch() { // it is created, thus we don't test calling "launch" before starting. download = yield promiseStartLegacyDownload( httpUrl("source.txt"), - { launcherPath, + { launcherPath: launcherPath, launchWhenSucceeded: true }); yield promiseDownloadStopped(download); } @@ -2266,13 +2266,13 @@ add_task(function* test_launchWhenSucceeded() { source: httpUrl("source.txt"), target: getTempFile(TEST_TARGET_FILE_NAME).path, launchWhenSucceeded: true, - launcherPath, + launcherPath: launcherPath, }); yield download.start(); } else { let download = yield promiseStartLegacyDownload( httpUrl("source.txt"), - { launcherPath, + { launcherPath: launcherPath, launchWhenSucceeded: true }); yield promiseDownloadStopped(download); } @@ -2338,7 +2338,7 @@ add_task(function* test_platform_integration() } let downloadWatcherNotified = false; let observer = { - observe(subject, topic, data) { + observe: function(subject, topic, data) { do_check_eq(topic, "download-watcher-notify"); do_check_eq(data, "modified"); downloadWatcherNotified = true; diff --git a/toolkit/components/jsdownloads/test/unit/head.js b/toolkit/components/jsdownloads/test/unit/head.js index 866392c79ebd..42fa2bb96f87 100644 --- a/toolkit/components/jsdownloads/test/unit/head.js +++ b/toolkit/components/jsdownloads/test/unit/head.js @@ -203,20 +203,20 @@ function promiseWaitForVisit(aUrl) PlacesUtils.history.addObserver({ QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver]), - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onVisit(aURI, aVisitID, aTime, aSessionID, aReferringID, + onBeginUpdateBatch: function() {}, + onEndUpdateBatch: function() {}, + onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID, aTransitionType, aGUID, aHidden) { if (aURI.equals(uri)) { PlacesUtils.history.removeObserver(this); deferred.resolve([aTime, aTransitionType]); } }, - onTitleChanged() {}, - onDeleteURI() {}, - onClearHistory() {}, - onPageChanged() {}, - onDeleteVisits() {}, + onTitleChanged: function() {}, + onDeleteURI: function() {}, + onClearHistory: function() {}, + onPageChanged: function() {}, + onDeleteVisits: function() {}, }, false); return deferred.promise; @@ -342,7 +342,7 @@ function promiseStartLegacyDownload(aSourceUrl, aOptions) { // Temporarily register a view that will get notified when the download we // are controlling becomes visible in the list of downloads. aList.addView({ - onDownloadAdded(aDownload) { + onDownloadAdded: function(aDownload) { aList.removeView(this).then(null, do_report_unexpected_exception); // Remove the download to keep the list empty for the next test. This @@ -395,7 +395,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { // Temporarily register a view that will get notified when the download we // are controlling becomes visible in the list of downloads. aList.addView({ - onDownloadAdded(aDownload) { + onDownloadAdded: function(aDownload) { aList.removeView(this).then(null, do_report_unexpected_exception); // Remove the download to keep the list empty for the next test. This @@ -417,7 +417,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { channel.asyncOpen2({ contentListener: null, - onStartRequest(aRequest, aContext) + onStartRequest: function(aRequest, aContext) { let requestChannel = aRequest.QueryInterface(Ci.nsIChannel); this.contentListener = gExternalHelperAppService.doContent( @@ -425,12 +425,12 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { this.contentListener.onStartRequest(aRequest, aContext); }, - onStopRequest(aRequest, aContext, aStatusCode) + onStopRequest: function(aRequest, aContext, aStatusCode) { this.contentListener.onStopRequest(aRequest, aContext, aStatusCode); }, - onDataAvailable(aRequest, aContext, aInputStream, aOffset, + onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount) { this.contentListener.onDataAvailable(aRequest, aContext, aInputStream, @@ -577,10 +577,10 @@ function startFakeServer() { let serverSocket = new ServerSocket(-1, true, -1); serverSocket.asyncListen({ - onSocketAccepted(aServ, aTransport) { + onSocketAccepted: function(aServ, aTransport) { aTransport.close(Cr.NS_BINDING_ABORTED); }, - onStopListening() { }, + onStopListening: function() { }, }); return serverSocket; } diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js b/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js index d470d33da908..cce155716fd6 100644 --- a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js +++ b/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js @@ -169,14 +169,14 @@ function promiseEntityID(aUrl) { }); channel.asyncOpen2({ - onStartRequest(aRequest) { + onStartRequest: function(aRequest) { if (aRequest instanceof Ci.nsIResumableChannel) { entityID = aRequest.entityID; } aRequest.cancel(Cr.NS_BINDING_ABORTED); }, - onStopRequest(aRequest, aContext, aStatusCode) { + onStopRequest: function(aRequest, aContext, aStatusCode) { if (aStatusCode == Cr.NS_BINDING_ABORTED) { deferred.resolve(entityID); } else { @@ -184,7 +184,7 @@ function promiseEntityID(aUrl) { } }, - onDataAvailable() {} + onDataAvailable: function() {} }); return deferred.promise; diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js b/toolkit/components/jsdownloads/test/unit/test_DownloadList.js index 42cd77e784ee..b3e24b0dba67 100644 --- a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js +++ b/toolkit/components/jsdownloads/test/unit/test_DownloadList.js @@ -56,7 +56,7 @@ function promiseExpirableDownloadVisit(aSourceUrl) aResultCode); deferred.reject(ex); }, - handleResult() {}, + handleResult: function() {}, handleCompletion: function handleCompletion() { deferred.resolve(); } @@ -192,7 +192,7 @@ add_task(function* test_notifications_add_remove() // Check that we receive add notifications for existing elements. let addNotifications = 0; let viewOne = { - onDownloadAdded(aDownload) { + onDownloadAdded: function(aDownload) { // The first download to be notified should be the first that was added. if (addNotifications == 0) { do_check_eq(aDownload, downloadOne); @@ -212,7 +212,7 @@ add_task(function* test_notifications_add_remove() // Check that we receive remove notifications. let removeNotifications = 0; let viewTwo = { - onDownloadRemoved(aDownload) { + onDownloadRemoved: function(aDownload) { do_check_eq(aDownload, downloadOne); removeNotifications++; }, @@ -257,7 +257,7 @@ add_task(function* test_notifications_change() // Check that we receive change notifications. let receivedOnDownloadChanged = false; yield list.addView({ - onDownloadChanged(aDownload) { + onDownloadChanged: function(aDownload) { do_check_eq(aDownload, downloadOne); receivedOnDownloadChanged = true; }, @@ -285,18 +285,18 @@ add_task(function* test_notifications_this() let receivedOnDownloadChanged = false; let receivedOnDownloadRemoved = false; let view = { - onDownloadAdded() { + onDownloadAdded: function() { do_check_eq(this, view); receivedOnDownloadAdded = true; }, - onDownloadChanged() { + onDownloadChanged: function() { // Only do this check once. if (!receivedOnDownloadChanged) { do_check_eq(this, view); receivedOnDownloadChanged = true; } }, - onDownloadRemoved() { + onDownloadRemoved: function() { do_check_eq(this, view); receivedOnDownloadRemoved = true; }, @@ -336,7 +336,7 @@ add_task(function* test_history_expiration() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved(aDownload) { + onDownloadRemoved: function(aDownload) { if (++removeNotifications == 2) { deferred.resolve(); } @@ -383,7 +383,7 @@ add_task(function* test_history_clear() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved(aDownload) { + onDownloadRemoved: function(aDownload) { if (++removeNotifications == 2) { deferred.resolve(); } @@ -419,7 +419,7 @@ add_task(function* test_removeFinished() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved(aDownload) { + onDownloadRemoved: function(aDownload) { do_check_true(aDownload == downloadOne || aDownload == downloadTwo || aDownload == downloadThree); @@ -555,7 +555,7 @@ add_task(function* test_DownloadSummary_notifications() // Check that we receive change notifications. let receivedOnSummaryChanged = false; yield summary.addView({ - onSummaryChanged() { + onSummaryChanged: function() { receivedOnSummaryChanged = true; }, }); diff --git a/toolkit/components/lz4/lz4.js b/toolkit/components/lz4/lz4.js index 70dd758e8537..8d4ffcf8e58e 100644 --- a/toolkit/components/lz4/lz4.js +++ b/toolkit/components/lz4/lz4.js @@ -150,7 +150,7 @@ exports.decompressFileContent = decompressFileContent; if (typeof Components != "undefined") { this.Lz4 = { - compressFileContent, - decompressFileContent + compressFileContent: compressFileContent, + decompressFileContent: decompressFileContent }; } diff --git a/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js b/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js index 745f44dd81cd..b26d554a8e6a 100644 --- a/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js +++ b/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js @@ -45,12 +45,12 @@ const tests = [ // A basic listener that reads checks the if we sniffed properly. var listener = { - onStartRequest(request, context) { + onStartRequest: function(request, context) { do_check_eq(request.QueryInterface(Ci.nsIChannel).contentType, tests[testRan].expectedContentType); }, - onDataAvailable(request, context, stream, offset, count) { + onDataAvailable: function(request, context, stream, offset, count) { try { var bis = Components.classes["@mozilla.org/binaryinputstream;1"] .createInstance(Components.interfaces.nsIBinaryInputStream); @@ -61,7 +61,7 @@ var listener = { } }, - onStopRequest(request, context, status) { + onStopRequest: function(request, context, status) { testRan++; runNext(); } @@ -72,7 +72,7 @@ function setupChannel(url, flags) let uri = "http://localhost:" + httpserver.identity.primaryPort + url; var chan = NetUtil.newChannel({ - uri, + uri: uri, loadUsingSystemPrincipal: true, contentPolicyType: Ci.nsIContentPolicy.TYPE_MEDIA }); diff --git a/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js b/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js index 78cb68c038a3..ce30a5c1ba18 100644 --- a/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js +++ b/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js @@ -46,12 +46,12 @@ const tests = [ // A basic listener that reads checks the if we sniffed properly. var listener = { - onStartRequest(request, context) { + onStartRequest: function(request, context) { do_print("Sniffing " + tests[testRan].path); do_check_eq(request.QueryInterface(Ci.nsIChannel).contentType, tests[testRan].expected); }, - onDataAvailable(request, context, stream, offset, count) { + onDataAvailable: function(request, context, stream, offset, count) { try { var bis = Components.classes["@mozilla.org/binaryinputstream;1"] .createInstance(Components.interfaces.nsIBinaryInputStream); @@ -62,7 +62,7 @@ var listener = { } }, - onStopRequest(request, context, status) { + onStopRequest: function(request, context, status) { testRan++; runNext(); } diff --git a/toolkit/components/microformats/microformat-shiv.js b/toolkit/components/microformats/microformat-shiv.js index 47651bbb88f8..f12d5208ad48 100644 --- a/toolkit/components/microformats/microformat-shiv.js +++ b/toolkit/components/microformats/microformat-shiv.js @@ -43,7 +43,7 @@ var Microformats; // jshint ignore:line modules.Parser.prototype = { - init() { + init: function() { this.rootNode = null; this.document = null; this.options = { @@ -67,7 +67,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Object} */ - get(options) { + get: function(options) { var out = this.formatEmpty(), data = [], rels; @@ -126,7 +126,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Object} */ - getParent(node, options) { + getParent: function(node, options) { this.init(); options = (options) ? options : {}; @@ -144,7 +144,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} rootNode * @return {Int} */ - count( options ) { + count: function( options ) { var out = {}, items, classItems, @@ -194,7 +194,7 @@ var Microformats; // jshint ignore:line * @param {Objecte} options * @return {Boolean} */ - isMicroformat( node, options ) { + isMicroformat: function( node, options ) { var classes, i; @@ -227,7 +227,7 @@ var Microformats; // jshint ignore:line * @param {Objecte} options * @return {Boolean} */ - hasMicroformats( node, options ) { + hasMicroformats: function( node, options ) { var items, i; @@ -258,7 +258,7 @@ var Microformats; // jshint ignore:line * * @param {Array} maps */ - add( maps ) { + add: function( maps ) { maps.forEach(function(map) { if (map && map.root && map.name && map.properties) { modules.maps[map.name] = JSON.parse(JSON.stringify(map)); @@ -275,7 +275,7 @@ var Microformats; // jshint ignore:line * @param {Int} recursive * @return {Object} */ - getParentTreeWalk(node, options, recursive) { + getParentTreeWalk: function(node, options, recursive) { options = (options) ? options : {}; // recursive calls @@ -303,7 +303,7 @@ var Microformats; // jshint ignore:line * * @param {Object} options */ - getDOMContext( options ) { + getDOMContext: function( options ) { var nodes = modules.domUtils.getDOMContext( options ); this.rootNode = nodes.rootNode; this.document = nodes.document; @@ -316,7 +316,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Boolean} */ - prepareDOM( options ) { + prepareDOM: function( options ) { var baseTag, href; @@ -370,7 +370,7 @@ var Microformats; // jshint ignore:line * * @return {Object} */ - formatError() { + formatError: function() { var out = this.formatEmpty(); out.errors = this.errors; return out; @@ -382,7 +382,7 @@ var Microformats; // jshint ignore:line * * @return {Object} */ - formatEmpty() { + formatEmpty: function() { return { 'items': [], 'rels': {}, @@ -392,7 +392,7 @@ var Microformats; // jshint ignore:line // find microformats of a given type and return node structures - findFilterNodes(rootNode, filters) { + findFilterNodes: function(rootNode, filters) { if (modules.utils.isString(filters)) { filters = [filters]; } @@ -438,7 +438,7 @@ var Microformats; // jshint ignore:line * @param {Int} count * @param {Object} */ - appendCount(name, count, out) { + appendCount: function(name, count, out) { if (out[name]) { out[name] = out[name] + count; } else { @@ -454,7 +454,7 @@ var Microformats; // jshint ignore:line * @param {Array} filters * @return {Boolean} */ - shouldInclude(uf, filters) { + shouldInclude: function(uf, filters) { var i; if (modules.utils.isArray(filters) && filters.length > 0) { @@ -477,7 +477,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} includeRoot * @return {Array} */ - findRootNodes(rootNode, includeRoot) { + findRootNodes: function(rootNode, includeRoot) { var arr = null, out = [], classList = [], @@ -538,7 +538,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - walkRoot(node) { + walkRoot: function(node) { var context = this, children = [], child, @@ -577,7 +577,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - walkTree(node) { + walkTree: function(node) { var classes, out = [], obj, @@ -612,7 +612,7 @@ var Microformats; // jshint ignore:line * @param {Int} rootID * @param {Object} parentClasses */ - walkChildren(node, out, ufName, rootID, parentClasses) { + walkChildren: function(node, out, ufName, rootID, parentClasses) { var context = this, children = [], rootItem, @@ -777,7 +777,7 @@ var Microformats; // jshint ignore:line * @param {Object} uf * @return {String || Object} */ - getValue(node, className, uf) { + getValue: function(node, className, uf) { var value = ''; if (modules.utils.startWith(className, 'p-')) { @@ -806,7 +806,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getPValue(node, valueParse) { + getPValue: function(node, valueParse) { var out = ''; if (valueParse) { out = this.getValueClass(node, 'p'); @@ -846,7 +846,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Object} */ - getEValue(node) { + getEValue: function(node) { var out = {value: '', html: ''}; @@ -867,7 +867,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getUValue(node, valueParse) { + getUValue: function(node, valueParse) { var out = ''; if (valueParse) { out = this.getValueClass(node, 'u'); @@ -919,7 +919,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getDTValue(node, className, uf, valueParse) { + getDTValue: function(node, className, uf, valueParse) { var out = ''; if (valueParse) { @@ -974,7 +974,7 @@ var Microformats; // jshint ignore:line * @param {String} id * @param {String} propertyName */ - appendRootID(node, id, propertyName) { + appendRootID: function(node, id, propertyName) { if (this.hasRootID(node, id, propertyName) === false) { var rootids = []; if (modules.domUtils.hasAttribute(node, 'rootids')) { @@ -994,7 +994,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyName * @return {Boolean} */ - hasRootID(node, id, propertyName) { + hasRootID: function(node, id, propertyName) { var rootids = []; if (!modules.domUtils.hasAttribute(node, 'rootids')) { return false; @@ -1012,7 +1012,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyName * @return {String || null} */ - getValueClass(node, propertyType) { + getValueClass: function(node, propertyType) { var context = this, children = [], out = [], @@ -1068,7 +1068,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - getValueTitle(node) { + getValueTitle: function(node) { var out = [], items, i, @@ -1093,7 +1093,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Boolean} */ - hasHClass(node) { + hasHClass: function(node) { var classes = this.getUfClassNames(node); if (classes.root && classes.root.length > 0) { return true; @@ -1109,7 +1109,7 @@ var Microformats; // jshint ignore:line * @param {Array} ufNameArr * @return {Object} */ - getUfClassNames(node, ufNameArr) { + getUfClassNames: function(node, ufNameArr) { var context = this, out = { 'root': [], @@ -1258,7 +1258,7 @@ var Microformats; // jshint ignore:line * @param {String} name * @return {Object || null} */ - getMapping(name) { + getMapping: function(name) { var key; for (key in modules.maps) { if (modules.maps[key].root === name || key === name) { @@ -1275,7 +1275,7 @@ var Microformats; // jshint ignore:line * @param {String} name * @return {String || null} */ - getV2RootName(name) { + getV2RootName: function(name) { var key; for (key in modules.maps) { if (modules.maps[key].root === name) { @@ -1293,7 +1293,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyVersion * @return {Boolean} */ - isAllowedPropertyVersion(typeVersion, propertyVersion) { + isAllowedPropertyVersion: function(typeVersion, propertyVersion) { if (this.options.overlappingVersions === true) { return true; } @@ -1308,7 +1308,7 @@ var Microformats; // jshint ignore:line * @param {String} value * @return {Object} */ - createUfObject(names, typeVersion, value) { + createUfObject: function(names, typeVersion, value) { var out = {}; // is more than just whitespace @@ -1337,7 +1337,7 @@ var Microformats; // jshint ignore:line * * @param {Object} microformat */ - cleanUfObject( microformat ) { + cleanUfObject: function( microformat ) { delete microformat.times; delete microformat.dates; delete microformat.typeVersion; @@ -1353,7 +1353,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - removePropPrefix(text) { + removePropPrefix: function(text) { var i; i = this.propertyPrefixes.length; @@ -1374,7 +1374,7 @@ var Microformats; // jshint ignore:line * @param {String} attrName * @param {String} baseUrl */ - expandURLs(node, attrName, baseUrl) { + expandURLs: function(node, attrName, baseUrl) { var i, nodes, attr; @@ -1403,7 +1403,7 @@ var Microformats; // jshint ignore:line * * @param {Object} options */ - mergeOptions(options) { + mergeOptions: function(options) { var key; for (key in options) { if (options.hasOwnProperty(key)) { @@ -1418,7 +1418,7 @@ var Microformats; // jshint ignore:line * * @param {DOM Node} rootNode */ - removeRootIds(rootNode) { + removeRootIds: function(rootNode) { var arr, i; @@ -1435,7 +1435,7 @@ var Microformats; // jshint ignore:line * * @param {DOM Node} rootNode */ - clearUpDom(rootNode) { + clearUpDom: function(rootNode) { if (this.removeIncludes) { this.removeIncludes(rootNode); } @@ -1751,15 +1751,15 @@ var Microformats; // jshint ignore:line if (uf.value && !uf.altValue) { // first p-name of the h-* child if (modules.utils.startWith(parentPropertyName, 'p-') && propertyName === 'p-name') { - uf.altValue = {name: propertyName, value}; + uf.altValue = {name: propertyName, value: value}; } // if it's an e-* property element if (modules.utils.startWith(parentPropertyName, 'e-') && modules.utils.startWith(propertyName, 'e-')) { - uf.altValue = {name: propertyName, value}; + uf.altValue = {name: propertyName, value: value}; } // if it's an u-* property element if (modules.utils.startWith(parentPropertyName, 'u-') && propertyName === 'u-url') { - uf.altValue = {name: propertyName, value}; + uf.altValue = {name: propertyName, value: value}; } } return uf; @@ -2205,7 +2205,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isString( obj ) { + isString: function( obj ) { return typeof( obj ) === 'string'; }, @@ -2215,7 +2215,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isNumber( obj ) { + isNumber: function( obj ) { return !isNaN(parseFloat( obj )) && isFinite( obj ); }, @@ -2226,7 +2226,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isArray( obj ) { + isArray: function( obj ) { return obj && !( obj.propertyIsEnumerable( 'length' ) ) && typeof obj === 'object' && typeof obj.length === 'number'; }, @@ -2237,7 +2237,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isFunction(obj) { + isFunction: function(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }, @@ -2249,7 +2249,7 @@ var Microformats; // jshint ignore:line * @param {String} test * @return {Boolean} */ - startWith( text, test ) { + startWith: function( text, test ) { return (text.indexOf(test) === 0); }, @@ -2260,7 +2260,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - trim( text ) { + trim: function( text ) { if (text && this.isString(text)) { return (text.trim()) ? text.trim() : text.replace(/^\s+|\s+$/g, ''); } @@ -2276,7 +2276,7 @@ var Microformats; // jshint ignore:line * @param {String} character * @return {String} */ - replaceCharAt( text, index, character ) { + replaceCharAt: function( text, index, character ) { if (text && text.length > index) { return text.substr(0, index) + character + text.substr(index + character.length); } @@ -2290,7 +2290,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - trimWhitespace( text ) { + trimWhitespace: function( text ) { if (text && text.length) { var i = text.length, x = 0; @@ -2325,7 +2325,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isOnlyWhiteSpace( text ) { + isOnlyWhiteSpace: function( text ) { return !(/[^\t\n\r ]/.test( text )); }, @@ -2336,7 +2336,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Sring} */ - collapseWhiteSpace( text ) { + collapseWhiteSpace: function( text ) { return text.replace(/[\t\n\r ]+/g, ' '); }, @@ -2347,7 +2347,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - hasProperties( obj ) { + hasProperties: function( obj ) { var key; for (key in obj) { if ( obj.hasOwnProperty( key ) ) { @@ -2365,7 +2365,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} reverse * @return {Int} */ - sortObjects(property, reverse) { + sortObjects: function(property, reverse) { reverse = (reverse) ? -1 : 1; return function(a, b) { a = a[property]; @@ -2395,7 +2395,7 @@ var Microformats; // jshint ignore:line * * @return {Object || undefined} */ - getDOMParser() { + getDOMParser: function() { if (typeof DOMParser === "undefined") { try { return Components.classes["@mozilla.org/xmlextras/domparser;1"] @@ -2415,7 +2415,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {DOM Node} node */ - getDOMContext( options ) { + getDOMContext: function( options ) { // if a node is passed if (options.node) { @@ -2465,7 +2465,7 @@ var Microformats; // jshint ignore:line * @param {Dom Document} * @return {DOM Node} node */ - getTopMostNode( node ) { + getTopMostNode: function( node ) { // var doc = this.ownerDocument(node); // if(doc && doc.nodeType && doc.nodeType === 9 && doc.documentElement){ // return doc.documentElement; @@ -2481,7 +2481,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Dom Document} */ - ownerDocument(node) { + ownerDocument: function(node) { return node.ownerDocument; }, @@ -2492,7 +2492,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - textContent(node) { + textContent: function(node) { if (node.textContent) { return node.textContent; } else if (node.innerText) { @@ -2508,7 +2508,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - innerHTML(node) { + innerHTML: function(node) { return node.innerHTML; }, @@ -2520,7 +2520,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {Boolean} */ - hasAttribute(node, attributeName) { + hasAttribute: function(node, attributeName) { return node.hasAttribute(attributeName); }, @@ -2533,7 +2533,7 @@ var Microformats; // jshint ignore:line * @param {String} value * @return {Boolean} */ - hasAttributeValue(node, attributeName, value) { + hasAttributeValue: function(node, attributeName, value) { return (this.getAttributeList(node, attributeName).indexOf(value) > -1); }, @@ -2545,7 +2545,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {String || null} */ - getAttribute(node, attributeName) { + getAttribute: function(node, attributeName) { return node.getAttribute(attributeName); }, @@ -2557,7 +2557,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @param {String} attributeValue */ - setAttribute(node, attributeName, attributeValue) { + setAttribute: function(node, attributeName, attributeValue) { node.setAttribute(attributeName, attributeValue); }, @@ -2568,7 +2568,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @param {String} attributeName */ - removeAttribute(node, attributeName) { + removeAttribute: function(node, attributeName) { node.removeAttribute(attributeName); }, @@ -2580,7 +2580,7 @@ var Microformats; // jshint ignore:line * @param {String} id * @return {DOM Node} */ - getElementById(docNode, id) { + getElementById: function(docNode, id) { return docNode.querySelector( '#' + id ); }, @@ -2592,7 +2592,7 @@ var Microformats; // jshint ignore:line * @param {String} selector * @return {DOM Node} */ - querySelector(docNode, selector) { + querySelector: function(docNode, selector) { return docNode.querySelector( selector ); }, @@ -2604,7 +2604,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {Array} */ - getAttributeList(node, attributeName) { + getAttributeList: function(node, attributeName) { var out = [], attList; @@ -2627,7 +2627,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {NodeList} */ - getNodesByAttribute(node, attributeName) { + getNodesByAttribute: function(node, attributeName) { var selector = '[' + attributeName + ']'; return node.querySelectorAll(selector); }, @@ -2640,7 +2640,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {DOM NodeList} */ - getNodesByAttributeValue(rootNode, name, value) { + getNodesByAttributeValue: function(rootNode, name, value) { var arr = [], x = 0, i, @@ -2667,7 +2667,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {String || null} */ - getAttrValFromTagList(node, tagNames, attributeName) { + getAttrValFromTagList: function(node, tagNames, attributeName) { var i = tagNames.length; while (i--) { @@ -2689,7 +2689,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getSingleDescendant(node) { + getSingleDescendant: function(node) { return this.getDescendant( node, null, false ); }, @@ -2701,7 +2701,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getSingleDescendantOfType(node, tagNames) { + getSingleDescendantOfType: function(node, tagNames) { return this.getDescendant( node, tagNames, true ); }, @@ -2713,7 +2713,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getDescendant( node, tagNames, onlyOfType ) { + getDescendant: function( node, tagNames, onlyOfType ) { var i = node.children.length, countAll = 0, countOfType = 0, @@ -2750,7 +2750,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {Boolean} */ - hasTagName(node, tagNames) { + hasTagName: function(node, tagNames) { var i = tagNames.length; while (i--) { if (node.tagName.toLowerCase() === tagNames[i]) { @@ -2768,7 +2768,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} childNode * @return {DOM Node} */ - appendChild(node, childNode) { + appendChild: function(node, childNode) { return node.appendChild(childNode); }, @@ -2779,7 +2779,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} childNode * @return {DOM Node || null} */ - removeChild(childNode) { + removeChild: function(childNode) { if (childNode.parentNode) { return childNode.parentNode.removeChild(childNode); } @@ -2793,7 +2793,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {DOM Node} */ - clone(node) { + clone: function(node) { var newNode = node.cloneNode(true); newNode.removeAttribute('id'); return newNode; @@ -2806,7 +2806,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - getElementText( node ) { + getElementText: function( node ) { if (node && node.data) { return node.data; } @@ -2820,7 +2820,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - getOrderedAttributes( node ) { + getOrderedAttributes: function( node ) { var nodeStr = node.outerHTML, attrs = []; @@ -2841,7 +2841,7 @@ var Microformats; // jshint ignore:line * @param String} text * @return {String} */ - decodeEntities( doc, text ) { + decodeEntities: function( doc, text ) { // return text; return doc.createTextNode( text ).nodeValue; }, @@ -2853,7 +2853,7 @@ var Microformats; // jshint ignore:line * @param {DOM Document} document * @return {DOM Document} */ - cloneDocument( document ) { + cloneDocument: function( document ) { var newNode, newDocument = null; @@ -2872,7 +2872,7 @@ var Microformats; // jshint ignore:line * @param {DOM Document} document * @return {Boolean} */ - canCloneDocument( document ) { + canCloneDocument: function( document ) { return (document && document.importNode && document.implementation && document.implementation.createHTMLDocument); }, @@ -2883,7 +2883,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Int} */ - getChildIndex(node) { + getChildIndex: function(node) { var parent = node.parentNode, i = -1, child; @@ -2902,7 +2902,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - getNodePath(node) { + getNodePath: function(node) { var parent = node.parentNode, path = [], index = this.getChildIndex(node); @@ -2923,7 +2923,7 @@ var Microformats; // jshint ignore:line * @param {Array} path * @return {DOM Node} */ - getNodeByPath(document, path) { + getNodeByPath: function(document, path) { var node = document.documentElement, i = 0, index; @@ -2940,7 +2940,7 @@ var Microformats; // jshint ignore:line * @param {DOM node} node * @return {Array} */ - getChildren( node ) { + getChildren: function( node ) { return node.children; }, @@ -2951,7 +2951,7 @@ var Microformats; // jshint ignore:line * @param {String} tagName * @return {DOM node} */ - createNode( tagName ) { + createNode: function( tagName ) { return this.document.createElement(tagName); }, @@ -2963,7 +2963,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {DOM node} */ - createNodeWithText( tagName, text ) { + createNodeWithText: function( tagName, text ) { var node = this.document.createElement(tagName); node.innerHTML = text; return node; @@ -2980,7 +2980,7 @@ var Microformats; // jshint ignore:line /** * creates DOM objects needed to resolve URLs */ - init() { + init: function() { // this._domParser = new DOMParser(); this._domParser = modules.domUtils.getDOMParser(); // do not use a head tag it does not work with IE9 @@ -2998,7 +2998,7 @@ var Microformats; // jshint ignore:line * @param {String} baseUrl * @return {String} */ - resolve(url, baseUrl) { + resolve: function(url, baseUrl) { // use modern URL web API where we can if (modules.utils.isString(url) && modules.utils.isString(baseUrl) && url.indexOf('://') === -1) { // this try catch is required as IE has an URL object but no constuctor support @@ -3062,7 +3062,7 @@ var Microformats; // jshint ignore:line * clear all states * */ - clear() { + clear: function() { this.clearDate(); this.clearTime(); this.clearTimeZone(); @@ -3074,7 +3074,7 @@ var Microformats; // jshint ignore:line * clear date states * */ - clearDate() { + clearDate: function() { this.dY = -1; this.dM = -1; this.dD = -1; @@ -3086,7 +3086,7 @@ var Microformats; // jshint ignore:line * clear time states * */ - clearTime() { + clearTime: function() { this.tH = -1; this.tM = -1; this.tS = -1; @@ -3098,7 +3098,7 @@ var Microformats; // jshint ignore:line * clear timezone states * */ - clearTimeZone() { + clearTimeZone: function() { this.tzH = -1; this.tzM = -1; this.tzPN = '+'; @@ -3110,7 +3110,7 @@ var Microformats; // jshint ignore:line * resets the auto profile state * */ - setAutoProfileState() { + setAutoProfileState: function() { this.autoProfile = { sep: 'T', dsep: '-', @@ -3128,7 +3128,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parse( dateString, format ) { + parse: function( dateString, format ) { this.clear(); var parts = [], @@ -3218,7 +3218,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseDate( dateString, format ) { + parseDate: function( dateString, format ) { this.clearDate(); var parts = []; @@ -3263,7 +3263,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseTime( timeString, format ) { + parseTime: function( timeString, format ) { this.clearTime(); var parts = []; @@ -3297,7 +3297,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseTimeZone( timeString, format ) { + parseTimeZone: function( timeString, format ) { this.clearTimeZone(); var parts = []; @@ -3337,7 +3337,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - toString( format ) { + toString: function( format ) { var output = ''; if (format) { @@ -3374,7 +3374,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - toTimeString( format ) { + toTimeString: function( format ) { var out = ''; if (format) { @@ -3417,7 +3417,7 @@ var Microformats; // jshint ignore:line * set the current profile to W3C Note, RFC 3339, HTML5, or auto profile * */ - setFormatSep() { + setFormatSep: function() { switch ( this.format.toLowerCase() ) { case 'rfc3339': this.sep = 'T'; @@ -3456,7 +3456,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasFullDate() { + hasFullDate: function() { return (this.dY !== -1 && this.dM !== -1 && this.dD !== -1); }, @@ -3466,7 +3466,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasDate() { + hasDate: function() { return (this.dY !== -1); }, @@ -3476,7 +3476,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasTime() { + hasTime: function() { return (this.tH !== -1); }, @@ -3485,7 +3485,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasTimeZone() { + hasTimeZone: function() { return (this.tzH !== -1); } @@ -3503,7 +3503,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - hasAM( text ) { + hasAM: function( text ) { text = text.toLowerCase(); return (text.indexOf('am') > -1 || text.indexOf('a.m.') > -1); }, @@ -3515,7 +3515,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - hasPM( text ) { + hasPM: function( text ) { text = text.toLowerCase(); return (text.indexOf('pm') > -1 || text.indexOf('p.m.') > -1); }, @@ -3527,7 +3527,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - removeAMPM( text ) { + removeAMPM: function( text ) { return text.replace('pm', '').replace('p.m.', '').replace('am', '').replace('a.m.', ''); }, @@ -3538,7 +3538,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isDuration( text ) { + isDuration: function( text ) { if (modules.utils.isString( text )) { text = text.toLowerCase(); if (modules.utils.startWith(text, 'p') ) { @@ -3556,7 +3556,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isTime( text ) { + isTime: function( text ) { if (modules.utils.isString(text)) { text = text.toLowerCase(); text = modules.utils.trim( text ); @@ -3592,7 +3592,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - parseAmPmTime( text ) { + parseAmPmTime: function( text ) { var out = text, times = []; @@ -3643,7 +3643,7 @@ var Microformats; // jshint ignore:line * @param {String} format ( Modules.ISODate profile format ) * @return {Object} Modules.ISODate */ - dateTimeUnion(date, time, format) { + dateTimeUnion: function(date, time, format) { var isodate = new modules.ISODate(date, format), isotime = new modules.ISODate(); @@ -3670,7 +3670,7 @@ var Microformats; // jshint ignore:line * @param {String} format ( Modules.ISODate profile format ) * @return {Object} Modules.ISODate */ - concatFragments(arr, format) { + concatFragments: function(arr, format) { var out = new modules.ISODate(), i = 0, value = ''; @@ -3721,7 +3721,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Array} Modules.ISODate */ - splitTimeAndZone( text ) { + splitTimeAndZone: function( text ) { var out = [text], chars = ['-', '+', 'z', 'Z'], i = chars.length; @@ -3762,7 +3762,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - parse(doc, node, textFormat) { + parse: function(doc, node, textFormat) { var out; this.textFormat = (textFormat) ? textFormat : this.textFormat; if (this.textFormat === 'normalised') { @@ -3784,7 +3784,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - parseText( doc, text, textFormat ) { + parseText: function( doc, text, textFormat ) { var node = modules.domUtils.createNodeWithText( 'div', text ); return this.parse( doc, node, textFormat ); }, @@ -3797,7 +3797,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - formatText( doc, text, textFormat ) { + formatText: function( doc, text, textFormat ) { this.textFormat = (textFormat) ? textFormat : this.textFormat; if (text) { var out = '', @@ -3821,7 +3821,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - normalise( doc, text ) { + normalise: function( doc, text ) { text = text.replace( / /g, ' ') ; // exchanges html entity for space into space char text = modules.utils.collapseWhiteSpace( text ); // removes linefeeds, tabs and addtional spaces text = modules.domUtils.decodeEntities( doc, text ); // decode HTML entities @@ -3836,7 +3836,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - walkTreeForText( node ) { + walkTreeForText: function( node ) { var out = '', j = 0; @@ -3882,7 +3882,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - parse( node ) { + parse: function( node ) { var out = '', j = 0; @@ -3907,7 +3907,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - walkTreeForHtml( node ) { + walkTreeForHtml: function( node ) { var out = '', j = 0; diff --git a/toolkit/components/narrate/NarrateControls.jsm b/toolkit/components/narrate/NarrateControls.jsm index 3ad889d82cc2..bfee9dd96ff5 100644 --- a/toolkit/components/narrate/NarrateControls.jsm +++ b/toolkit/components/narrate/NarrateControls.jsm @@ -137,7 +137,7 @@ function NarrateControls(mm, win, languagePromise) { } NarrateControls.prototype = { - handleEvent(evt) { + handleEvent: function(evt) { switch (evt.type) { case "change": if (evt.target.id == "narrate-rate-input") { @@ -163,7 +163,7 @@ NarrateControls.prototype = { /** * Returns true if synth voices are available. */ - _setupVoices() { + _setupVoices: function() { return this._languagePromise.then(language => { this.voiceSelect.clear(); let win = this._win; @@ -211,7 +211,7 @@ NarrateControls.prototype = { }); }, - _getVoicePref() { + _getVoicePref: function() { let voicePref = Services.prefs.getCharPref("narrate.voice"); try { return JSON.parse(voicePref); @@ -220,12 +220,12 @@ NarrateControls.prototype = { } }, - _onRateInput(evt) { + _onRateInput: function(evt) { AsyncPrefs.set("narrate.rate", parseInt(evt.target.value, 10)); this.narrator.setRate(this._convertRate(evt.target.value)); }, - _onVoiceChange() { + _onVoiceChange: function() { let voice = this.voice; this.narrator.setVoice(voice); this._languagePromise.then(language => { @@ -237,7 +237,7 @@ NarrateControls.prototype = { }); }, - _onButtonClick(evt) { + _onButtonClick: function(evt) { switch (evt.target.id) { case "narrate-skip-previous": this.narrator.skipPrevious(); @@ -262,7 +262,7 @@ NarrateControls.prototype = { } }, - _updateSpeechControls(speaking) { + _updateSpeechControls: function(speaking) { let dropdown = this._doc.getElementById("narrate-dropdown"); dropdown.classList.toggle("keep-open", speaking); dropdown.classList.toggle("speaking", speaking); @@ -281,7 +281,7 @@ NarrateControls.prototype = { } }, - _createVoiceLabel(voice) { + _createVoiceLabel: function(voice) { // This is a highly imperfect method of making human-readable labels // for system voices. Because each platform has a different naming scheme // for voices, we use a different method for each platform. @@ -304,7 +304,7 @@ NarrateControls.prototype = { } }, - _getLanguageName(lang) { + _getLanguageName: function(lang) { if (!this._langStrings) { this._langStrings = Services.strings.createBundle( "chrome://global/locale/languageNames.properties "); @@ -318,7 +318,7 @@ NarrateControls.prototype = { } }, - _convertRate(rate) { + _convertRate: function(rate) { // We need to convert a relative percentage value to a fraction rate value. // eg. -100 is half the speed, 100 is twice the speed in percentage, // 0.5 is half the speed and 2 is twice the speed in fractions. diff --git a/toolkit/components/narrate/Narrator.jsm b/toolkit/components/narrate/Narrator.jsm index 03bec2500cf0..4af9c7eed604 100644 --- a/toolkit/components/narrate/Narrator.jsm +++ b/toolkit/components/narrate/Narrator.jsm @@ -53,7 +53,7 @@ Narrator.prototype = { // For example, paragraphs. But nested anchors and other elements // are not interesting since their text already appears in their // parent's textContent. - acceptNode(node) { + acceptNode: function(node) { if (this._matches.has(node.parentNode)) { // Reject sub-trees of accepted nodes. return nf.FILTER_REJECT; @@ -106,7 +106,7 @@ Narrator.prototype = { this._win.speechSynthesis.pending; }, - _getVoice(voiceURI) { + _getVoice: function(voiceURI) { if (!this._voiceMap || !this._voiceMap.has(voiceURI)) { this._voiceMap = new Map( this._win.speechSynthesis.getVoices().map(v => [v.voiceURI, v])); @@ -115,7 +115,7 @@ Narrator.prototype = { return this._voiceMap.get(voiceURI); }, - _isParagraphInView(paragraph) { + _isParagraphInView: function(paragraph) { if (!paragraph) { return false; } @@ -124,13 +124,13 @@ Narrator.prototype = { return bb.top >= 0 && bb.top < this._win.innerHeight; }, - _sendTestEvent(eventType, detail) { + _sendTestEvent: function(eventType, detail) { let win = this._win; win.dispatchEvent(new win.CustomEvent(eventType, { detail: Cu.cloneInto(detail, win.document) })); }, - _speakInner() { + _speakInner: function() { this._win.speechSynthesis.cancel(); let tw = this._treeWalker; let paragraph = tw.currentNode; @@ -235,7 +235,7 @@ Narrator.prototype = { }); }, - start(speechOptions) { + start: function(speechOptions) { this._speechOptions = { rate: speechOptions.rate, voice: this._getVoice(speechOptions.voice) @@ -264,32 +264,32 @@ Narrator.prototype = { }); }, - stop() { + stop: function() { this._stopped = true; this._win.speechSynthesis.cancel(); }, - skipNext() { + skipNext: function() { this._win.speechSynthesis.cancel(); }, - skipPrevious() { + skipPrevious: function() { this._goBackParagraphs(this._timeIntoParagraph < PREV_THRESHOLD ? 2 : 1); }, - setRate(rate) { + setRate: function(rate) { this._speechOptions.rate = rate; /* repeat current paragraph */ this._goBackParagraphs(1); }, - setVoice(voice) { + setVoice: function(voice) { this._speechOptions.voice = this._getVoice(voice); /* repeat current paragraph */ this._goBackParagraphs(1); }, - _goBackParagraphs(count) { + _goBackParagraphs: function(count) { let tw = this._treeWalker; for (let i = 0; i < count; i++) { if (!tw.previousNode()) { @@ -316,7 +316,7 @@ Highlighter.prototype = { * @param {Number} startOffset the start offset * @param {Number} length the length in characters of the range */ - highlight(startOffset, length) { + highlight: function(startOffset, length) { let containerRect = this.container.getBoundingClientRect(); let range = this._getRange(startOffset, startOffset + length); let rangeRects = range.getClientRects(); @@ -362,7 +362,7 @@ Highlighter.prototype = { /** * Releases reference to container and removes all highlight nodes. */ - remove() { + remove: function() { for (let node of this._nodes) { node.remove(); } @@ -376,7 +376,7 @@ Highlighter.prototype = { * * @param {Number} count number of nodes needed */ - _getFreshHighlightNodes(count) { + _getFreshHighlightNodes: function(count) { let doc = this.container.ownerDocument; let nodes = Array.from(this._nodes); @@ -403,7 +403,7 @@ Highlighter.prototype = { * @param {Number} startOffset the start offset * @param {Number} endOffset the end offset */ - _getRange(startOffset, endOffset) { + _getRange: function(startOffset, endOffset) { let doc = this.container.ownerDocument; let i = 0; let treeWalker = doc.createTreeWalker( diff --git a/toolkit/components/narrate/VoiceSelect.jsm b/toolkit/components/narrate/VoiceSelect.jsm index 4d3ff82b9e24..b283a06b39f4 100644 --- a/toolkit/components/narrate/VoiceSelect.jsm +++ b/toolkit/components/narrate/VoiceSelect.jsm @@ -37,7 +37,7 @@ function VoiceSelect(win, label) { } VoiceSelect.prototype = { - add(label, value) { + add: function(label, value) { let option = this._doc.createElement("button"); option.dataset.value = value; option.classList.add("option"); @@ -48,7 +48,7 @@ VoiceSelect.prototype = { return option; }, - addOptions(options) { + addOptions: function(options) { let selected = null; for (let option of options) { if (option.selected) { @@ -61,11 +61,11 @@ VoiceSelect.prototype = { this._select(selected || this.options[0], true); }, - clear() { + clear: function() { this.listbox.innerHTML = ""; }, - toggleList(force, focus = true) { + toggleList: function(force, focus = true) { if (this.element.classList.toggle("open", force)) { if (focus) { (this.selected || this.options[0]).focus(); @@ -84,7 +84,7 @@ VoiceSelect.prototype = { } }, - handleEvent(evt) { + handleEvent: function(evt) { let target = evt.target; switch (evt.type) { @@ -131,7 +131,7 @@ VoiceSelect.prototype = { } }, - _getPagedOption(option, up) { + _getPagedOption: function(option, up) { let height = elem => elem.getBoundingClientRect().height; let listboxHeight = height(this.listbox); @@ -148,7 +148,7 @@ VoiceSelect.prototype = { return next; }, - _keyPressedButton(evt) { + _keyPressedButton: function(evt) { if (evt.altKey && (evt.key === "ArrowUp" || evt.key === "ArrowUp")) { this.toggleList(true); return; @@ -178,7 +178,7 @@ VoiceSelect.prototype = { } }, - _keyPressedInBox(evt) { + _keyPressedInBox: function(evt) { let toFocus; let cur = this._doc.activeElement; @@ -212,7 +212,7 @@ VoiceSelect.prototype = { } }, - _select(option, suppressEvent = false) { + _select: function(option, suppressEvent = false) { let oldSelected = this.selected; if (oldSelected) { oldSelected.removeAttribute("aria-selected"); @@ -233,7 +233,7 @@ VoiceSelect.prototype = { } }, - _updateDropdownHeight(now) { + _updateDropdownHeight: function(now) { let updateInner = () => { let winHeight = this._win.innerHeight; let listbox = this.listbox; @@ -252,7 +252,7 @@ VoiceSelect.prototype = { } }, - _getOptionFromValue(value) { + _getOptionFromValue: function(value) { return Array.from(this.options).find(o => o.dataset.value === value); }, diff --git a/toolkit/components/narrate/test/NarrateTestUtils.jsm b/toolkit/components/narrate/test/NarrateTestUtils.jsm index 227a7cf2b100..302e5c9928b8 100644 --- a/toolkit/components/narrate/test/NarrateTestUtils.jsm +++ b/toolkit/components/narrate/test/NarrateTestUtils.jsm @@ -24,7 +24,7 @@ this.NarrateTestUtils = { BACK: "#narrate-skip-previous", FORWARD: "#narrate-skip-next", - isVisible(element) { + isVisible: function(element) { let style = element.ownerDocument.defaultView.getComputedStyle(element, ""); if (style.display == "none") { return false; @@ -42,7 +42,7 @@ this.NarrateTestUtils = { return true; }, - isStoppedState(window, ok) { + isStoppedState: function(window, ok) { let $ = window.document.querySelector.bind(window.document); ok($(this.BACK).disabled, "back button is disabled"); ok($(this.FORWARD).disabled, "forward button is disabled"); @@ -52,7 +52,7 @@ this.NarrateTestUtils = { ok($(this.START).title == "Start", "Button tooltip is correct"); }, - isStartedState(window, ok) { + isStartedState: function(window, ok) { let $ = window.document.querySelector.bind(window.document); ok(!$(this.BACK).disabled, "back button is enabled"); ok(!$(this.FORWARD).disabled, "forward button is enabled"); @@ -62,7 +62,7 @@ this.NarrateTestUtils = { ok($(this.STOP).title == "Stop", "Button tooltip is correct"); }, - selectVoice(window, voiceUri) { + selectVoice: function(window, voiceUri) { if (!this.isVisible(window.document.querySelector(this.VOICE_OPTIONS))) { window.document.querySelector(this.VOICE_SELECT).click(); } @@ -76,11 +76,11 @@ this.NarrateTestUtils = { return voiceOption.classList.contains("selected"); }, - getEventUtils(window) { + getEventUtils: function(window) { let eventUtils = { "_EU_Ci": Components.interfaces, "_EU_Cc": Components.classes, - window, + window: window, parent: window, navigator: window.navigator, KeyboardEvent: window.KeyboardEvent, @@ -91,7 +91,7 @@ this.NarrateTestUtils = { return eventUtils; }, - getReaderReadyPromise(window) { + getReaderReadyPromise: function(window) { return new Promise(resolve => { function observeReady(subject, topic) { if (subject == window) { @@ -108,13 +108,13 @@ this.NarrateTestUtils = { }); }, - waitForNarrateToggle(window) { + waitForNarrateToggle: function(window) { let toggle = window.document.querySelector(this.TOGGLE); return ContentTaskUtils.waitForCondition( () => !toggle.hidden, ""); }, - waitForPrefChange(pref) { + waitForPrefChange: function(pref) { return new Promise(resolve => { function observeChange() { Services.prefs.removeObserver(pref, observeChange); @@ -125,18 +125,18 @@ this.NarrateTestUtils = { }); }, - sendBoundaryEvent(window, name, charIndex, charLength) { + sendBoundaryEvent: function(window, name, charIndex, charLength) { let detail = { type: "boundary", args: { name, charIndex, charLength } }; window.dispatchEvent(new window.CustomEvent("testsynthevent", - { detail })); + { detail: detail })); }, - isWordHighlightGone(window, ok) { + isWordHighlightGone: function(window, ok) { let $ = window.document.querySelector.bind(window.document); ok(!$(".narrate-word-highlight"), "No more word highlights exist"); }, - getWordHighlights(window) { + getWordHighlights: function(window) { let $$ = window.document.querySelectorAll.bind(window.document); let nodes = Array.from($$(".narrate-word-highlight")); return nodes.map(node => { diff --git a/toolkit/components/passwordmgr/LoginHelper.jsm b/toolkit/components/passwordmgr/LoginHelper.jsm index be0fc32aac73..f63832762138 100644 --- a/toolkit/components/passwordmgr/LoginHelper.jsm +++ b/toolkit/components/passwordmgr/LoginHelper.jsm @@ -517,7 +517,7 @@ this.LoginHelper = { } else { window.openDialog("chrome://passwordmgr/content/passwordManager.xul", "Toolkit:PasswordManager", "", - {filterString}); + {filterString : filterString}); } }, diff --git a/toolkit/components/passwordmgr/LoginImport.jsm b/toolkit/components/passwordmgr/LoginImport.jsm index 9d620dd43ade..8f4ce246b087 100644 --- a/toolkit/components/passwordmgr/LoginImport.jsm +++ b/toolkit/components/passwordmgr/LoginImport.jsm @@ -137,19 +137,19 @@ this.LoginImport.prototype = { this.store.data.logins.push({ id: this.store.data.nextId++, - hostname, - httpRealm, - formSubmitURL, - usernameField, - passwordField, - encryptedUsername, - encryptedPassword, - guid, - encType, - timeCreated, - timeLastUsed, - timePasswordChanged, - timesUsed, + hostname: hostname, + httpRealm: httpRealm, + formSubmitURL: formSubmitURL, + usernameField: usernameField, + passwordField: passwordField, + encryptedUsername: encryptedUsername, + encryptedPassword: encryptedPassword, + guid: guid, + encType: encType, + timeCreated: timeCreated, + timeLastUsed: timeLastUsed, + timePasswordChanged: timePasswordChanged, + timesUsed: timesUsed, }); } catch (ex) { Cu.reportError("Error importing login: " + ex); diff --git a/toolkit/components/passwordmgr/LoginManagerContent.jsm b/toolkit/components/passwordmgr/LoginManagerContent.jsm index 998b6c991181..c6926f2a713c 100644 --- a/toolkit/components/passwordmgr/LoginManagerContent.jsm +++ b/toolkit/components/passwordmgr/LoginManagerContent.jsm @@ -235,7 +235,7 @@ var LoginManagerContent = { let loginsFound = LoginHelper.vanillaObjectsToLogins(msg.data.logins); request.promise.resolve({ form: request.form, - loginsFound, + loginsFound: loginsFound, recipes: msg.data.recipes, }); break; @@ -276,10 +276,10 @@ var LoginManagerContent = { let messageManager = messageManagerFromWindow(win); // XXX Weak?? - let requestData = { form }; - let messageData = { formOrigin, - actionOrigin, - options }; + let requestData = { form: form }; + let messageData = { formOrigin: formOrigin, + actionOrigin: actionOrigin, + options: options }; return this._sendRequest(messageManager, requestData, "RemoteLogins:findLogins", @@ -306,14 +306,14 @@ var LoginManagerContent = { null; let requestData = {}; - let messageData = { formOrigin, - actionOrigin, + let messageData = { formOrigin: formOrigin, + actionOrigin: actionOrigin, searchString: aSearchString, - previousResult, + previousResult: previousResult, rect: aRect, isSecure: InsecurePasswordUtils.isFormSecure(form), isPasswordField: aElement.type == "password", - remote }; + remote: remote }; return this._sendRequest(messageManager, requestData, "RemoteLogins:autoCompleteLogins", @@ -608,7 +608,7 @@ var LoginManagerContent = { pwFields[pwFields.length] = { index : i, - element + element : element }; } @@ -881,8 +881,8 @@ var LoginManagerContent = { let openerTopWindow = win.opener ? win.opener.top : null; messageManager.sendAsyncMessage("RemoteLogins:onFormSubmit", - { hostname, - formSubmitURL, + { hostname: hostname, + formSubmitURL: formSubmitURL, usernameField: mockUsername, newPasswordField: mockPassword, oldPasswordField: mockOldPassword }, diff --git a/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm b/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm index 74a9bd8ca1a4..c5671a56905d 100644 --- a/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm +++ b/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm @@ -164,10 +164,10 @@ var LoginManagerContextMenu = { */ _fillTargetField(login, inputElement, browser, documentURI) { LoginManagerParent.fillForm({ - browser, + browser: browser, loginFormOrigin: documentURI.prePath, - login, - inputElement, + login: login, + inputElement: inputElement, }).catch(Cu.reportError); }, diff --git a/toolkit/components/passwordmgr/LoginManagerParent.jsm b/toolkit/components/passwordmgr/LoginManagerParent.jsm index 52ce73f239eb..ec951344c971 100644 --- a/toolkit/components/passwordmgr/LoginManagerParent.jsm +++ b/toolkit/components/passwordmgr/LoginManagerParent.jsm @@ -38,7 +38,7 @@ var LoginManagerParent = { */ _recipeManager: null, - init() { + init: function() { let mm = Cc["@mozilla.org/globalmessagemanager;1"] .getService(Ci.nsIMessageListenerManager); mm.addMessageListener("RemoteLogins:findLogins", this); @@ -57,7 +57,7 @@ var LoginManagerParent = { }); }, - receiveMessage(msg) { + receiveMessage: function(msg) { let data = msg.data; switch (msg.name) { case "RemoteLogins:findLogins": { @@ -156,7 +156,7 @@ var LoginManagerParent = { if (!showMasterPassword && !Services.logins.isLoggedIn) { try { target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId, + requestId: requestId, logins: [], recipes, }); @@ -175,14 +175,14 @@ var LoginManagerParent = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - observe(subject, topic, data) { + observe: function(subject, topic, data) { log("Got deferred sendLoginDataToChild notification:", topic); // Only run observer once. Services.obs.removeObserver(this, "passwordmgr-crypto-login"); Services.obs.removeObserver(this, "passwordmgr-crypto-loginCanceled"); if (topic == "passwordmgr-crypto-loginCanceled") { target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId, + requestId: requestId, logins: [], recipes, }); @@ -219,13 +219,13 @@ var LoginManagerParent = { // doesn't support structured cloning. var jsLogins = LoginHelper.loginsToVanillaObjects(logins); target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId, + requestId: requestId, logins: jsLogins, recipes, }); }), - doAutocompleteSearch({ formOrigin, actionOrigin, + doAutocompleteSearch: function({ formOrigin, actionOrigin, searchString, previousResult, rect, requestId, isSecure, isPasswordField, remote }, target) { @@ -283,12 +283,12 @@ var LoginManagerParent = { // doesn't support structured cloning. var jsLogins = LoginHelper.loginsToVanillaObjects(matchingLogins); target.messageManager.sendAsyncMessage("RemoteLogins:loginsAutoCompleted", { - requestId, + requestId: requestId, logins: jsLogins, }); }, - onFormSubmit(hostname, formSubmitURL, + onFormSubmit: function(hostname, formSubmitURL, usernameField, newPasswordField, oldPasswordField, openerTopWindow, target) { diff --git a/toolkit/components/passwordmgr/content/passwordManager.js b/toolkit/components/passwordmgr/content/passwordManager.js index 941fe8bdf390..3dbb499cc3ab 100644 --- a/toolkit/components/passwordmgr/content/passwordManager.js +++ b/toolkit/components/passwordmgr/content/passwordManager.js @@ -35,7 +35,7 @@ let removeAllButton; let signonsTree; let signonReloadDisplay = { - observe(subject, topic, data) { + observe: function(subject, topic, data) { if (topic == "passwordmgr-storage-changed") { switch (data) { case "addLogin": diff --git a/toolkit/components/passwordmgr/crypto-SDR.js b/toolkit/components/passwordmgr/crypto-SDR.js index d88e87d91140..82797bb0d844 100644 --- a/toolkit/components/passwordmgr/crypto-SDR.js +++ b/toolkit/components/passwordmgr/crypto-SDR.js @@ -37,14 +37,14 @@ LoginManagerCrypto_SDR.prototype = { return this.__utfConverter; }, - _utfConverterReset() { + _utfConverterReset : function() { this.__utfConverter = null; }, _uiBusy : false, - init() { + init : function() { // Check to see if the internal PKCS#11 token has been initialized. // If not, set a blank password. let tokenDB = Cc["@mozilla.org/security/pk11tokendb;1"]. @@ -66,7 +66,7 @@ LoginManagerCrypto_SDR.prototype = { * Returns the encrypted string, or throws an exception if there was a * problem. */ - encrypt(plainText) { + encrypt : function(plainText) { let cipherText = null; let wasLoggedIn = this.isLoggedIn; @@ -107,7 +107,7 @@ LoginManagerCrypto_SDR.prototype = { * Returns the decrypted string, or throws an exception if there was a * problem. */ - decrypt(cipherText) { + decrypt : function(cipherText) { let plainText = null; let wasLoggedIn = this.isLoggedIn; @@ -178,7 +178,7 @@ LoginManagerCrypto_SDR.prototype = { /* * _notifyObservers */ - _notifyObservers(topic) { + _notifyObservers : function(topic) { this.log("Prompted for a master password, notifying for " + topic); Services.obs.notifyObservers(null, topic, null); }, diff --git a/toolkit/components/passwordmgr/nsLoginInfo.js b/toolkit/components/passwordmgr/nsLoginInfo.js index 79ed276ce1e4..3baed81145ce 100644 --- a/toolkit/components/passwordmgr/nsLoginInfo.js +++ b/toolkit/components/passwordmgr/nsLoginInfo.js @@ -29,7 +29,7 @@ nsLoginInfo.prototype = { usernameField : null, passwordField : null, - init(aHostname, aFormSubmitURL, aHttpRealm, + init : function(aHostname, aFormSubmitURL, aHttpRealm, aUsername, aPassword, aUsernameField, aPasswordField) { this.hostname = aHostname; @@ -47,7 +47,7 @@ nsLoginInfo.prototype = { }); }, - equals(aLogin) { + equals : function(aLogin) { if (this.hostname != aLogin.hostname || this.formSubmitURL != aLogin.formSubmitURL || this.httpRealm != aLogin.httpRealm || @@ -60,7 +60,7 @@ nsLoginInfo.prototype = { return true; }, - clone() { + clone : function() { let clone = Cc["@mozilla.org/login-manager/loginInfo;1"]. createInstance(Ci.nsILoginInfo); clone.init(this.hostname, this.formSubmitURL, this.httpRealm, diff --git a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js index 971ff0afbef4..54c6f53d8c7d 100644 --- a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js +++ b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js @@ -46,7 +46,7 @@ LoginManagerPromptFactory.prototype = { _asyncPrompts : {}, _asyncPromptInProgress : false, - observe(subject, topic, data) { + observe : function(subject, topic, data) { this.log("Observed: " + topic); if (topic == "quit-application-granted") { this._cancelPendingPrompts(); @@ -60,13 +60,13 @@ LoginManagerPromptFactory.prototype = { } }, - getPrompt(aWindow, aIID) { + getPrompt : function(aWindow, aIID) { var prompt = new LoginManagerPrompter().QueryInterface(aIID); prompt.init(aWindow, this); return prompt; }, - _doAsyncPrompt() { + _doAsyncPrompt : function() { if (this._asyncPromptInProgress) { this.log("_doAsyncPrompt bypassed, already in progress"); return; @@ -115,7 +115,7 @@ LoginManagerPromptFactory.prototype = { var runnable = { cancel: false, - run() { + run : function() { var ok = false; if (!this.cancel) { try { @@ -185,7 +185,7 @@ LoginManagerPromptFactory.prototype = { }, - _cancelPendingPrompts() { + _cancelPendingPrompts : function() { this.log("Canceling all pending prompts..."); var asyncPrompts = this._asyncPrompts; this.__proto__._asyncPrompts = {}; @@ -321,7 +321,7 @@ LoginManagerPrompter.prototype = { * Wrapper around the prompt service prompt. Saving random fields here * doesn't really make sense and therefore isn't implemented. */ - prompt(aDialogTitle, aText, aPasswordRealm, + prompt : function(aDialogTitle, aText, aPasswordRealm, aSavePassword, aDefaultText, aResult) { if (aSavePassword != Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER) throw new Components.Exception("prompt only supports SAVE_PASSWORD_NEVER", @@ -342,7 +342,7 @@ LoginManagerPrompter.prototype = { * Looks up a username and password in the database. Will prompt the user * with a dialog, even if a username and password are found. */ - promptUsernameAndPassword(aDialogTitle, aText, aPasswordRealm, + promptUsernameAndPassword : function(aDialogTitle, aText, aPasswordRealm, aSavePassword, aUsername, aPassword) { this.log("===== promptUsernameAndPassword() called ====="); @@ -443,7 +443,7 @@ LoginManagerPrompter.prototype = { * with a dialog with a text field and ok/cancel buttons. If the user * allows it, then the password will be saved in the database. */ - promptPassword(aDialogTitle, aText, aPasswordRealm, + promptPassword : function(aDialogTitle, aText, aPasswordRealm, aSavePassword, aPassword) { this.log("===== promptPassword called() ====="); @@ -519,7 +519,7 @@ LoginManagerPrompter.prototype = { * arguments to let callers know the login can't be saved because we don't * know whether it's http or https. */ - _getRealmInfo(aRealmString) { + _getRealmInfo : function(aRealmString) { var httpRealm = /^.+ \(.+\)$/; if (httpRealm.test(aRealmString)) return [null, null, null]; @@ -547,7 +547,7 @@ LoginManagerPrompter.prototype = { * @param {int} aLevel * @param {nsIAuthInformation} aAuthInfo */ - promptAuth(aChannel, aLevel, aAuthInfo) { + promptAuth : function(aChannel, aLevel, aAuthInfo) { var selectedLogin = null; var checkbox = { value : false }; var checkboxLabel = null; @@ -678,7 +678,7 @@ LoginManagerPrompter.prototype = { return ok; }, - asyncPromptAuth(aChannel, aCallback, aContext, aLevel, aAuthInfo) { + asyncPromptAuth : function(aChannel, aCallback, aContext, aLevel, aAuthInfo) { var cancelable = null; try { @@ -731,7 +731,7 @@ LoginManagerPrompter.prototype = { /* ---------- nsILoginManagerPrompter prompts ---------- */ - init(aWindow = null, aFactory = null) { + init : function(aWindow = null, aFactory = null) { if (!aWindow) { // There may be no applicable window e.g. in a Sandbox or JSM. this._chromeWindow = null; @@ -759,7 +759,7 @@ LoginManagerPrompter.prototype = { this._opener = aOpener; }, - promptToSavePassword(aLogin) { + promptToSavePassword : function(aLogin) { this.log("promptToSavePassword"); var notifyObj = this._getPopupNote() || this._getNotifyBox(); if (notifyObj) @@ -771,7 +771,7 @@ LoginManagerPrompter.prototype = { /** * Displays a notification bar. */ - _showLoginNotification(aNotifyBox, aName, aText, aButtons) { + _showLoginNotification : function(aNotifyBox, aName, aText, aButtons) { var oldBar = aNotifyBox.getNotificationWithValue(aName); const priority = aNotifyBox.PRIORITY_INFO_MEDIUM; @@ -1014,7 +1014,7 @@ LoginManagerPrompter.prototype = { persistent: true, passwordNotificationType: type, hideClose: true, - eventCallback(topic) { + eventCallback: function(topic) { switch (topic) { case "showing": currentNotification = this; @@ -1072,7 +1072,7 @@ LoginManagerPrompter.prototype = { * @param aLogin * The login captured from the form. */ - _showSaveLoginNotification(aNotifyObj, aLogin) { + _showSaveLoginNotification : function(aNotifyObj, aLogin) { // Ugh. We can't use the strings from the popup window, because they // have the access key marked in the string (eg "Mo&zilla"), along // with some weird rules for handling access keys that do not occur @@ -1110,7 +1110,7 @@ LoginManagerPrompter.prototype = { label: rememberButtonText, accessKey: rememberButtonAccessKey, popup: null, - callback(aNotifyObj, aButton) { + callback: function(aNotifyObj, aButton) { pwmgr.addLogin(aLogin); } }, @@ -1120,7 +1120,7 @@ LoginManagerPrompter.prototype = { label: neverButtonText, accessKey: neverButtonAccessKey, popup: null, - callback(aNotifyObj, aButton) { + callback: function(aNotifyObj, aButton) { pwmgr.setLoginSavingEnabled(aLogin.hostname, false); } }, @@ -1130,7 +1130,7 @@ LoginManagerPrompter.prototype = { label: notNowButtonText, accessKey: notNowButtonAccessKey, popup: null, - callback() { /* NOP */ } + callback: function() { /* NOP */ } } ]; @@ -1141,7 +1141,7 @@ LoginManagerPrompter.prototype = { Services.obs.notifyObservers(aLogin, "passwordmgr-prompt-save", null); }, - _removeLoginNotifications() { + _removeLoginNotifications : function() { var popupNote = this._getPopupNote(); if (popupNote) popupNote = popupNote.getNotification("password"); @@ -1169,7 +1169,7 @@ LoginManagerPrompter.prototype = { * Called when we detect a new login in a form submission, * asks the user what to do. */ - _showSaveLoginDialog(aLogin) { + _showSaveLoginDialog : function(aLogin) { const buttonFlags = Ci.nsIPrompt.BUTTON_POS_1_DEFAULT + (Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_0) + (Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_1) + @@ -1292,7 +1292,7 @@ LoginManagerPrompter.prototype = { label: changeButtonText, accessKey: changeButtonAccessKey, popup: null, - callback(aNotifyObj, aButton) { + callback: function(aNotifyObj, aButton) { self._updateLogin(aOldLogin, aNewLogin); } }, @@ -1302,7 +1302,7 @@ LoginManagerPrompter.prototype = { label: dontChangeButtonText, accessKey: dontChangeButtonAccessKey, popup: null, - callback(aNotifyObj, aButton) { + callback: function(aNotifyObj, aButton) { // do nothing } } @@ -1361,7 +1361,7 @@ LoginManagerPrompter.prototype = { * * Note; XPCOM stupidity: |count| is just |logins.length|. */ - promptToChangePasswordWithUsernames(logins, count, aNewLogin) { + promptToChangePasswordWithUsernames : function(logins, count, aNewLogin) { this.log("promptToChangePasswordWithUsernames with count:", count); var usernames = logins.map(l => l.username); @@ -1419,7 +1419,7 @@ LoginManagerPrompter.prototype = { /** * Given a content DOM window, returns the chrome window and browser it's in. */ - _getChromeWindow(aWindow) { + _getChromeWindow: function(aWindow) { let windows = Services.wm.getEnumerator(null); while (windows.hasMoreElements()) { let win = windows.getNext(); @@ -1431,7 +1431,7 @@ LoginManagerPrompter.prototype = { return null; }, - _getNotifyWindow() { + _getNotifyWindow: function() { // Some sites pop up a temporary login window, which disappears // upon submission of credentials. We want to put the notification // bar in the opener window if this seems to be happening. @@ -1455,7 +1455,7 @@ LoginManagerPrompter.prototype = { * Returns the popup notification to this prompter, * or null if there isn't one available. */ - _getPopupNote() { + _getPopupNote : function() { let popupNote = null; try { @@ -1475,7 +1475,7 @@ LoginManagerPrompter.prototype = { * Returns the notification box to this prompter, or null if there isn't * a notification box available. */ - _getNotifyBox() { + _getNotifyBox : function() { let notifyBox = null; try { @@ -1496,7 +1496,7 @@ LoginManagerPrompter.prototype = { * is the same as some other existing login. So, pick a login with a * matching username, or return null. */ - _repickSelectedLogin(foundLogins, username) { + _repickSelectedLogin : function(foundLogins, username) { for (var i = 0; i < foundLogins.length; i++) if (foundLogins[i].username == username) return foundLogins[i]; @@ -1515,7 +1515,7 @@ LoginManagerPrompter.prototype = { * formatted if required. * */ - _getLocalizedString(key, formatArgs) { + _getLocalizedString : function(key, formatArgs) { if (formatArgs) return this._strBundle.formatStringFromName( key, formatArgs, formatArgs.length); @@ -1528,7 +1528,7 @@ LoginManagerPrompter.prototype = { * it's too long. This helps prevent an evil site from messing with the * "save password?" prompt too much. */ - _sanitizeUsername(username) { + _sanitizeUsername : function(username) { if (username.length > 30) { username = username.substring(0, 30); username += this._ellipsis; @@ -1543,7 +1543,7 @@ LoginManagerPrompter.prototype = { * Returns the hostname to use in a nsILoginInfo object (for example, * "http://example.com"). */ - _getFormattedHostname(aURI) { + _getFormattedHostname : function(aURI) { let uri; if (aURI instanceof Ci.nsIURI) { uri = aURI; @@ -1560,7 +1560,7 @@ LoginManagerPrompter.prototype = { * prompting purposes. Eg, "http://foo.com" --> "foo.com", or * "ftp://www.site.co.uk" --> "site.co.uk". */ - _getShortDisplayHost(aURIString) { + _getShortDisplayHost: function(aURIString) { var displayHost; var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"]. @@ -1586,7 +1586,7 @@ LoginManagerPrompter.prototype = { * Returns the hostname and realm for which authentication is being * requested, in the format expected to be used with nsILoginInfo. */ - _getAuthTarget(aChannel, aAuthInfo) { + _getAuthTarget : function(aChannel, aAuthInfo) { var hostname, realm; // If our proxy is demanding authentication, don't use the @@ -1634,7 +1634,7 @@ LoginManagerPrompter.prototype = { * If the authentication was for a Windows domain, we'll prepend the * return username with the domain. (eg, "domain\user") */ - _GetAuthInfo(aAuthInfo) { + _GetAuthInfo : function(aAuthInfo) { var username, password; var flags = aAuthInfo.flags; @@ -1654,7 +1654,7 @@ LoginManagerPrompter.prototype = { * domain out of the username if necessary and sets domain, username and * password on the auth information object. */ - _SetAuthInfo(aAuthInfo, username, password) { + _SetAuthInfo : function(aAuthInfo, username, password) { var flags = aAuthInfo.flags; if (flags & Ci.nsIAuthInformation.NEED_DOMAIN) { // Domain is separated from username by a backslash @@ -1671,12 +1671,12 @@ LoginManagerPrompter.prototype = { aAuthInfo.password = password; }, - _newAsyncPromptConsumer(aCallback, aContext) { + _newAsyncPromptConsumer : function(aCallback, aContext) { return { QueryInterface: XPCOMUtils.generateQI([Ci.nsICancelable]), callback: aCallback, context: aContext, - cancel() { + cancel: function() { this.callback.onAuthCancelled(this.context, false); this.callback = null; this.context = null; diff --git a/toolkit/components/passwordmgr/storage-json.js b/toolkit/components/passwordmgr/storage-json.js index bf9b13cc4e28..5bf75aab5071 100644 --- a/toolkit/components/passwordmgr/storage-json.js +++ b/toolkit/components/passwordmgr/storage-json.js @@ -141,7 +141,7 @@ this.LoginManagerStorage_json.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: loginClone.guid, - encType, + encType: encType, timeCreated: loginClone.timeCreated, timeLastUsed: loginClone.timeLastUsed, timePasswordChanged: loginClone.timePasswordChanged, @@ -377,9 +377,9 @@ this.LoginManagerStorage_json.prototype = { findLogins(count, hostname, formSubmitURL, httpRealm) { let loginData = { - hostname, - formSubmitURL, - httpRealm + hostname: hostname, + formSubmitURL: formSubmitURL, + httpRealm: httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) @@ -397,9 +397,9 @@ this.LoginManagerStorage_json.prototype = { countLogins(hostname, formSubmitURL, httpRealm) { let loginData = { - hostname, - formSubmitURL, - httpRealm + hostname: hostname, + formSubmitURL: formSubmitURL, + httpRealm: httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) diff --git a/toolkit/components/passwordmgr/storage-mozStorage.js b/toolkit/components/passwordmgr/storage-mozStorage.js index 54f640ae4f83..f1f1273c70c5 100644 --- a/toolkit/components/passwordmgr/storage-mozStorage.js +++ b/toolkit/components/passwordmgr/storage-mozStorage.js @@ -31,12 +31,12 @@ function Transaction(aDatabase) { } Transaction.prototype = { - commit() { + commit : function() { if (this._hasTransaction) this._db.commitTransaction(); }, - rollback() { + rollback : function() { if (this._hasTransaction) this._db.rollbackTransaction(); }, @@ -50,7 +50,7 @@ LoginManagerStorage_mozStorage.prototype = { classID : Components.ID("{8c2023b9-175c-477e-9761-44ae7b549756}"), QueryInterface : XPCOMUtils.generateQI([Ci.nsILoginManagerStorage, Ci.nsIInterfaceRequestor]), - getInterface(aIID) { + getInterface : function(aIID) { if (aIID.equals(Ci.nsIVariant)) { // Allows unwrapping the JavaScript object for regression tests. return this; @@ -155,7 +155,7 @@ LoginManagerStorage_mozStorage.prototype = { * Internal method used by regression tests only. It overrides the default * database location. */ - initWithFile(aDBFile) { + initWithFile : function(aDBFile) { if (aDBFile) this._signonsFile = aDBFile; @@ -163,7 +163,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - initialize() { + initialize : function() { this._dbStmts = {}; let isFirstRun; @@ -200,12 +200,12 @@ LoginManagerStorage_mozStorage.prototype = { * Internal method used by regression tests only. It is called before * replacing this storage module with a new instance. */ - terminate() { + terminate : function() { return Promise.resolve(); }, - addLogin(login) { + addLogin : function(login) { // Throws if there are bogus values. LoginHelper.checkLoginValues(login); @@ -254,7 +254,7 @@ LoginManagerStorage_mozStorage.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: loginClone.guid, - encType, + encType: encType, timeCreated: loginClone.timeCreated, timeLastUsed: loginClone.timeLastUsed, timePasswordChanged: loginClone.timePasswordChanged, @@ -280,7 +280,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - removeLogin(login) { + removeLogin : function(login) { let [idToDelete, storedLogin] = this._getIdForLogin(login); if (!idToDelete) throw new Error("No matching logins"); @@ -307,7 +307,7 @@ LoginManagerStorage_mozStorage.prototype = { LoginHelper.notifyStorageChanged("removeLogin", storedLogin); }, - modifyLogin(oldLogin, newLoginData) { + modifyLogin : function(oldLogin, newLoginData) { let [idToModify, oldStoredLogin] = this._getIdForLogin(oldLogin); if (!idToModify) throw new Error("No matching logins"); @@ -360,7 +360,7 @@ LoginManagerStorage_mozStorage.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: newLogin.guid, - encType, + encType: encType, timeCreated: newLogin.timeCreated, timeLastUsed: newLogin.timeLastUsed, timePasswordChanged: newLogin.timePasswordChanged, @@ -387,7 +387,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Returns an array of nsILoginInfo. */ - getAllLogins(count) { + getAllLogins : function(count) { let [logins, ids] = this._searchLogins({}); // decrypt entries for caller. @@ -406,7 +406,7 @@ LoginManagerStorage_mozStorage.prototype = { * * @return {nsILoginInfo[]} which are decrypted. */ - searchLogins(count, matchData) { + searchLogins : function(count, matchData) { let realMatchData = {}; let options = {}; // Convert nsIPropertyBag to normal JS object @@ -444,7 +444,7 @@ LoginManagerStorage_mozStorage.prototype = { * is an array of encrypted nsLoginInfo and ids is an array of associated * ids in the database. */ - _searchLogins(matchData, aOptions = { + _searchLogins : function(matchData, aOptions = { schemeUpgrades: false, }) { let conditions = [], params = {}; @@ -551,7 +551,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Moves a login to the deleted logins table */ - storeDeletedLogin(aLogin) { + storeDeletedLogin : function(aLogin) { let stmt = null; try { this.log("Storing " + aLogin.guid + " in deleted passwords\n"); @@ -572,7 +572,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Removes all logins from storage. */ - removeAllLogins() { + removeAllLogins : function() { this.log("Removing all logins"); let query; let stmt; @@ -600,11 +600,11 @@ LoginManagerStorage_mozStorage.prototype = { }, - findLogins(count, hostname, formSubmitURL, httpRealm) { + findLogins : function(count, hostname, formSubmitURL, httpRealm) { let loginData = { - hostname, - formSubmitURL, - httpRealm + hostname: hostname, + formSubmitURL: formSubmitURL, + httpRealm: httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) @@ -621,7 +621,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - countLogins(hostname, formSubmitURL, httpRealm) { + countLogins : function(hostname, formSubmitURL, httpRealm) { let _countLoginsHelper = (hostname, formSubmitURL, httpRealm) => { // Do checks for null and empty strings, adjust conditions and params @@ -670,7 +670,7 @@ LoginManagerStorage_mozStorage.prototype = { * found, both items will be null. The returned login contains the actual * stored login (useful for looking at the actual nsILoginMetaInfo values). */ - _getIdForLogin(login) { + _getIdForLogin : function(login) { let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) if (login[field] != '') @@ -705,7 +705,7 @@ LoginManagerStorage_mozStorage.prototype = { * statement being created. This fixes the cases where nulls are involved * and the empty string is supposed to be a wildcard match */ - _buildConditionsAndParams(hostname, formSubmitURL, httpRealm) { + _buildConditionsAndParams : function(hostname, formSubmitURL, httpRealm) { let conditions = [], params = {}; if (hostname == null) { @@ -736,9 +736,9 @@ LoginManagerStorage_mozStorage.prototype = { /** * Checks to see if the specified GUID already exists. */ - _isGuidUnique(guid) { + _isGuidUnique : function(guid) { let query = "SELECT COUNT(1) AS numLogins FROM moz_logins WHERE guid = :guid"; - let params = { guid }; + let params = { guid: guid }; let stmt, numLogins; try { @@ -761,7 +761,7 @@ LoginManagerStorage_mozStorage.prototype = { * Returns the encrypted username, password, and encrypton type for the specified * login. Can throw if the user cancels a master password entry. */ - _encryptLogin(login) { + _encryptLogin : function(login) { let encUsername = this._crypto.encrypt(login.username); let encPassword = this._crypto.encrypt(login.password); let encType = this._crypto.defaultEncType; @@ -781,7 +781,7 @@ LoginManagerStorage_mozStorage.prototype = { * to lose unencrypted entries (eg, because the user clicked Cancel * instead of entering their master password) */ - _decryptLogins(logins) { + _decryptLogins : function(logins) { let result = []; for (let login of logins) { @@ -809,7 +809,7 @@ LoginManagerStorage_mozStorage.prototype = { * Returns the wrapped statement for execution. Will use memoization * so that statements can be reused. */ - _dbCreateStatement(query, params) { + _dbCreateStatement : function(query, params) { let wrappedStmt = this._dbStmts[query]; // Memoize the statements if (!wrappedStmt) { @@ -829,7 +829,7 @@ LoginManagerStorage_mozStorage.prototype = { * Attempts to initialize the database. This creates the file if it doesn't * exist, performs any migrations, etc. Return if this is the first run. */ - _dbInit() { + _dbInit : function() { this.log("Initializing Database"); let isFirstRun = false; try { @@ -856,7 +856,7 @@ LoginManagerStorage_mozStorage.prototype = { return isFirstRun; }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { switch (topic) { case "profile-before-change": Services.obs.removeObserver(this, "profile-before-change"); @@ -865,27 +865,27 @@ LoginManagerStorage_mozStorage.prototype = { } }, - _dbCreate() { + _dbCreate: function() { this.log("Creating Database"); this._dbCreateSchema(); this._dbConnection.schemaVersion = DB_VERSION; }, - _dbCreateSchema() { + _dbCreateSchema : function() { this._dbCreateTables(); this._dbCreateIndices(); }, - _dbCreateTables() { + _dbCreateTables : function() { this.log("Creating Tables"); for (let name in this._dbSchema.tables) this._dbConnection.createTable(name, this._dbSchema.tables[name]); }, - _dbCreateIndices() { + _dbCreateIndices : function() { this.log("Creating Indices"); for (let name in this._dbSchema.indices) { let index = this._dbSchema.indices[name]; @@ -896,7 +896,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - _dbMigrate(oldVersion) { + _dbMigrate : function(oldVersion) { this.log("Attempting to migrate from version " + oldVersion); if (oldVersion > DB_VERSION) { @@ -943,7 +943,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 2 adds a GUID column. Existing logins are assigned a random GUID. */ - _dbMigrateToVersion2() { + _dbMigrateToVersion2 : function() { // Check to see if GUID column already exists, add if needed let query; if (!this._dbColumnExists("guid")) { @@ -975,7 +975,7 @@ LoginManagerStorage_mozStorage.prototype = { query = "UPDATE moz_logins SET guid = :guid WHERE id = :id"; for (let id of ids) { let params = { - id, + id: id, guid: this._uuidService.generateUUID().toString() }; @@ -997,7 +997,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 3 adds a encType column. */ - _dbMigrateToVersion3() { + _dbMigrateToVersion3 : function() { // Check to see if encType column already exists, add if needed let query; if (!this._dbColumnExists("encType")) { @@ -1057,7 +1057,7 @@ LoginManagerStorage_mozStorage.prototype = { * Version 4 adds timeCreated, timeLastUsed, timePasswordChanged, * and timesUsed columns */ - _dbMigrateToVersion4() { + _dbMigrateToVersion4 : function() { let query; // Add the new columns, if needed. for (let column of ["timeCreated", "timeLastUsed", "timePasswordChanged", "timesUsed"]) { @@ -1112,7 +1112,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 5 adds the moz_deleted_logins table */ - _dbMigrateToVersion5() { + _dbMigrateToVersion5 : function() { if (!this._dbConnection.tableExists("moz_deleted_logins")) { this._dbConnection.createTable("moz_deleted_logins", this._dbSchema.tables.moz_deleted_logins); } @@ -1122,7 +1122,7 @@ LoginManagerStorage_mozStorage.prototype = { * Version 6 migrates all the hosts from * moz_disabledHosts to the permission manager. */ - _dbMigrateToVersion6() { + _dbMigrateToVersion6 : function() { let disabledHosts = []; let query = "SELECT hostname FROM moz_disabledHosts"; let stmt; @@ -1158,7 +1158,7 @@ LoginManagerStorage_mozStorage.prototype = { * Sanity check to ensure that the columns this version of the code expects * are present in the DB we're using. */ - _dbAreExpectedColumnsPresent() { + _dbAreExpectedColumnsPresent : function() { let query = "SELECT " + "id, " + "hostname, " + @@ -1203,7 +1203,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Checks to see if the named column already exists. */ - _dbColumnExists(columnName) { + _dbColumnExists : function(columnName) { let query = "SELECT " + columnName + " FROM moz_logins"; try { let stmt = this._dbConnection.createStatement(query); @@ -1215,7 +1215,7 @@ LoginManagerStorage_mozStorage.prototype = { } }, - _dbClose() { + _dbClose : function() { this.log("Closing the DB connection."); // Finalize all statements to free memory, avoid errors later for (let query in this._dbStmts) { @@ -1238,7 +1238,7 @@ LoginManagerStorage_mozStorage.prototype = { * Called when database creation fails. Finalizes database statements, * closes the database connection, deletes the database file. */ - _dbCleanup(backup) { + _dbCleanup : function(backup) { this.log("Cleaning up DB file - close & remove & backup=" + backup); // Create backup file diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js index 0b04042e3482..f2255b32738d 100644 --- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js @@ -19,7 +19,7 @@ add_task(function* test() { let modifiedLogin; let testNumber = 0; let testObserver = { - observe(subject, topic, data) { + observe: function(subject, topic, data) { if (topic == "passwordmgr-dialog-updated") { switch (testNumber) { case 1: diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js index 4f841f042c34..efe7c26c5d7c 100644 --- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js @@ -12,7 +12,7 @@ add_task(function* test() { isnot(tab, gBrowser.selectedTab, "New tab shouldn't be selected"); let listener = { - onOpenWindow(window) { + onOpenWindow: function(window) { var domwindow = window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindow); waitForFocus(() => { @@ -25,7 +25,7 @@ add_task(function* test() { }, domwindow); }, - onCloseWindow() { + onCloseWindow: function() { } }; diff --git a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html index dc4acbd01cd1..65c79f3bb78b 100644 --- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html +++ b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html @@ -76,14 +76,14 @@ var startupComplete = new Promise(resolve => startupCompleteResolver = resolve); function proxyChannelListener() { } proxyChannelListener.prototype = { - onStartRequest(request, context) { + onStartRequest: function(request, context) { startupCompleteResolver(); }, - onStopRequest(request, context, status) { } + onStopRequest: function(request, context, status) { } }; var resolveCallback = SpecialPowers.wrapCallbackObject({ - QueryInterface(iid) { + QueryInterface : function(iid) { const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -91,7 +91,7 @@ var resolveCallback = SpecialPowers.wrapCallbackObject({ return this; }, - onProxyAvailable(req, uri, pi, status) { + onProxyAvailable : function(req, uri, pi, status) { initLogins(pi); // I'm cheating a bit here... We should probably do some magic foo to get diff --git a/toolkit/components/passwordmgr/test/prompt_common.js b/toolkit/components/passwordmgr/test/prompt_common.js index 6749ea4db6a2..a72e04ba28eb 100644 --- a/toolkit/components/passwordmgr/test/prompt_common.js +++ b/toolkit/components/passwordmgr/test/prompt_common.js @@ -26,7 +26,7 @@ function startCallbackTimer() { var observer = SpecialPowers.wrapCallbackObject({ - QueryInterface(iid) { + QueryInterface : function(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports, Ci.nsISupportsWeakReference]; @@ -35,7 +35,7 @@ var observer = SpecialPowers.wrapCallbackObject({ return this; }, - observe(subject, topic, data) { + observe : function(subject, topic, data) { var doc = getDialogDoc(); if (doc) handleDialog(doc, testNum); diff --git a/toolkit/components/passwordmgr/test/test_master_password.html b/toolkit/components/passwordmgr/test/test_master_password.html index 1b2d5f48194d..c8884811f7c6 100644 --- a/toolkit/components/passwordmgr/test/test_master_password.html +++ b/toolkit/components/passwordmgr/test/test_master_password.html @@ -128,7 +128,7 @@ function handleDialog(doc, testNumber) { } var outerWindowObserver = { - observe(id) { + observe: function(id) { SpecialPowers.removeObserver(outerWindowObserver, "outer-window-destroyed"); var func; if (testNum == 1) diff --git a/toolkit/components/passwordmgr/test/test_prompt_async.html b/toolkit/components/passwordmgr/test/test_prompt_async.html index 4cb08e0959b6..03bea611bc8f 100644 --- a/toolkit/components/passwordmgr/test/test_prompt_async.html +++ b/toolkit/components/passwordmgr/test/test_prompt_async.html @@ -39,7 +39,7 @@ windowsOpen : 0, windowsRegistered : 0, - QueryInterface(iid) { + QueryInterface : function(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -47,7 +47,7 @@ return this; }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { if (topic === "domwindowopened") { this.windowsOpen++; this.windowsRegistered++; @@ -59,14 +59,14 @@ } }, - shutdown() { + shutdown: function() { var observerService = SpecialPowers.Cc["@mozilla.org/observer-service;1"] .getService(Ci.nsIObserverService); observerService.removeObserver(this, "domwindowopened"); observerService.removeObserver(this, "domwindowclosed"); }, - reset() { + reset: function() { this.windowsOpen = 0; this.windowsRegistered = 0; } @@ -130,7 +130,7 @@ } var resolveCallback = SpecialPowers.wrapCallbackObject({ - QueryInterface(iid) { + QueryInterface : function(iid) { const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -138,7 +138,7 @@ return this; }, - onProxyAvailable(req, uri, pi, status) { + onProxyAvailable : function(req, uri, pi, status) { initLogins(pi); doTest(testNum); } diff --git a/toolkit/components/passwordmgr/test/unit/test_notifications.js b/toolkit/components/passwordmgr/test/unit/test_notifications.js index 0ff2253baa47..d564c766aa08 100644 --- a/toolkit/components/passwordmgr/test/unit/test_notifications.js +++ b/toolkit/components/passwordmgr/test/unit/test_notifications.js @@ -8,7 +8,7 @@ var expectedData; var TestObserver = { QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - observe(subject, topic, data) { + observe : function(subject, topic, data) { do_check_eq(topic, "passwordmgr-storage-changed"); do_check_eq(data, expectedNotification); diff --git a/toolkit/components/passwordmgr/test/unit/test_storage.js b/toolkit/components/passwordmgr/test/unit/test_storage.js index 09ec96131164..d65516d9b007 100644 --- a/toolkit/components/passwordmgr/test/unit/test_storage.js +++ b/toolkit/components/passwordmgr/test/unit/test_storage.js @@ -31,7 +31,7 @@ add_task(function* test_storage_addLogin_nonascii() // Store the strings "user" and "pass" using similarly looking glyphs. let loginInfo = TestData.formLogin({ - hostname, + hostname: hostname, formSubmitURL: hostname, username: String.fromCharCode(533, 537, 7570, 345), password: String.fromCharCode(421, 259, 349, 537), diff --git a/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js b/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js index 7b869ab6ebb3..36da8e8b72bb 100644 --- a/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js +++ b/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js @@ -35,7 +35,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: false, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -63,7 +63,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: false, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -95,7 +95,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: true, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -123,7 +123,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: true, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -155,7 +155,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: false, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -183,7 +183,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: false, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -211,7 +211,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: true, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -239,7 +239,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: true, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -267,7 +267,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: false, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -295,7 +295,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: false, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -327,7 +327,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: true, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -355,7 +355,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: true, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -387,7 +387,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: false, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -415,7 +415,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: false, - matchingLogins, + matchingLogins: matchingLogins, items: [] }, { @@ -423,7 +423,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: true, - matchingLogins, + matchingLogins: matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -451,7 +451,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: true, - matchingLogins, + matchingLogins: matchingLogins, items: [] }, ]; diff --git a/toolkit/components/perfmonitoring/AddonWatcher.jsm b/toolkit/components/perfmonitoring/AddonWatcher.jsm index b081f97e98d2..58decba85722 100644 --- a/toolkit/components/perfmonitoring/AddonWatcher.jsm +++ b/toolkit/components/perfmonitoring/AddonWatcher.jsm @@ -44,7 +44,7 @@ this.AddonWatcher = { */ TOPIC_SLOW_ADDON_DETECTED: "addon-watcher-detected-slow-addon", - init() { + init: function() { this._initializedTimeStamp = Cu.now(); try { @@ -58,7 +58,7 @@ this.AddonWatcher = { this._idleThreshold = Preferences.get("browser.addon-watch.deactivate-after-idle-ms", 3000); this.paused = false; }, - uninit() { + uninit: function() { this.paused = true; }, _initializedTimeStamp: 0, @@ -87,7 +87,7 @@ this.AddonWatcher = { * {number} latestNotificationTimeStamp The timestamp of the latest user notification * that this add-on is slow. */ - _getAlerts(addonId) { + _getAlerts: function(addonId) { let alerts = this._alerts.get(addonId); if (!alerts) { alerts = { @@ -100,7 +100,7 @@ this.AddonWatcher = { return alerts; }, _alerts: new Map(), - _onSlowAddons(addons) { + _onSlowAddons: function(addons) { try { if (IdleService.idleTime >= this._idleThreshold) { // The application is idle. Maybe the computer is sleeping, or maybe @@ -202,10 +202,10 @@ this.AddonWatcher = { } }, - ignoreAddonForSession(addonid) { + ignoreAddonForSession: function(addonid) { this._ignoreList.add(addonid); }, - ignoreAddonPermanently(addonid) { + ignoreAddonPermanently: function(addonid) { this._ignoreList.add(addonid); try { let ignoreList = JSON.parse(Preferences.get("browser.addon-watch.ignore", "[]")) diff --git a/toolkit/components/perfmonitoring/PerformanceStats.jsm b/toolkit/components/perfmonitoring/PerformanceStats.jsm index 155009bb2916..6b5fb117c49e 100644 --- a/toolkit/components/perfmonitoring/PerformanceStats.jsm +++ b/toolkit/components/perfmonitoring/PerformanceStats.jsm @@ -79,7 +79,7 @@ Probe.prototype = { * If the probe was inactive, activate it. Note that activating a probe * can incur a memory or performance cost. */ - acquire() { + acquire: function() { if (this._counter == 0) { this._impl.isActive = true; Process.broadcast("acquire", [this._name]); @@ -92,7 +92,7 @@ Probe.prototype = { * * If this was the last client for this probe, deactivate it. */ - release() { + release: function() { this._counter--; if (this._counter == 0) { try { @@ -117,7 +117,7 @@ Probe.prototype = { * @return {object} An object containing the data extracted from this * probe. Actual format depends on the probe. */ - extract(xpcom) { + extract: function(xpcom) { if (!this._impl.isActive) { throw new Error(`Probe is inactive: ${this._name}`); } @@ -130,7 +130,7 @@ Probe.prototype = { * * @return {true} If `a` and `b` hold identical values. */ - isEqual(a, b) { + isEqual: function(a, b) { if (a == null && b == null) { return true; } @@ -149,7 +149,7 @@ Probe.prototype = { * @return {object} An object representing `a - b`. If `b` is * `null`, this is `a`. */ - subtract(a, b) { + subtract: function(a, b) { if (a == null) { throw new TypeError(); } @@ -159,7 +159,7 @@ Probe.prototype = { return this._impl.subtract(a, b); }, - importChildCompartments(parent, children) { + importChildCompartments: function(parent, children) { if (!Array.isArray(children)) { throw new TypeError(); } @@ -176,7 +176,7 @@ Probe.prototype = { return this._name; }, - compose(stats) { + compose: function(stats) { if (!Array.isArray(stats)) { throw new TypeError(); } @@ -221,17 +221,17 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringJank; }, - extract(xpcom) { + extract: function(xpcom) { let durations = xpcom.getDurations(); return { totalUserTime: xpcom.totalUserTime, totalSystemTime: xpcom.totalSystemTime, totalCPUTime: xpcom.totalUserTime + xpcom.totalSystemTime, - durations, + durations: durations, longestDuration: lastNonZero(durations) } }, - isEqual(a, b) { + isEqual: function(a, b) { // invariant: `a` and `b` are both non-null if (a.totalUserTime != b.totalUserTime) { return false; @@ -246,7 +246,7 @@ var Probes = { } return true; }, - subtract(a, b) { + subtract: function(a, b) { // invariant: `a` and `b` are both non-null let result = { totalUserTime: a.totalUserTime - b.totalUserTime, @@ -261,8 +261,8 @@ var Probes = { result.longestDuration = lastNonZero(result.durations); return result; }, - importChildCompartments() { /* nothing to do */ }, - compose(stats) { + importChildCompartments: function() { /* nothing to do */ }, + compose: function(stats) { let result = { totalUserTime: 0, totalSystemTime: 0, @@ -298,21 +298,21 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringCPOW; }, - extract(xpcom) { + extract: function(xpcom) { return { totalCPOWTime: xpcom.totalCPOWTime }; }, - isEqual(a, b) { + isEqual: function(a, b) { return a.totalCPOWTime == b.totalCPOWTime; }, - subtract(a, b) { + subtract: function(a, b) { return { totalCPOWTime: a.totalCPOWTime - b.totalCPOWTime }; }, - importChildCompartments() { /* nothing to do */ }, - compose(stats) { + importChildCompartments: function() { /* nothing to do */ }, + compose: function(stats) { let totalCPOWTime = 0; for (let stat of stats) { totalCPOWTime += stat.totalCPOWTime; @@ -335,21 +335,21 @@ var Probes = { ticks: new Probe("ticks", { set isActive(x) { /* this probe cannot be deactivated */ }, get isActive() { return true; }, - extract(xpcom) { + extract: function(xpcom) { return { ticks: xpcom.ticks }; }, - isEqual(a, b) { + isEqual: function(a, b) { return a.ticks == b.ticks; }, - subtract(a, b) { + subtract: function(a, b) { return { ticks: a.ticks - b.ticks }; }, - importChildCompartments() { /* nothing to do */ }, - compose(stats) { + importChildCompartments: function() { /* nothing to do */ }, + compose: function(stats) { let ticks = 0; for (let stat of stats) { ticks += stat.ticks; @@ -365,19 +365,19 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringPerCompartment; }, - extract(xpcom) { + extract: function(xpcom) { return null; }, - isEqual(a, b) { + isEqual: function(a, b) { return true; }, - subtract(a, b) { + subtract: function(a, b) { return true; }, - importChildCompartments(parent, children) { + importChildCompartments: function(parent, children) { parent.children = children; }, - compose(stats) { + compose: function(stats) { return null; }, }), @@ -447,7 +447,7 @@ PerformanceMonitor.prototype = { * @return {Promise} * @resolve {Snapshot} */ - _checkBeforeSnapshot(options) { + _checkBeforeSnapshot: function(options) { if (!this._finalizer) { throw new Error("dispose() has already been called, this PerformanceMonitor is not usable anymore"); } @@ -472,11 +472,11 @@ PerformanceMonitor.prototype = { } return probes; }, - promiseContentSnapshot(options = null) { + promiseContentSnapshot: function(options = null) { this._checkBeforeSnapshot(options); return (new ProcessSnapshot(performanceStatsService.getSnapshot())); }, - promiseSnapshot(options = null) { + promiseSnapshot: function(options = null) { let probes = this._checkBeforeSnapshot(options); return Task.spawn(function*() { let childProcesses = yield Process.broadcastAndCollect("collect", {probeNames: probes.map(p => p.name)}); @@ -496,7 +496,7 @@ PerformanceMonitor.prototype = { * Releasing probes as soon as they are unused is a good idea, as some probes * cost CPU and/or memory. */ - dispose() { + dispose: function() { if (!this._finalizer) { return; } @@ -573,7 +573,7 @@ this.PerformanceStats = { /** * Create a monitor for observing a set of performance probes. */ - getMonitor(probes) { + getMonitor: function(probes) { return PerformanceMonitor.make(probes); } }; @@ -640,7 +640,7 @@ PerformanceDataLeaf.prototype = { * * @return `true` if `this` and `to` have equal values in all fields. */ - equals(to) { + equals: function(to) { if (!(to instanceof PerformanceDataLeaf)) { throw new TypeError(); } @@ -661,7 +661,7 @@ PerformanceDataLeaf.prototype = { * * @return {PerformanceDiff} The performance usage between `to` and `this`. */ - subtract(to = null) { + subtract: function(to = null) { return (new PerformanceDiffLeaf(this, to)); } }; @@ -673,7 +673,7 @@ function PerformanceData(timestamp) { this._timestamp = timestamp; } PerformanceData.prototype = { - addChild(stat) { + addChild: function(stat) { if (!(stat instanceof PerformanceDataLeaf)) { throw new TypeError(); // FIXME } @@ -684,7 +684,7 @@ PerformanceData.prototype = { this._all.push(stat); stat.owner = this; }, - setParent(stat) { + setParent: function(stat) { if (!(stat instanceof PerformanceDataLeaf)) { throw new TypeError(); // FIXME } @@ -695,7 +695,7 @@ PerformanceData.prototype = { this._all.push(stat); stat.owner = this; }, - equals(to) { + equals: function(to) { if (this._parent && !to._parent) { return false; } @@ -719,7 +719,7 @@ PerformanceData.prototype = { } return true; }, - subtract(to = null) { + subtract: function(to = null) { return (new PerformanceDiff(this, to)); }, get addonId() { @@ -767,7 +767,7 @@ function PerformanceDiff(current, old = null) { } } PerformanceDiff.prototype = { - toString() { + toString: function() { return `[PerformanceDiff] ${this.key}`; }, get windowIds() { @@ -924,7 +924,7 @@ var Process = { * * NOOP if we are in a child process. */ - broadcast(topic, payload) { + broadcast: function(topic, payload) { if (!this.loader) { return; } diff --git a/toolkit/components/perfmonitoring/PerformanceWatcher.jsm b/toolkit/components/perfmonitoring/PerformanceWatcher.jsm index 994c057c59f6..d0d034974967 100644 --- a/toolkit/components/perfmonitoring/PerformanceWatcher.jsm +++ b/toolkit/components/perfmonitoring/PerformanceWatcher.jsm @@ -95,20 +95,20 @@ ChildManager.prototype = { * Add a listener, which will be notified whenever a child process * reports a slow performance alert for this addon/window. */ - addListener(listener) { + addListener: function(listener) { this._listeners.add(listener); }, /** * Remove a listener. */ - removeListener(listener) { + removeListener: function(listener) { let deleted = this._listeners.delete(listener); if (!deleted) { throw new Error("Unknown listener"); } }, - listeners() { + listeners: function() { return this._listeners.values(); } }; @@ -216,7 +216,7 @@ function Observable(target) { } } Observable.prototype = { - addJankObserver(listener) { + addJankObserver: function(listener) { if (this._observers.has(listener)) { throw new TypeError(`Listener already registered for target ${this._key}`); } @@ -230,7 +230,7 @@ Observable.prototype = { this._process.addJankObserver(observer); }, - removeJankObserver(listener) { + removeJankObserver: function(listener) { let observer = this._observers.get(listener); if (!observer) { throw new TypeError(`No listener for target ${this._key}`); @@ -284,10 +284,10 @@ function Observer(listener) { this._listener = listener; } Observer.prototype = { - observe(...args) { + observe: function(...args) { this._listener(...args); }, - dispose() { + dispose: function() { this._monitor.dispose(); this.observe = function poison() { throw new Error("Internal error: I should have stopped receiving notifications"); @@ -350,14 +350,14 @@ this.PerformanceWatcher = { * If the listener listens to all add-ons/all webpages, it is triggered with * an array of {source, details}, as described above. */ - addPerformanceListener(target, listener) { + addPerformanceListener: function(target, listener) { if (typeof listener != "function") { throw new TypeError(); } let observable = Observable.get(target); observable.addJankObserver(listener); }, - removePerformanceListener(target, listener) { + removePerformanceListener: function(target, listener) { if (typeof listener != "function") { throw new TypeError(); } diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js b/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js index b7bc198e05b6..8b674937282f 100644 --- a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js +++ b/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js @@ -64,25 +64,25 @@ function frameScript() { // A variant of `Assert` that doesn't spam the logs // in case of success. var SilentAssert = { - equal(a, b, msg) { + equal: function(a, b, msg) { if (a == b) { return; } Assert.equal(a, b, msg); }, - notEqual(a, b, msg) { + notEqual: function(a, b, msg) { if (a != b) { return; } Assert.notEqual(a, b, msg); }, - ok(a, msg) { + ok: function(a, msg) { if (a) { return; } Assert.ok(a, msg); }, - leq(a, b, msg) { + leq: function(a, b, msg) { this.ok(a <= b, `${msg}: ${a} <= ${b}`); } }; diff --git a/toolkit/components/perfmonitoring/tests/browser/head.js b/toolkit/components/perfmonitoring/tests/browser/head.js index 85e2ca5f2bb0..92258fd1b9d6 100644 --- a/toolkit/components/perfmonitoring/tests/browser/head.js +++ b/toolkit/components/perfmonitoring/tests/browser/head.js @@ -45,7 +45,7 @@ CPUBurner.prototype = { } return false; }), - dispose() { + dispose: function() { info(`CPUBurner: Closing tab for ${this.url}\n`); gBrowser.removeTab(this.tab); } @@ -142,7 +142,7 @@ function AlertListener(accept, {register, unregister}) { register(); } AlertListener.prototype = { - unregister() { + unregister: function() { this.reset(); if (this._unregistered) { info(`head.js: No need to unregister, we're already unregistered.\n`); @@ -153,7 +153,7 @@ AlertListener.prototype = { this._unregister(); info(`head.js: Unregistration complete.\n`); }, - reset() { + reset: function() { this.triggered = false; this.result = null; }, @@ -181,7 +181,7 @@ function AddonBurner(addonId = "fake add-on id: " + Math.random()) { } AddonBurner.prototype = Object.create(CPUBurner.prototype); Object.defineProperty(AddonBurner.prototype, "addonId", { - get() { + get: function() { return this._addonId; } }); diff --git a/toolkit/components/places/BookmarkHTMLUtils.jsm b/toolkit/components/places/BookmarkHTMLUtils.jsm index 10db007368c6..5aff75e9d084 100644 --- a/toolkit/components/places/BookmarkHTMLUtils.jsm +++ b/toolkit/components/places/BookmarkHTMLUtils.jsm @@ -1037,19 +1037,19 @@ BookmarkExporter.prototype = { _converterOut: null, - _write(aText) { + _write: function(aText) { this._converterOut.writeString(aText || ""); }, - _writeAttribute(aName, aValue) { + _writeAttribute: function(aName, aValue) { this._write(' ' + aName + '="' + aValue + '"'); }, - _writeLine(aText) { + _writeLine: function(aText) { this._write(aText + "\n"); }, - _writeHeader() { + _writeHeader: function() { this._writeLine(""); this._writeLine(" a nsIURI which represents the url to launch - _launchExternalUrl: function(aURL) { + _launchExternalUrl(aURL) { var extProtocolSvc = Cc["@mozilla.org/uriloader/external-protocol-service;1"] .getService(Ci.nsIExternalProtocolService); @@ -6504,7 +6504,7 @@ function AddKeywordForSearchField() { PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" , uri: makeURI(bookmarkData.spec) - , title: title + , title , description: bookmarkData.description , keyword: "" , postData: bookmarkData.postData @@ -6840,7 +6840,7 @@ var gIdentityHandler = { * Handler for mouseclicks on the "More Information" button in the * "identity-popup" panel. */ - handleMoreInfoClick : function(event) { + handleMoreInfoClick(event) { displaySecurityInfo(); event.stopPropagation(); this._identityPopup.hidePopup(); @@ -6898,7 +6898,7 @@ var gIdentityHandler = { * Helper to parse out the important parts of _sslStatus (of the SSL cert in * particular) for use in constructing identity UI strings */ - getIdentityData : function() { + getIdentityData() { var result = {}; var cert = this._sslStatus.serverCert; @@ -6999,7 +6999,7 @@ var gIdentityHandler = { /** * Attempt to provide proper IDN treatment for host names */ - getEffectiveHost: function() { + getEffectiveHost() { if (!this._IDNService) this._IDNService = Cc["@mozilla.org/network/idn-service;1"] .getService(Ci.nsIIDNService); @@ -7179,7 +7179,7 @@ var gIdentityHandler = { let buttons = [{ label: gNavigatorBundle.getString("revokeOverride.label"), accessKey: gNavigatorBundle.getString("revokeOverride.accesskey"), - callback: function(aNotification, aButton) { + callback(aNotification, aButton) { try { let weakCryptoOverride = Cc["@mozilla.org/security/weakcryptooverride;1"] .getService(Ci.nsIWeakCryptoOverride); @@ -7369,7 +7369,7 @@ var gIdentityHandler = { /** * Click handler for the identity-box element in primary chrome. */ - handleIdentityButtonEvent : function(event) { + handleIdentityButtonEvent(event) { event.stopPropagation(); if ((event.type == "click" && event.button != 0) || @@ -7430,7 +7430,7 @@ var gIdentityHandler = { } }, - onDragStart: function(event) { + onDragStart(event) { if (gURLBar.getAttribute("pageproxystate") != "valid") return; @@ -7446,12 +7446,12 @@ var gIdentityHandler = { dt.setDragImage(this._identityIcon, 16, 16); }, - onLocationChange: function() { + onLocationChange() { this._permissionJustRemoved = false; this.updatePermissionHint(); }, - updatePermissionHint: function() { + updatePermissionHint() { if (!this._permissionList.hasChildNodes() && !this._permissionJustRemoved) { this._permissionEmptyHint.removeAttribute("hidden"); } else { @@ -7465,7 +7465,7 @@ var gIdentityHandler = { } }, - updateSitePermissions: function() { + updateSitePermissions() { while (this._permissionList.hasChildNodes()) this._permissionList.removeChild(this._permissionList.lastChild); @@ -7504,7 +7504,7 @@ var gIdentityHandler = { this.updatePermissionHint(); }, - _handleHeightChange: function(aFunction, aWillShowReloadHint) { + _handleHeightChange(aFunction, aWillShowReloadHint) { let heightBefore = getComputedStyle(this._permissionList).height; aFunction(); let heightAfter = getComputedStyle(this._permissionList).height; @@ -7518,7 +7518,7 @@ var gIdentityHandler = { this._identityPopupMultiView.setHeightToFit(heightChange); }, - _createPermissionItem: function(aPermission) { + _createPermissionItem(aPermission) { let container = document.createElement("hbox"); container.setAttribute("class", "identity-popup-permission-item"); container.setAttribute("align", "center"); @@ -7681,7 +7681,7 @@ var gPrivateBrowsingUI = { }; var gRemoteTabsUI = { - init: function() { + init() { if (window.location.href != getBrowserURL() && // Also check hidden window for the Mac no-window case window.location.href != "chrome://browser/content/hiddenWindow.xul") { @@ -7828,7 +7828,7 @@ function switchToTabHavingURI(aURI, aOpenNew, aOpenParams = {}) { } var RestoreLastSessionObserver = { - init: function() { + init() { if (SessionStore.canRestoreLastSession && !PrivateBrowsingUtils.isWindowPrivate(window)) { Services.obs.addObserver(this, "sessionstore-last-session-cleared", true); @@ -7836,7 +7836,7 @@ var RestoreLastSessionObserver = { } }, - observe: function() { + observe() { // The last session can only be restored once so there's // no way we need to re-enable our menu item. Services.obs.removeObserver(this, "sessionstore-last-session-cleared"); @@ -8047,7 +8047,7 @@ var MousePosTracker = { return this._windowUtils = window.getInterface(Ci.nsIDOMWindowUtils); }, - addListener: function(listener) { + addListener(listener) { if (this._listeners.has(listener)) return; @@ -8057,11 +8057,11 @@ var MousePosTracker = { this._callListener(listener); }, - removeListener: function(listener) { + removeListener(listener) { this._listeners.delete(listener); }, - handleEvent: function(event) { + handleEvent(event) { var fullZoom = this._windowUtils.fullZoom; this._x = event.screenX / fullZoom - window.mozInnerScreenX; this._y = event.screenY / fullZoom - window.mozInnerScreenY; @@ -8075,7 +8075,7 @@ var MousePosTracker = { }, this); }, - _callListener: function(listener) { + _callListener(listener) { let rect = listener.getMouseTargetRect(); let hover = this._x >= rect.left && this._x <= rect.right && @@ -8097,7 +8097,7 @@ var MousePosTracker = { }; var ToolbarIconColor = { - init: function() { + init() { this._initialized = true; window.addEventListener("activate", this); @@ -8111,7 +8111,7 @@ var ToolbarIconColor = { this.inferFromText(); }, - uninit: function() { + uninit() { this._initialized = false; window.removeEventListener("activate", this); @@ -8119,7 +8119,7 @@ var ToolbarIconColor = { Services.obs.removeObserver(this, "lightweight-theme-styling-update"); }, - handleEvent: function(event) { + handleEvent(event) { switch (event.type) { case "activate": case "deactivate": @@ -8128,7 +8128,7 @@ var ToolbarIconColor = { } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "lightweight-theme-styling-update": // inferFromText needs to run after LightweightThemeConsumer.jsm's @@ -8138,7 +8138,7 @@ var ToolbarIconColor = { } }, - inferFromText: function() { + inferFromText() { if (!this._initialized) return; @@ -8172,14 +8172,14 @@ var ToolbarIconColor = { } var PanicButtonNotifier = { - init: function() { + init() { this._initialized = true; if (window.PanicButtonNotifierShouldNotify) { delete window.PanicButtonNotifierShouldNotify; this.notify(); } }, - notify: function() { + notify() { if (!this._initialized) { window.PanicButtonNotifierShouldNotify = true; return; @@ -8196,14 +8196,14 @@ var PanicButtonNotifier = { Cu.reportError(ex); } }, - close: function() { + close() { let popup = document.getElementById("panic-button-success-notification"); popup.hidePopup(); }, }; var AboutPrivateBrowsingListener = { - init: function() { + init() { window.messageManager.addMessageListener( "AboutPrivateBrowsing:OpenPrivateWindow", msg => { diff --git a/browser/base/content/content.js b/browser/base/content/content.js index c5e1c0ec1451..837cd5863b80 100644 --- a/browser/base/content/content.js +++ b/browser/base/content/content.js @@ -103,8 +103,8 @@ var handleContentContextMenu = function(event) { let addonInfo = {}; let subject = { - event: event, - addonInfo: addonInfo, + event, + addonInfo, }; subject.wrappedJSObject = subject; Services.obs.notifyObservers(subject, "content-contextmenu", null); @@ -197,18 +197,18 @@ var handleContentContextMenu = function(event) { let mainWin = browser.ownerGlobal; mainWin.gContextMenuContentData = { isRemote: false, - event: event, + event, popupNode: event.target, - browser: browser, - addonInfo: addonInfo, + browser, + addonInfo, documentURIObject: doc.documentURIObject, - docLocation: docLocation, - charSet: charSet, - referrer: referrer, - referrerPolicy: referrerPolicy, - contentType: contentType, - contentDisposition: contentDisposition, - selectionInfo: selectionInfo, + docLocation, + charSet, + referrer, + referrerPolicy, + contentType, + contentDisposition, + selectionInfo, disableSetDesktopBackground: disableSetDesktopBg, loginFillInfo, parentAllowsMixedContent, @@ -262,7 +262,7 @@ function getSerializedSecurityInfo(docShell) { } var AboutNetAndCertErrorListener = { - init: function(chromeGlobal) { + init(chromeGlobal) { addMessageListener("CertErrorDetails", this); addMessageListener("Browser:CaptivePortalFreed", this); chromeGlobal.addEventListener('AboutNetErrorLoad', this, false, true); @@ -280,7 +280,7 @@ var AboutNetAndCertErrorListener = { return content.document.documentURI.startsWith("about:certerror"); }, - receiveMessage: function(msg) { + receiveMessage(msg) { if (!this.isAboutCertError) { return; } @@ -348,7 +348,7 @@ var AboutNetAndCertErrorListener = { content.dispatchEvent(new content.CustomEvent("AboutNetErrorCaptivePortalFreed")); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (!this.isAboutNetError && !this.isAboutCertError) { return; } @@ -372,7 +372,7 @@ var AboutNetAndCertErrorListener = { } }, - changedCertPrefs: function() { + changedCertPrefs() { for (let prefName of PREF_SSL_IMPACT) { if (Services.prefs.prefHasUserValue(prefName)) { return true; @@ -382,7 +382,7 @@ var AboutNetAndCertErrorListener = { return false; }, - onPageLoad: function(evt) { + onPageLoad(evt) { if (this.isAboutCertError) { let originalTarget = evt.originalTarget; let ownerDoc = originalTarget.ownerDocument; @@ -394,7 +394,7 @@ var AboutNetAndCertErrorListener = { detail: JSON.stringify({ enabled: Services.prefs.getBoolPref("security.ssl.errorReporting.enabled"), changedCertPrefs: this.changedCertPrefs(), - automatic: automatic + automatic }) })); @@ -402,16 +402,16 @@ var AboutNetAndCertErrorListener = { {reportStatus: TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN}); }, - openCaptivePortalPage: function(evt) { + openCaptivePortalPage(evt) { sendAsyncMessage("Browser:OpenCaptivePortalPage"); }, - onResetPreferences: function(evt) { + onResetPreferences(evt) { sendAsyncMessage("Browser:ResetSSLPreferences"); }, - onSetAutomatic: function(evt) { + onSetAutomatic(evt) { sendAsyncMessage("Browser:SetSSLErrorReportAuto", { automatic: evt.detail }); @@ -427,7 +427,7 @@ var AboutNetAndCertErrorListener = { } }, - onOverride: function(evt) { + onOverride(evt) { let {host, port} = content.document.mozDocumentURIIfNotForErrorPages; sendAsyncMessage("Browser:OverrideWeakCrypto", { uri: {host, port} }); } @@ -443,7 +443,7 @@ var ClickEventHandler = { .addSystemEventListener(global, "click", this, true); }, - handleEvent: function(event) { + handleEvent(event) { if (!event.isTrusted || event.defaultPrevented || event.button == 2) { return; } @@ -484,7 +484,7 @@ var ClickEventHandler = { let json = { button: event.button, shiftKey: event.shiftKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, href: null, title: null, - bookmark: false, referrerPolicy: referrerPolicy, + bookmark: false, referrerPolicy, originAttributes: principal ? principal.originAttributes : {}, isContentWindowPrivate: PrivateBrowsingUtils.isContentWindowPrivate(ownerDoc.defaultView)}; @@ -535,7 +535,7 @@ var ClickEventHandler = { } }, - onCertError: function(targetElement, ownerDoc) { + onCertError(targetElement, ownerDoc) { let docShell = ownerDoc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShell); @@ -547,7 +547,7 @@ var ClickEventHandler = { }); }, - onAboutBlocked: function(targetElement, ownerDoc) { + onAboutBlocked(targetElement, ownerDoc) { var reason = 'phishing'; if (/e=malwareBlocked/.test(ownerDoc.documentURI)) { reason = 'malware'; @@ -556,13 +556,13 @@ var ClickEventHandler = { } sendAsyncMessage("Browser:SiteBlockedError", { location: ownerDoc.location.href, - reason: reason, + reason, elementId: targetElement.getAttribute("id"), isTopFrame: (ownerDoc.defaultView.parent === ownerDoc.defaultView) }); }, - onAboutNetError: function(event, documentURI) { + onAboutNetError(event, documentURI) { let elmId = event.originalTarget.getAttribute("id"); if (elmId == "returnButton") { sendAsyncMessage("Browser:SSLErrorGoBack", {}); @@ -591,7 +591,7 @@ var ClickEventHandler = { * element. This includes SVG links, because callers expect |node| * to behave like an element, which SVG links (XLink) don't. */ - _hrefAndLinkNodeForClickEvent: function(event) { + _hrefAndLinkNodeForClickEvent(event) { function isHTMLLink(aNode) { // Be consistent with what nsContextMenu.js does. return ((aNode instanceof content.HTMLAnchorElement && aNode.href) || @@ -656,7 +656,7 @@ addMessageListener("webrtc:StartBrowserSharing", () => { let windowID = content.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils).outerWindowID; sendAsyncMessage("webrtc:response:StartBrowserSharing", { - windowID: windowID + windowID }); }); @@ -876,20 +876,20 @@ addMessageListener("Bookmarks:GetPageDetails", (message) => { let doc = content.document; let isErrorPage = /^about:(neterror|certerror|blocked)/.test(doc.documentURI); sendAsyncMessage("Bookmarks:GetPageDetails:Result", - { isErrorPage: isErrorPage, + { isErrorPage, description: PlacesUIUtils.getDescriptionFromDocument(doc) }); }); var LightWeightThemeWebInstallListener = { _previewWindow: null, - init: function() { + init() { addEventListener("InstallBrowserTheme", this, false, true); addEventListener("PreviewBrowserTheme", this, false, true); addEventListener("ResetBrowserThemePreview", this, false, true); }, - handleEvent: function(event) { + handleEvent(event) { switch (event.type) { case "InstallBrowserTheme": { sendAsyncMessage("LightWeightThemeWebInstaller:Install", { @@ -923,7 +923,7 @@ var LightWeightThemeWebInstallListener = { } }, - _resetPreviewWindow: function() { + _resetPreviewWindow() { this._previewWindow.removeEventListener("pagehide", this, true); this._previewWindow = null; } @@ -982,11 +982,11 @@ addMessageListener("ContextMenu:SetAsDesktopBackground", (message) => { var PageInfoListener = { - init: function() { + init() { addMessageListener("PageInfo:getData", this); }, - receiveMessage: function(message) { + receiveMessage(message) { let strings = message.data.strings; let window; let document; @@ -1017,7 +1017,7 @@ var PageInfoListener = { this.getMediaInfo(document, window, strings); }, - getImageInfo: function(imageElement) { + getImageInfo(imageElement) { let imageInfo = null; if (imageElement) { imageInfo = { @@ -1030,7 +1030,7 @@ var PageInfoListener = { return imageInfo; }, - getMetaInfo: function(document) { + getMetaInfo(document) { let metaViewRows = []; // Get the meta tags from the page. @@ -1044,7 +1044,7 @@ var PageInfoListener = { return metaViewRows; }, - getWindowInfo: function(window) { + getWindowInfo(window) { let windowInfo = {}; windowInfo.isTopWindow = window == window.top; @@ -1058,7 +1058,7 @@ var PageInfoListener = { return windowInfo; }, - getDocumentInfo: function(document) { + getDocumentInfo(document) { let docInfo = {}; docInfo.title = document.title; docInfo.location = document.location.toString(); @@ -1079,7 +1079,7 @@ var PageInfoListener = { return docInfo; }, - getFeedsInfo: function(document, strings) { + getFeedsInfo(document, strings) { let feeds = []; // Get the feeds from the page. let linkNodes = document.getElementsByTagName("link"); @@ -1110,13 +1110,13 @@ var PageInfoListener = { }, // Only called once to get the media tab's media elements from the content page. - getMediaInfo: function(document, window, strings) + getMediaInfo(document, window, strings) { let frameList = this.goThroughFrames(document, window); Task.spawn(() => this.processFrames(document, frameList, strings)); }, - goThroughFrames: function(document, window) + goThroughFrames(document, window) { let frameList = [document]; if (window && window.frames.length > 0) { @@ -1130,7 +1130,7 @@ var PageInfoListener = { return frameList; }, - processFrames: function*(document, frameList, strings) + *processFrames(document, frameList, strings) { let nodeCount = 0; for (let doc of frameList) { @@ -1155,7 +1155,7 @@ var PageInfoListener = { sendAsyncMessage("PageInfo:mediaData", {isComplete: true}); }, - getMediaItems: function(document, strings, elem) + getMediaItems(document, strings, elem) { // Check for images defined in CSS (e.g. background, borders) let computedStyle = elem.ownerGlobal.getComputedStyle(elem); @@ -1241,7 +1241,7 @@ var PageInfoListener = { * makePreview in pageInfo.js uses to figure out how to display the preview. */ - serializeElementInfo: function(document, url, type, alt, item, isBG) + serializeElementInfo(document, url, type, alt, item, isBG) { let result = {}; @@ -1322,7 +1322,7 @@ var PageInfoListener = { // Other Misc Stuff // Modified from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html // parse a node to extract the contents of the node - getValueText: function(node) + getValueText(node) { let valueText = ""; @@ -1362,7 +1362,7 @@ var PageInfoListener = { // Copied from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html. // Traverse the tree in search of an img or area element and grab its alt tag. - getAltText: function(node) + getAltText(node) { let altText = ""; @@ -1380,7 +1380,7 @@ var PageInfoListener = { // Copied from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html. // Strip leading and trailing whitespace, and replace multiple consecutive whitespace characters with a single space. - stripWS: function(text) + stripWS(text) { let middleRE = /\s+/g; let endRE = /(^\s+)|(\s+$)/g; diff --git a/browser/base/content/contentSearchUI.js b/browser/base/content/contentSearchUI.js index 688d8b1cfe4b..d3f8d5f143ce 100644 --- a/browser/base/content/contentSearchUI.js +++ b/browser/base/content/contentSearchUI.js @@ -90,7 +90,7 @@ ContentSearchUIController.prototype = { } this._defaultEngine = { name: engine.name, - icon: icon, + icon, }; this._updateDefaultEngineHeader(); @@ -189,7 +189,7 @@ ContentSearchUIController.prototype = { return this._suggestionsList.children.length; }, - selectAndUpdateInput: function(idx) { + selectAndUpdateInput(idx) { this.selectedIndex = idx; let newValue = this.suggestionAtIndex(idx) || this._stickyInputValue; // Setting the input value when the value has not changed commits the current @@ -200,12 +200,12 @@ ContentSearchUIController.prototype = { this._updateSearchWithHeader(); }, - suggestionAtIndex: function(idx) { + suggestionAtIndex(idx) { let row = this._suggestionsList.children[idx]; return row ? row.textContent : null; }, - deleteSuggestionAtIndex: function(idx) { + deleteSuggestionAtIndex(idx) { // Only form history suggestions can be deleted. if (this.isFormHistorySuggestionAtIndex(idx)) { let suggestionStr = this.suggestionAtIndex(idx); @@ -215,20 +215,20 @@ ContentSearchUIController.prototype = { } }, - isFormHistorySuggestionAtIndex: function(idx) { + isFormHistorySuggestionAtIndex(idx) { let row = this._suggestionsList.children[idx]; return row && row.classList.contains("formHistory"); }, - addInputValueToFormHistory: function() { + addInputValueToFormHistory() { this._sendMsg("AddFormHistoryEntry", this.input.value); }, - handleEvent: function(event) { + handleEvent(event) { this["_on" + event.type[0].toUpperCase() + event.type.substr(1)](event); }, - _onCommand: function(aEvent) { + _onCommand(aEvent) { if (this.selectedButtonIndex == this._oneOffButtons.length) { // Settings button was selected. this._sendMsg("ManageEngines"); @@ -242,7 +242,7 @@ ContentSearchUIController.prototype = { } }, - search: function(aEvent) { + search(aEvent) { if (!this.defaultEngine) { return; // Not initialized yet. } @@ -291,7 +291,7 @@ ContentSearchUIController.prototype = { this.addInputValueToFormHistory(); }, - _onInput: function() { + _onInput() { if (!this.input.value) { this._stickyInputValue = ""; this._hideSuggestions(); @@ -304,7 +304,7 @@ ContentSearchUIController.prototype = { this._updateSearchWithHeader(); }, - _onKeypress: function(event) { + _onKeypress(event) { let selectedIndexDelta = 0; let selectedSuggestionDelta = 0; let selectedOneOffDelta = 0; @@ -451,7 +451,7 @@ ContentSearchUIController.prototype = { }, _currentEngineIndex: -1, - _cycleCurrentEngine: function(aReverse) { + _cycleCurrentEngine(aReverse) { if ((this._currentEngineIndex == this._engines.length - 1 && !aReverse) || (this._currentEngineIndex == 0 && aReverse)) { return; @@ -461,7 +461,7 @@ ContentSearchUIController.prototype = { this._sendMsg("SetCurrentEngine", engineName); }, - _onFocus: function() { + _onFocus() { if (this._mousedown) { return; } @@ -474,7 +474,7 @@ ContentSearchUIController.prototype = { this._speculativeConnect(); }, - _onBlur: function() { + _onBlur() { if (this._mousedown) { // At this point, this.input has lost focus, but a new element has not yet // received it. If we re-focus this.input directly, the new element will @@ -486,7 +486,7 @@ ContentSearchUIController.prototype = { this._hideSuggestions(); }, - _onMousemove: function(event) { + _onMousemove(event) { let idx = this._indexOfTableItem(event.target); if (idx >= this.numSuggestions) { this.selectedButtonIndex = idx - this.numSuggestions; @@ -495,14 +495,14 @@ ContentSearchUIController.prototype = { this.selectedIndex = idx; }, - _onMouseup: function(event) { + _onMouseup(event) { if (event.button == 2) { return; } this._onCommand(event); }, - _onMouseout: function(event) { + _onMouseout(event) { // We only deselect one-off buttons and the settings button when they are // moused out. let idx = this._indexOfTableItem(event.originalTarget); @@ -511,22 +511,22 @@ ContentSearchUIController.prototype = { } }, - _onClick: function(event) { + _onClick(event) { this._onMouseup(event); }, - _onContentSearchService: function(event) { + _onContentSearchService(event) { let methodName = "_onMsg" + event.detail.type; if (methodName in this) { this[methodName](event.detail.data); } }, - _onMsgFocusInput: function(event) { + _onMsgFocusInput(event) { this.input.focus(); }, - _onMsgSuggestions: function(suggestions) { + _onMsgSuggestions(suggestions) { // Ignore the suggestions if their search string or engine doesn't match // ours. Due to the async nature of message passing, this can easily happen // when the user types quickly. @@ -581,13 +581,13 @@ ContentSearchUIController.prototype = { } }, - _onMsgSuggestionsCancelled: function() { + _onMsgSuggestionsCancelled() { if (!this._table.hidden) { this._hideSuggestions(); } }, - _onMsgState: function(state) { + _onMsgState(state) { this.engines = state.engines; // No point updating the default engine (and the header) if there's no change. if (this.defaultEngine && @@ -598,16 +598,16 @@ ContentSearchUIController.prototype = { this.defaultEngine = state.currentEngine; }, - _onMsgCurrentState: function(state) { + _onMsgCurrentState(state) { this._onMsgState(state); }, - _onMsgCurrentEngine: function(engine) { + _onMsgCurrentEngine(engine) { this.defaultEngine = engine; this._pendingOneOffRefresh = true; }, - _onMsgStrings: function(strings) { + _onMsgStrings(strings) { this._strings = strings; this._updateDefaultEngineHeader(); this._updateSearchWithHeader(); @@ -616,7 +616,7 @@ ContentSearchUIController.prototype = { this.input.setAttribute("placeholder", this._strings.searchPlaceholder); }, - _updateDefaultEngineHeader: function() { + _updateDefaultEngineHeader() { let header = document.getElementById("contentSearchDefaultEngineHeader"); header.firstChild.setAttribute("src", this.defaultEngine.icon); if (!this._strings) { @@ -629,7 +629,7 @@ ContentSearchUIController.prototype = { this._strings.searchHeader.replace("%S", this.defaultEngine.name))); }, - _updateSearchWithHeader: function() { + _updateSearchWithHeader() { if (!this._strings) { return; } @@ -642,13 +642,13 @@ ContentSearchUIController.prototype = { } }, - _speculativeConnect: function() { + _speculativeConnect() { if (this.defaultEngine) { this._sendMsg("SpeculativeConnect", this.defaultEngine.name); } }, - _makeTableRow: function(type, suggestionStr, currentRow, searchWords) { + _makeTableRow(type, suggestionStr, currentRow, searchWords) { let row = document.createElementNS(HTML_NS, "tr"); row.dir = "auto"; row.classList.add("contentSearchSuggestionRow"); @@ -685,28 +685,28 @@ ContentSearchUIController.prototype = { }, // Converts favicon array buffer into a data URI. - _getFaviconURIFromBuffer: function(buffer) { + _getFaviconURIFromBuffer(buffer) { let blob = new Blob([buffer]); return URL.createObjectURL(blob); }, // Adds "@2x" to the name of the given PNG url for "retina" screens. - _getImageURIForCurrentResolution: function(uri) { + _getImageURIForCurrentResolution(uri) { if (window.devicePixelRatio > 1) { return uri.replace(/\.png$/, "@2x.png"); } return uri; }, - _getSearchEngines: function() { + _getSearchEngines() { this._sendMsg("GetState"); }, - _getStrings: function() { + _getStrings() { this._sendMsg("GetStrings"); }, - _getSuggestions: function() { + _getSuggestions() { this._stickyInputValue = this.input.value; if (this.defaultEngine) { this._sendMsg("GetSuggestions", { @@ -716,13 +716,13 @@ ContentSearchUIController.prototype = { } }, - _clearSuggestionRows: function() { + _clearSuggestionRows() { while (this._suggestionsList.firstElementChild) { this._suggestionsList.firstElementChild.remove(); } }, - _hideSuggestions: function() { + _hideSuggestions() { this.input.setAttribute("aria-expanded", "false"); this.selectedIndex = -1; this.selectedButtonIndex = -1; @@ -730,7 +730,7 @@ ContentSearchUIController.prototype = { this._table.hidden = true; }, - _indexOfTableItem: function(elt) { + _indexOfTableItem(elt) { if (elt.classList.contains("contentSearchOneOffItem")) { return this.numSuggestions + this._oneOffButtons.indexOf(elt); } @@ -746,7 +746,7 @@ ContentSearchUIController.prototype = { return elt.rowIndex; }, - _makeTable: function(id) { + _makeTable(id) { this._table = document.createElementNS(HTML_NS, "table"); this._table.id = id; this._table.hidden = true; @@ -815,7 +815,7 @@ ContentSearchUIController.prototype = { return this._table; }, - _setUpOneOffButtons: function() { + _setUpOneOffButtons() { // Sometimes we receive a CurrentEngine message from the ContentSearch service // before we've received a State message - i.e. before we have our engines. if (!this._engines) { @@ -896,11 +896,11 @@ ContentSearchUIController.prototype = { this._oneOffsTable.hidden = false; }, - _sendMsg: function(type, data = null) { + _sendMsg(type, data = null) { dispatchEvent(new CustomEvent("ContentSearchClient", { detail: { - type: type, - data: data, + type, + data, }, })); }, diff --git a/browser/base/content/pageinfo/pageInfo.js b/browser/base/content/pageinfo/pageInfo.js index 1e96c4e8b632..dd4336951248 100644 --- a/browser/base/content/pageinfo/pageInfo.js +++ b/browser/base/content/pageinfo/pageInfo.js @@ -24,12 +24,12 @@ pageInfoTreeView.prototype = { set rowCount(c) { throw "rowCount is a readonly property"; }, get rowCount() { return this.rows; }, - setTree: function(tree) + setTree(tree) { this.tree = tree; }, - getCellText: function(row, column) + getCellText(row, column) { // row can be null, but js arrays are 0-indexed. // colidx cannot be null, but can be larger than the number @@ -38,16 +38,16 @@ pageInfoTreeView.prototype = { return this.data[row][column.index] || ""; }, - setCellValue: function(row, column, value) + setCellValue(row, column, value) { }, - setCellText: function(row, column, value) + setCellText(row, column, value) { this.data[row][column.index] = value; }, - addRow: function(row) + addRow(row) { this.rows = this.data.push(row); this.rowCountChanged(this.rows - 1, 1); @@ -56,24 +56,24 @@ pageInfoTreeView.prototype = { } }, - addRows: function(rows) + addRows(rows) { for (let row of rows) { this.addRow(row); } }, - rowCountChanged: function(index, count) + rowCountChanged(index, count) { this.tree.rowCountChanged(index, count); }, - invalidate: function() + invalidate() { this.tree.invalidate(); }, - clear: function() + clear() { if (this.tree) this.tree.rowCountChanged(0, -this.rows); @@ -81,12 +81,12 @@ pageInfoTreeView.prototype = { this.data = [ ]; }, - handleCopy: function(row) + handleCopy(row) { return (row < 0 || this.copycol < 0) ? "" : (this.data[row][this.copycol] || ""); }, - performActionOnRow: function(action, row) + performActionOnRow(action, row) { if (action == "copy") { var data = this.handleCopy(row) @@ -94,7 +94,7 @@ pageInfoTreeView.prototype = { } }, - onPageMediaSort : function(columnname) + onPageMediaSort(columnname) { var tree = document.getElementById(this.treeid); var treecol = tree.columns.getNamedColumn(columnname); @@ -121,29 +121,29 @@ pageInfoTreeView.prototype = { this.sortcol = treecol.index; }, - getRowProperties: function(row) { return ""; }, - getCellProperties: function(row, column) { return ""; }, - getColumnProperties: function(column) { return ""; }, - isContainer: function(index) { return false; }, - isContainerOpen: function(index) { return false; }, - isSeparator: function(index) { return false; }, - isSorted: function() { return this.sortcol > -1 }, - canDrop: function(index, orientation) { return false; }, - drop: function(row, orientation) { return false; }, - getParentIndex: function(index) { return 0; }, - hasNextSibling: function(index, after) { return false; }, - getLevel: function(index) { return 0; }, - getImageSrc: function(row, column) { }, - getProgressMode: function(row, column) { }, - getCellValue: function(row, column) { }, - toggleOpenState: function(index) { }, - cycleHeader: function(col) { }, - selectionChanged: function() { }, - cycleCell: function(row, column) { }, - isEditable: function(row, column) { return false; }, - isSelectable: function(row, column) { return false; }, - performAction: function(action) { }, - performActionOnCell: function(action, row, column) { } + getRowProperties(row) { return ""; }, + getCellProperties(row, column) { return ""; }, + getColumnProperties(column) { return ""; }, + isContainer(index) { return false; }, + isContainerOpen(index) { return false; }, + isSeparator(index) { return false; }, + isSorted() { return this.sortcol > -1 }, + canDrop(index, orientation) { return false; }, + drop(row, orientation) { return false; }, + getParentIndex(index) { return 0; }, + hasNextSibling(index, after) { return false; }, + getLevel(index) { return 0; }, + getImageSrc(row, column) { }, + getProgressMode(row, column) { }, + getCellValue(row, column) { }, + toggleOpenState(index) { }, + cycleHeader(col) { }, + selectionChanged() { }, + cycleCell(row, column) { }, + isEditable(row, column) { return false; }, + isSelectable(row, column) { return false; }, + performAction(action) { }, + performActionOnCell(action, row, column) { } }; // mmm, yummy. global variables. @@ -359,7 +359,7 @@ function loadPageInfo(frameOuterWindowID, imageElement, browser) // Look for pageInfoListener in content.js. Sends message to listener with arguments. mm.sendAsyncMessage("PageInfo:getData", {strings: gStrings, - frameOuterWindowID: frameOuterWindowID}, + frameOuterWindowID}, { imageElement }); let pageInfoData; @@ -517,10 +517,10 @@ function toggleGroupbox(id) function openCacheEntry(key, cb) { var checkCacheListener = { - onCacheEntryCheck: function(entry, appCache) { + onCacheEntryCheck(entry, appCache) { return Components.interfaces.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable: function(entry, isNew, appCache, status) { + onCacheEntryAvailable(entry, isNew, appCache, status) { cb(entry); } }; @@ -1004,7 +1004,7 @@ function makeBlockImage(url) } var imagePermissionObserver = { - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { if (document.getElementById("mediaPreviewBox").collapsed) return; diff --git a/browser/base/content/pageinfo/permissions.js b/browser/base/content/pageinfo/permissions.js index b3e1720dc544..5a563c035e97 100644 --- a/browser/base/content/pageinfo/permissions.js +++ b/browser/base/content/pageinfo/permissions.js @@ -20,7 +20,7 @@ var gPermissions = SitePermissions.listPermissions().sort((a, b) => { gPermissions.push("plugins"); var permissionObserver = { - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { var permission = aSubject.QueryInterface(Components.interfaces.nsIPermission); diff --git a/browser/base/content/pageinfo/security.js b/browser/base/content/pageinfo/security.js index 2638cb13d76e..e3f0fdc886b9 100644 --- a/browser/base/content/pageinfo/security.js +++ b/browser/base/content/pageinfo/security.js @@ -9,18 +9,18 @@ XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper", "resource://gre/modules/LoginHelper.jsm"); var security = { - init: function(uri, windowInfo) { + init(uri, windowInfo) { this.uri = uri; this.windowInfo = windowInfo; }, // Display the server certificate (static) - viewCert : function() { + viewCert() { var cert = security._cert; viewCertHelper(window, cert); }, - _getSecurityInfo : function() { + _getSecurityInfo() { const nsISSLStatusProvider = Components.interfaces.nsISSLStatusProvider; const nsISSLStatus = Components.interfaces.nsISSLStatus; @@ -54,15 +54,15 @@ var security = { this.mapIssuerOrganization(cert.issuerOrganization) || cert.issuerName; var retval = { - hostName : hostName, + hostName, cAName : issuerName, encryptionAlgorithm : undefined, encryptionStrength : undefined, version: undefined, - isBroken : isBroken, - isMixed : isMixed, - isEV : isEV, - cert : cert, + isBroken, + isMixed, + isEV, + cert, certificateTransparency : undefined }; @@ -117,21 +117,21 @@ var security = { return retval; } return { - hostName : hostName, + hostName, cAName : "", encryptionAlgorithm : "", encryptionStrength : 0, version: "", - isBroken : isBroken, - isMixed : isMixed, - isEV : isEV, + isBroken, + isMixed, + isEV, cert : null, certificateTransparency : null }; }, // Find the secureBrowserUI object (if present) - _getSecurityUI : function() { + _getSecurityUI() { if (window.opener.gBrowser) return window.opener.gBrowser.securityUI; return null; @@ -140,7 +140,7 @@ var security = { // Interface for mapping a certificate issuer organization to // the value to be displayed. // Bug 82017 - this implementation should be moved to pipnss C++ code - mapIssuerOrganization: function(name) { + mapIssuerOrganization(name) { if (!name) return null; if (name == "RSA Data Security, Inc.") return "Verisign, Inc."; @@ -152,7 +152,7 @@ var security = { /** * Open the cookie manager window */ - viewCookies : function() + viewCookies() { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); @@ -181,7 +181,7 @@ var security = { /** * Open the login manager window */ - viewPasswords : function() { + viewPasswords() { LoginHelper.openPasswordManager(window, this._getSecurityInfo().hostName); }, diff --git a/browser/base/content/sanitize.js b/browser/base/content/sanitize.js index 725daa64ed5a..53cf4e943d37 100644 --- a/browser/base/content/sanitize.js +++ b/browser/base/content/sanitize.js @@ -38,14 +38,14 @@ function Sanitizer() { } Sanitizer.prototype = { // warning to the caller: this one may raise an exception (e.g. bug #265028) - clearItem: function(aItemName) + clearItem(aItemName) { this.items[aItemName].clear(); }, prefDomain: "", - getNameFromPreference: function(aPreferenceName) + getNameFromPreference(aPreferenceName) { return aPreferenceName.substr(this.prefDomain.length); }, @@ -516,7 +516,7 @@ Sanitizer.prototype = { openWindows: { privateStateForNewWindow: "non-private", - _canCloseWindow: function(aWindow) { + _canCloseWindow(aWindow) { if (aWindow.CanCloseWindow()) { // We already showed PermitUnload for the window, so let's // make sure we don't do it again when we actually close the @@ -526,7 +526,7 @@ Sanitizer.prototype = { } return false; }, - _resetAllWindowClosures: function(aWindowList) { + _resetAllWindowClosures(aWindowList) { for (let win of aWindowList) { win.skipNextCanClose = false; } diff --git a/browser/base/content/social-content.js b/browser/base/content/social-content.js index b5fa6a5c4bda..071d057d522c 100644 --- a/browser/base/content/social-content.js +++ b/browser/base/content/social-content.js @@ -114,7 +114,7 @@ const SocialErrorListener = { webNav.loadURI(url, null, null, null, null); } sendAsyncMessage("Social:ErrorPageNotify", { - origin: origin, + origin, url: src }); }, diff --git a/browser/base/content/sync/aboutSyncTabs.js b/browser/base/content/sync/aboutSyncTabs.js index e49411c7434f..731a0edfee81 100644 --- a/browser/base/content/sync/aboutSyncTabs.js +++ b/browser/base/content/sync/aboutSyncTabs.js @@ -23,7 +23,7 @@ if (AppConstants.MOZ_SERVICES_CLOUDSYNC) { var RemoteTabViewer = { _tabsList: null, - init: function() { + init() { Services.obs.addObserver(this, "weave:service:login:finish", false); Services.obs.addObserver(this, "weave:engine:sync:finish", false); @@ -34,14 +34,14 @@ var RemoteTabViewer = { this.buildList(true); }, - uninit: function() { + uninit() { Services.obs.removeObserver(this, "weave:service:login:finish"); Services.obs.removeObserver(this, "weave:engine:sync:finish"); Services.obs.removeObserver(this, "cloudsync:tabs:update"); }, - createItem: function(attrs) { + createItem(attrs) { let item = document.createElement("richlistitem"); // Copy the attributes from the argument into the item. @@ -56,7 +56,7 @@ var RemoteTabViewer = { return item; }, - filterTabs: function(event) { + filterTabs(event) { let val = event.target.value.toLowerCase(); let numTabs = this._tabsList.getRowCount(); let clientTabs = 0; @@ -89,7 +89,7 @@ var RemoteTabViewer = { } }, - openSelected: function() { + openSelected() { let items = this._tabsList.selectedItems; let urls = []; for (let i = 0; i < items.length; i++) { @@ -105,14 +105,14 @@ var RemoteTabViewer = { } }, - bookmarkSingleTab: function() { + bookmarkSingleTab() { let item = this._tabsList.selectedItems[0]; let uri = Weave.Utils.makeURI(item.getAttribute("url")); let title = item.getAttribute("title"); PlacesUIUtils.showBookmarkDialog({ action: "add" , type: "bookmark" - , uri: uri - , title: title + , uri + , title , hiddenRows: [ "description" , "location" , "loadInSidebar" @@ -120,7 +120,7 @@ var RemoteTabViewer = { }, window.top); }, - bookmarkSelectedTabs: function() { + bookmarkSelectedTabs() { let items = this._tabsList.selectedItems; let URIs = []; for (let i = 0; i < items.length; i++) { @@ -142,7 +142,7 @@ var RemoteTabViewer = { } }, - getIcon: function(iconUri, defaultIcon) { + getIcon(iconUri, defaultIcon) { try { let iconURI = Weave.Utils.makeURI(iconUri); return PlacesUtils.favicons.getFaviconLinkForIcon(iconURI).spec; @@ -158,7 +158,7 @@ var RemoteTabViewer = { _buildListRequested: false, - buildList: function(forceSync) { + buildList(forceSync) { if (this._waitingForBuildList) { this._buildListRequested = true; return; @@ -192,7 +192,7 @@ var RemoteTabViewer = { } }, - _clearTabList: function() { + _clearTabList() { let list = this._tabsList; // Clear out existing richlistitems. @@ -204,7 +204,7 @@ var RemoteTabViewer = { } }, - _generateWeaveTabList: function() { + _generateWeaveTabList() { let engine = Weave.Service.engineManager.get("tabs"); let list = this._tabsList; @@ -236,7 +236,7 @@ var RemoteTabViewer = { let attrs = { type: "tab", title: title || url, - url: url, + url, icon: this.getIcon(icon), } let tab = this.createItem(attrs); @@ -245,7 +245,7 @@ var RemoteTabViewer = { } }, - _generateCloudSyncTabList: function() { + _generateCloudSyncTabList() { let updateTabList = function(remoteTabs) { let list = this._tabsList; @@ -275,7 +275,7 @@ var RemoteTabViewer = { .then(updateTabList, Promise.reject.bind(Promise)); }, - adjustContextMenu: function(event) { + adjustContextMenu(event) { let mode = "all"; switch (this._tabsList.selectedItems.length) { case 0: @@ -300,7 +300,7 @@ var RemoteTabViewer = { } }, - _refetchTabs: function(force) { + _refetchTabs(force) { if (!force) { // Don't bother refetching tabs if we already did so recently let lastFetch = 0; @@ -325,7 +325,7 @@ var RemoteTabViewer = { return true; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "weave:service:login:finish": // A login has finished, which means that a Sync is about to start and @@ -346,7 +346,7 @@ var RemoteTabViewer = { } }, - handleClick: function(event) { + handleClick(event) { if (event.target.getAttribute("type") != "tab") { return; } diff --git a/browser/base/content/sync/genericChange.js b/browser/base/content/sync/genericChange.js index a9571b662f6d..5828e5dbb900 100644 --- a/browser/base/content/sync/genericChange.js +++ b/browser/base/content/sync/genericChange.js @@ -136,7 +136,7 @@ var Change = { window.setTimeout(window.close, 1500); }, - onDialogAccept: function() { + onDialogAccept() { switch (this._dialogType) { case "UpdatePassphrase": case "ResetPassphrase": @@ -147,7 +147,7 @@ var Change = { return undefined; }, - doGeneratePassphrase: function() { + doGeneratePassphrase() { let passphrase = Weave.Utils.generatePassphrase(); this._passphraseBox.value = Weave.Utils.hyphenatePassphrase(passphrase); this._dialog.getButton("finish").disabled = false; @@ -201,7 +201,7 @@ var Change = { return false; }, - validate: function(event) { + validate(event) { let valid = false; let errorString = ""; diff --git a/browser/base/content/sync/setup.js b/browser/base/content/sync/setup.js index ab7f61001565..9190263283a9 100644 --- a/browser/base/content/sync/setup.js +++ b/browser/base/content/sync/setup.js @@ -61,7 +61,7 @@ var gSyncSetup = { return document.getElementById("existingServer").selectedIndex == 0; }, - init: function() { + init() { let obs = [ ["weave:service:change-passphrase", "onResetPassphrase"], ["weave:service:login:start", "onLoginStart"], @@ -121,14 +121,14 @@ var gSyncSetup = { .getAttribute("accesskey"); }, - startNewAccountSetup: function() { + startNewAccountSetup() { if (!Weave.Utils.ensureMPUnlocked()) return; this._settingUpNew = true; this.wizard.pageIndex = NEW_ACCOUNT_START_PAGE; }, - useExistingAccount: function() { + useExistingAccount() { if (!Weave.Utils.ensureMPUnlocked()) return; this._settingUpNew = false; @@ -173,22 +173,22 @@ var gSyncSetup = { gSyncUtils.resetPassphrase(true); }, - onResetPassphrase: function() { + onResetPassphrase() { document.getElementById("existingPassphrase").value = Weave.Utils.hyphenatePassphrase(Weave.Service.identity.syncKey); this.checkFields(); this.wizard.advance(); }, - onLoginStart: function() { + onLoginStart() { this.toggleLoginFeedback(false); }, - onLoginEnd: function() { + onLoginEnd() { this.toggleLoginFeedback(true); }, - sendCredentialsAfterSync: function() { + sendCredentialsAfterSync() { let send = function() { Services.obs.removeObserver("weave:service:sync:finish", send); Services.obs.removeObserver("weave:service:sync:error", send); @@ -202,7 +202,7 @@ var gSyncSetup = { Services.obs.addObserver("weave:service:sync:error", send, false); }, - toggleLoginFeedback: function(stop) { + toggleLoginFeedback(stop) { document.getElementById("login-throbber").hidden = stop; let password = document.getElementById("existingPasswordFeedbackRow"); let server = document.getElementById("existingServerFeedbackRow"); @@ -231,7 +231,7 @@ var gSyncSetup = { this._setFeedbackMessage(feedback, false, Weave.Status.login); }, - setupInitialSync: function() { + setupInitialSync() { let action = document.getElementById("mergeChoiceRadio").selectedItem.id; switch (action) { case "resetClient": @@ -248,11 +248,11 @@ var gSyncSetup = { }, // fun with validation! - checkFields: function() { + checkFields() { this.wizard.canAdvance = this.readyToAdvance(); }, - readyToAdvance: function() { + readyToAdvance() { switch (this.wizard.pageIndex) { case INTRO_PAGE: return false; @@ -293,7 +293,7 @@ var gSyncSetup = { this.pin3.value.length == PIN_PART_LENGTH); }, - onEmailInput: function() { + onEmailInput() { // Check account validity when the user stops typing for 1 second. if (this._checkAccountTimer) window.clearTimeout(this._checkAccountTimer); @@ -302,7 +302,7 @@ var gSyncSetup = { }, 1000); }, - checkAccount: function() { + checkAccount() { delete this._checkAccountTimer; let value = Weave.Utils.normalizeAccount( document.getElementById("weaveEmail").value); @@ -337,7 +337,7 @@ var gSyncSetup = { this.checkFields(); }, - onPasswordChange: function() { + onPasswordChange() { let password = document.getElementById("weavePassword"); let pwconfirm = document.getElementById("weavePasswordConfirm"); let [valid, errorString] = gSyncUtils.validatePassword(password, pwconfirm); @@ -349,7 +349,7 @@ var gSyncSetup = { this.checkFields(); }, - onPageShow: function() { + onPageShow() { switch (this.wizard.pageIndex) { case PAIR_PAGE: this.wizard.getButton("back").hidden = true; @@ -420,7 +420,7 @@ var gSyncSetup = { } }, - onWizardAdvance: function() { + onWizardAdvance() { // Check pageIndex so we don't prompt before the Sync setup wizard appears. // This is a fallback in case the Master Password gets locked mid-wizard. if ((this.wizard.pageIndex >= 0) && @@ -509,7 +509,7 @@ var gSyncSetup = { return true; }, - onWizardBack: function() { + onWizardBack() { switch (this.wizard.pageIndex) { case NEW_ACCOUNT_START_PAGE: this.wizard.pageIndex = INTRO_PAGE; @@ -535,7 +535,7 @@ var gSyncSetup = { return true; }, - wizardFinish: function() { + wizardFinish() { this.setupInitialSync(); if (this.wizardType == "pair") { @@ -563,7 +563,7 @@ var gSyncSetup = { window.close(); }, - onWizardCancel: function() { + onWizardCancel() { if (this._resettingSync) return; @@ -572,12 +572,12 @@ var gSyncSetup = { Weave.Service.startOver(); }, - onSyncOptions: function() { + onSyncOptions() { this._beforeOptionsPage = this.wizard.pageIndex; this.wizard.pageIndex = OPTIONS_PAGE; }, - returnFromOptions: function() { + returnFromOptions() { this.wizard.getButton("next").label = this._nextButtonLabel; this.wizard.getButton("next").setAttribute("accesskey", this._nextButtonAccesskey); @@ -644,7 +644,7 @@ var gSyncSetup = { this._jpakeclient.controller = controller; }, - startEasySetup: function() { + startEasySetup() { // Don't do anything if we have a client already (e.g. we went to // Sync Options and just came back). if (this._jpakeclient) @@ -691,7 +691,7 @@ var gSyncSetup = { this._jpakeclient.receiveNoPIN(); }, - abortEasySetup: function() { + abortEasySetup() { document.getElementById("easySetupPIN1").value = ""; document.getElementById("easySetupPIN2").value = ""; document.getElementById("easySetupPIN3").value = ""; @@ -702,7 +702,7 @@ var gSyncSetup = { delete this._jpakeclient; }, - manualSetup: function() { + manualSetup() { this.abortEasySetup(); this.wizard.pageIndex = EXISTING_ACCOUNT_LOGIN_PAGE; }, @@ -710,7 +710,7 @@ var gSyncSetup = { // _handleNoScript is needed because it blocks the captcha. So we temporarily // allow the necessary sites so that we can verify the user is in fact a human. // This was done with the help of Giorgio (NoScript author). See bug 508112. - _handleNoScript: function(addExceptions) { + _handleNoScript(addExceptions) { // if NoScript isn't installed, or is disabled, bail out. let ns = Cc["@maone.net/noscript-service;1"]; if (ns == null) @@ -734,7 +734,7 @@ var gSyncSetup = { } }, - onExistingServerCommand: function() { + onExistingServerCommand() { let control = document.getElementById("existingServer"); if (control.selectedIndex == 0) { control.removeAttribute("editable"); @@ -750,7 +750,7 @@ var gSyncSetup = { this.checkFields(); }, - onExistingServerInput: function() { + onExistingServerInput() { // Check custom server validity when the user stops typing for 1 second. if (this._existingServerTimer) window.clearTimeout(this._existingServerTimer); @@ -759,7 +759,7 @@ var gSyncSetup = { }, 1000); }, - onServerCommand: function() { + onServerCommand() { setVisibility(document.getElementById("TOSRow"), this._usingMainServers); let control = document.getElementById("server"); if (!this._usingMainServers) { @@ -783,7 +783,7 @@ var gSyncSetup = { this.checkFields(); }, - onServerInput: function() { + onServerInput() { // Check custom server validity when the user stops typing for 1 second. if (this._checkServerTimer) window.clearTimeout(this._checkServerTimer); @@ -792,7 +792,7 @@ var gSyncSetup = { }, 1000); }, - checkServer: function() { + checkServer() { delete this._checkServerTimer; let el = document.getElementById("server"); let valid = false; @@ -813,7 +813,7 @@ var gSyncSetup = { this.checkFields(); }, - _validateServer: function(element) { + _validateServer(element) { let valid = false; let val = element.value; if (!val) @@ -859,7 +859,7 @@ var gSyncSetup = { return valid; }, - _handleChoice: function() { + _handleChoice() { let desc = document.getElementById("mergeChoiceRadio").selectedIndex; document.getElementById("chosenActionDeck").selectedIndex = desc; switch (desc) { @@ -983,7 +983,7 @@ var gSyncSetup = { // sets class and string on a feedback element // if no property string is passed in, we clear label/style - _setFeedback: function(element, success, string) { + _setFeedback(element, success, string) { element.hidden = success || !string; let classname = success ? "success" : "error"; let image = element.getElementsByAttribute("class", "statusIcon")[0]; @@ -993,7 +993,7 @@ var gSyncSetup = { }, // shim - _setFeedbackMessage: function(element, success, string) { + _setFeedbackMessage(element, success, string) { let str = ""; if (string) { try { @@ -1015,7 +1015,7 @@ var gSyncSetup = { } }, - onStateChange: function(webProgress, request, stateFlags, status) { + onStateChange(webProgress, request, stateFlags, status) { // We're only looking for the end of the frame load if ((stateFlags & Ci.nsIWebProgressListener.STATE_STOP) == 0) return; @@ -1029,10 +1029,10 @@ var gSyncSetup = { setVisibility(this.captchaBrowser, responseStatus != 404); // XXX TODO we should really log any responseStatus other than 200 }, - onProgressChange: function() {}, - onStatusChange: function() {}, - onSecurityChange: function() {}, - onLocationChange: function() {} + onProgressChange() {}, + onStatusChange() {}, + onSecurityChange() {}, + onLocationChange() {} }; // Define lazy getters for various XUL elements. diff --git a/browser/base/content/sync/utils.js b/browser/base/content/sync/utils.js index c49d4b3b71fb..ea60ba1a0541 100644 --- a/browser/base/content/sync/utils.js +++ b/browser/base/content/sync/utils.js @@ -22,7 +22,7 @@ var gSyncUtils = { }, // opens in a new window if we're in a modal prefwindow world, in a new tab otherwise - _openLink: function(url) { + _openLink(url) { let thisDocEl = document.documentElement, openerDocEl = window.opener && window.opener.document.documentElement; if (thisDocEl.id == "accountSetup" && window.opener && @@ -58,22 +58,22 @@ var gSyncUtils = { type, duringSetup); }, - changePassword: function() { + changePassword() { if (Weave.Utils.ensureMPUnlocked()) this.openChange("ChangePassword"); }, - resetPassphrase: function(duringSetup) { + resetPassphrase(duringSetup) { if (Weave.Utils.ensureMPUnlocked()) this.openChange("ResetPassphrase", duringSetup); }, - updatePassphrase: function() { + updatePassphrase() { if (Weave.Utils.ensureMPUnlocked()) this.openChange("UpdatePassphrase"); }, - resetPassword: function() { + resetPassword() { this._openLink(Weave.Service.pwResetURL); }, @@ -82,7 +82,7 @@ var gSyncUtils = { return Weave.Svc.Prefs.get(root + "termsURL"); }, - openToS: function() { + openToS() { this._openLink(this.tosURL); }, @@ -91,7 +91,7 @@ var gSyncUtils = { return Weave.Svc.Prefs.get(root + "privacyURL"); }, - openPrivacyPolicy: function() { + openPrivacyPolicy() { this._openLink(this.privacyPolicyURL); }, @@ -102,7 +102,7 @@ var gSyncUtils = { * @param elid : ID of the form element containing the passphrase. * @param callback : Function called once the iframe has loaded. */ - _preparePPiframe: function(elid, callback) { + _preparePPiframe(elid, callback) { let pp = document.getElementById(elid).value; // Create an invisible iframe whose contents we can print. @@ -137,7 +137,7 @@ var gSyncUtils = { * * @param elid : ID of the form element containing the passphrase. */ - passphrasePrint: function(elid) { + passphrasePrint(elid) { this._preparePPiframe(elid, function(iframe) { let webBrowserPrint = iframe.contentWindow .QueryInterface(Ci.nsIInterfaceRequestor) @@ -165,7 +165,7 @@ var gSyncUtils = { * * @param elid : ID of the form element containing the passphrase. */ - passphraseSave: function(elid) { + passphraseSave(elid) { let dialogTitle = this.bundle.GetStringFromName("save.recoverykey.title"); let defaultSaveName = this.bundle.GetStringFromName("save.recoverykey.defaultfilename"); this._preparePPiframe(elid, function(iframe) { @@ -203,7 +203,7 @@ var gSyncUtils = { * * returns [valid, errorString] */ - validatePassword: function(el1, el2) { + validatePassword(el1, el2) { let valid = false; let val1 = el1.value; let val2 = el2 ? el2.value : ""; diff --git a/browser/base/content/tab-content.js b/browser/base/content/tab-content.js index 34eb58627207..67db5b5fc183 100644 --- a/browser/base/content/tab-content.js +++ b/browser/base/content/tab-content.js @@ -27,7 +27,7 @@ XPCOMUtils.defineLazyGetter(this, "SimpleServiceDiscovery", function() { ssdp.registerDevice({ id: "roku:ecp", target: "roku:ecp", - factory: function(aService) { + factory(aService) { Cu.import("resource://gre/modules/RokuApp.jsm"); return new RokuApp(aService); }, @@ -98,13 +98,13 @@ addMessageListener("SecondScreen:tab-mirror", function(message) { if (app) { let width = content.innerWidth; let height = content.innerHeight; - let viewport = {cssWidth: width, cssHeight: height, width: width, height: height}; + let viewport = {cssWidth: width, cssHeight: height, width, height}; app.mirror(function() {}, content, viewport, function() {}, content); } }); var AboutHomeListener = { - init: function(chromeGlobal) { + init(chromeGlobal) { chromeGlobal.addEventListener('AboutHomeLoad', this, false, true); }, @@ -112,7 +112,7 @@ var AboutHomeListener = { return content.document.documentURI.toLowerCase() == "about:home"; }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (!this.isAboutHome) { return; } @@ -129,7 +129,7 @@ var AboutHomeListener = { } }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { if (!this.isAboutHome) { return; } @@ -140,7 +140,7 @@ var AboutHomeListener = { } }, - onUpdate: function(aData) { + onUpdate(aData) { let doc = content.document; if (aData.showRestoreLastSession && !PrivateBrowsingUtils.isContentWindowPrivate(content)) doc.getElementById("launcher").setAttribute("session", "true"); @@ -154,7 +154,7 @@ var AboutHomeListener = { docElt.setAttribute("snippetsVersion", aData.snippetsVersion); }, - onPageLoad: function() { + onPageLoad() { addMessageListener("AboutHome:Update", this); addEventListener("click", this, true); addEventListener("pagehide", this, true); @@ -163,7 +163,7 @@ var AboutHomeListener = { sendAsyncMessage("AboutHome:RequestUpdate"); }, - onClick: function(aEvent) { + onClick(aEvent) { if (!aEvent.isTrusted || // Don't trust synthetic events aEvent.button == 2 || aEvent.target.localName != "button") { return; @@ -210,7 +210,7 @@ var AboutHomeListener = { } }, - onPageHide: function(aEvent) { + onPageHide(aEvent) { if (aEvent.target.defaultView.frameElement) { return; } @@ -260,7 +260,7 @@ var AboutReaderListener = { _isLeavingReaderMode: false, - init: function() { + init() { addEventListener("AboutReaderContentLoaded", this, false, true); addEventListener("DOMContentLoaded", this, false); addEventListener("pageshow", this, false); @@ -269,7 +269,7 @@ var AboutReaderListener = { addMessageListener("Reader:PushState", this); }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Reader:ToggleReaderMode": if (!this.isAboutReader) { @@ -294,7 +294,7 @@ var AboutReaderListener = { return content.document.documentURI.startsWith("about:reader"); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (aEvent.originalTarget.defaultView != content) { return; } @@ -344,7 +344,7 @@ var AboutReaderListener = { * this is a suitable document). Calling it on things which won't be * painted is not going to work. */ - updateReaderButton: function(forceNonArticle) { + updateReaderButton(forceNonArticle) { if (!ReaderMode.isEnabledForParseOnLoad || this.isAboutReader || !content || !(content.document instanceof content.HTMLDocument) || content.document.mozSyntheticDocument) { @@ -354,14 +354,14 @@ var AboutReaderListener = { this.scheduleReadabilityCheckPostPaint(forceNonArticle); }, - cancelPotentialPendingReadabilityCheck: function() { + cancelPotentialPendingReadabilityCheck() { if (this._pendingReadabilityCheck) { removeEventListener("MozAfterPaint", this._pendingReadabilityCheck); delete this._pendingReadabilityCheck; } }, - scheduleReadabilityCheckPostPaint: function(forceNonArticle) { + scheduleReadabilityCheckPostPaint(forceNonArticle) { if (this._pendingReadabilityCheck) { // We need to stop this check before we re-add one because we don't know // if forceNonArticle was true or false last time. @@ -371,7 +371,7 @@ var AboutReaderListener = { addEventListener("MozAfterPaint", this._pendingReadabilityCheck); }, - onPaintWhenWaitedFor: function(forceNonArticle, event) { + onPaintWhenWaitedFor(forceNonArticle, event) { // In non-e10s, we'll get called for paints other than ours, and so it's // possible that this page hasn't been laid out yet, in which case we // should wait until we get an event that does relate to our layout. We @@ -401,18 +401,18 @@ var ContentSearchMediator = { "about:newtab", ]), - init: function(chromeGlobal) { + init(chromeGlobal) { chromeGlobal.addEventListener("ContentSearchClient", this, true, true); addMessageListener("ContentSearch", this); }, - handleEvent: function(event) { + handleEvent(event) { if (this._contentWhitelisted) { this._sendMsg(event.detail.type, event.detail.data); } }, - receiveMessage: function(msg) { + receiveMessage(msg) { if (msg.data.type == "AddToWhitelist") { for (let uri of msg.data.data) { this.whitelist.add(uri); @@ -429,18 +429,18 @@ var ContentSearchMediator = { return this.whitelist.has(content.document.documentURI); }, - _sendMsg: function(type, data = null) { + _sendMsg(type, data = null) { sendAsyncMessage("ContentSearch", { - type: type, - data: data, + type, + data, }); }, - _fireEvent: function(type, data = null) { + _fireEvent(type, data = null) { let event = Cu.cloneInto({ detail: { - type: type, - data: data, + type, + data, }, }, content); content.dispatchEvent(new content.CustomEvent("ContentSearchService", @@ -450,7 +450,7 @@ var ContentSearchMediator = { ContentSearchMediator.init(this); var PageStyleHandler = { - init: function() { + init() { addMessageListener("PageStyle:Switch", this); addMessageListener("PageStyle:Disable", this); addEventListener("pageshow", () => this.sendStyleSheetInfo()); @@ -460,23 +460,23 @@ var PageStyleHandler = { return docShell.contentViewer; }, - sendStyleSheetInfo: function() { + sendStyleSheetInfo() { let filteredStyleSheets = this._filterStyleSheets(this.getAllStyleSheets()); sendAsyncMessage("PageStyle:StyleSheets", { - filteredStyleSheets: filteredStyleSheets, + filteredStyleSheets, authorStyleDisabled: this.markupDocumentViewer.authorStyleDisabled, preferredStyleSheetSet: content.document.preferredStyleSheetSet }); }, - getAllStyleSheets: function(frameset = content) { + getAllStyleSheets(frameset = content) { let selfSheets = Array.slice(frameset.document.styleSheets); let subSheets = Array.map(frameset.frames, frame => this.getAllStyleSheets(frame)); return selfSheets.concat(...subSheets); }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "PageStyle:Switch": this.markupDocumentViewer.authorStyleDisabled = false; @@ -491,7 +491,7 @@ var PageStyleHandler = { this.sendStyleSheetInfo(); }, - _stylesheetSwitchAll: function(frameset, title) { + _stylesheetSwitchAll(frameset, title) { if (!title || this._stylesheetInFrame(frameset, title)) { this._stylesheetSwitchFrame(frameset, title); } @@ -502,7 +502,7 @@ var PageStyleHandler = { } }, - _stylesheetSwitchFrame: function(frame, title) { + _stylesheetSwitchFrame(frame, title) { var docStyleSheets = frame.document.styleSheets; for (let i = 0; i < docStyleSheets.length; ++i) { @@ -515,11 +515,11 @@ var PageStyleHandler = { } }, - _stylesheetInFrame: function(frame, title) { + _stylesheetInFrame(frame, title) { return Array.some(frame.document.styleSheets, (styleSheet) => styleSheet.title == title); }, - _filterStyleSheets: function(styleSheets) { + _filterStyleSheets(styleSheets) { let result = []; for (let currentStyleSheet of styleSheets) { @@ -661,13 +661,13 @@ let PrerenderContentHandler = { sendAsyncMessage("Prerender:Request", { href: aHref.spec, referrer: aReferrer ? aReferrer.spec : null, - id: id, + id, }); this._pending.push({ href: aHref, referrer: aReferrer, - id: id, + id, success: null, failure: null, }); @@ -699,12 +699,12 @@ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { } var WebBrowserChrome = { - onBeforeLinkTraversal: function(originalTarget, linkURI, linkNode, isAppTab) { + onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) { return BrowserUtils.onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab); }, // Check whether this URI should load in the current process - shouldLoadURI: function(aDocShell, aURI, aReferrer) { + shouldLoadURI(aDocShell, aURI, aReferrer) { if (!E10SUtils.shouldLoadURI(aDocShell, aURI, aReferrer)) { E10SUtils.redirectLoad(aDocShell, aURI, aReferrer); return false; @@ -713,23 +713,23 @@ var WebBrowserChrome = { return true; }, - shouldLoadURIInThisProcess: function(aURI) { + shouldLoadURIInThisProcess(aURI) { return E10SUtils.shouldLoadURIInThisProcess(aURI); }, // Try to reload the currently active or currently loading page in a new process. - reloadInFreshProcess: function(aDocShell, aURI, aReferrer) { + reloadInFreshProcess(aDocShell, aURI, aReferrer) { E10SUtils.redirectLoad(aDocShell, aURI, aReferrer, true); return true; }, - startPrerenderingDocument: function(aHref, aReferrer) { + startPrerenderingDocument(aHref, aReferrer) { if (PrerenderContentHandler.initialized) { PrerenderContentHandler.startPrerenderingDocument(aHref, aReferrer); } }, - shouldSwitchToPrerenderedDocument: function(aHref, aReferrer, aSuccess, aFailure) { + shouldSwitchToPrerenderedDocument(aHref, aReferrer, aSuccess, aFailure) { if (PrerenderContentHandler.initialized) { return PrerenderContentHandler.shouldSwitchToPrerenderedDocument( aHref, aReferrer, aSuccess, aFailure); @@ -747,7 +747,7 @@ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { var DOMFullscreenHandler = { - init: function() { + init() { addMessageListener("DOMFullscreen:Entered", this); addMessageListener("DOMFullscreen:CleanUp", this); addEventListener("MozDOMFullscreen:Request", this); @@ -765,7 +765,7 @@ var DOMFullscreenHandler = { .getInterface(Ci.nsIDOMWindowUtils); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { let windowUtils = this._windowUtils; switch (aMessage.name) { case "DOMFullscreen:Entered": { @@ -793,7 +793,7 @@ var DOMFullscreenHandler = { } }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "MozDOMFullscreen:Request": { sendAsyncMessage("DOMFullscreen:Request"); diff --git a/browser/base/content/test/general/browser_aboutAccounts.js b/browser/base/content/test/general/browser_aboutAccounts.js index c825c91cd02d..173ac8c52fde 100644 --- a/browser/base/content/test/general/browser_aboutAccounts.js +++ b/browser/base/content/test/general/browser_aboutAccounts.js @@ -36,11 +36,11 @@ registerCleanupFunction(function() { var gTests = [ { desc: "Test the remote commands", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/browser/browser/base/content/test/general/accounts_testRemoteCommands.html"); @@ -76,7 +76,7 @@ var gTests = [ { desc: "Test action=signin - no user logged in", teardown: () => gBrowser.removeCurrentTab(), - run: function* () + *run() { // When this loads with no user logged-in, we expect the "normal" URL const expected_url = "https://example.com/?is_sign_in"; @@ -95,11 +95,11 @@ var gTests = [ }, { desc: "Test action=signin - user logged in", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { // When this loads with a user logged-in, we expect the normal URL to // have been ignored and the "manage" page to be shown. @@ -124,7 +124,7 @@ var gTests = [ { desc: "Test action=signin - captive portal", teardown: () => gBrowser.removeCurrentTab(), - run: function* () + *run() { const signinUrl = "https://redirproxy.example.com/test"; setPref("identity.fxaccounts.remote.signin.uri", signinUrl); @@ -144,7 +144,7 @@ var gTests = [ gBrowser.removeCurrentTab(); BrowserOffline.toggleOfflineStatus(); }, - run: function* () + *run() { BrowserOffline.toggleOfflineStatus(); Services.cache2.clear(); @@ -164,7 +164,7 @@ var gTests = [ { desc: "Test action=signup - no user logged in", teardown: () => gBrowser.removeCurrentTab(), - run: function* () + *run() { const expected_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", expected_url); @@ -183,7 +183,7 @@ var gTests = [ { desc: "Test action=signup - user logged in", teardown: () => gBrowser.removeCurrentTab(), - run: function* () + *run() { const expected_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", expected_url); @@ -202,11 +202,11 @@ var gTests = [ }, { desc: "Test action=reauth", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { const expected_url = "https://example.com/?is_force_auth"; setPref("identity.fxaccounts.remote.force_auth.uri", expected_url); @@ -220,11 +220,11 @@ var gTests = [ }, { desc: "Test with migrateToDevEdition enabled (success)", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { let fxAccountsCommon = {}; Cu.import("resource://gre/modules/FxAccountsCommon.js", fxAccountsCommon); @@ -281,11 +281,11 @@ var gTests = [ }, { desc: "Test with migrateToDevEdition enabled (no user to migrate)", - teardown: function* () { + *teardown() { gBrowser.removeCurrentTab(); yield signOut(); }, - run: function* () + *run() { const pref = "identity.fxaccounts.migrateToDevEdition"; changedPrefs.add(pref); @@ -321,10 +321,10 @@ var gTests = [ }, { desc: "Test observers about:accounts", - teardown: function() { + teardown() { gBrowser.removeCurrentTab(); }, - run: function* () { + *run() { setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/"); yield setSignedInUser(); let tab = yield promiseNewTabLoadEvent("about:accounts"); @@ -339,7 +339,7 @@ var gTests = [ { desc: "Test entrypoint query string, no action, no user logged in", teardown: () => gBrowser.removeCurrentTab(), - run: function* () { + *run() { // When this loads with no user logged-in, we expect the "normal" URL setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/"); let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?entrypoint=abouthome"); @@ -349,7 +349,7 @@ var gTests = [ { desc: "Test entrypoint query string for signin", teardown: () => gBrowser.removeCurrentTab(), - run: function* () { + *run() { // When this loads with no user logged-in, we expect the "normal" URL const expected_url = "https://example.com/?is_sign_in"; setPref("identity.fxaccounts.remote.signin.uri", expected_url); @@ -360,7 +360,7 @@ var gTests = [ { desc: "Test entrypoint query string for signup", teardown: () => gBrowser.removeCurrentTab(), - run: function* () { + *run() { // When this loads with no user logged-in, we expect the "normal" URL const sign_up_url = "https://example.com/?is_sign_up"; setPref("identity.fxaccounts.remote.signup.uri", sign_up_url); @@ -374,7 +374,7 @@ var gTests = [ teardown() { gBrowser.removeCurrentTab(); }, - run: function* () { + *run() { let signupURL = "https://example.com/"; setPref("identity.fxaccounts.remote.signup.uri", signupURL); let queryStr = "email=foo%40example.com&foo=bar&baz=quux"; @@ -390,7 +390,7 @@ var gTests = [ teardown() { gBrowser.removeCurrentTab(); }, - run: function* () { + *run() { let signupURL = "https://example.com/?param"; setPref("identity.fxaccounts.remote.signup.uri", signupURL); let queryStr = "email=foo%40example.com&foo=bar&baz=quux"; @@ -472,7 +472,7 @@ function checkVisibilities(tab, data) { } deferred.resolve(); }); - mm.sendAsyncMessage("test:check-visibilities", {ids: ids}); + mm.sendAsyncMessage("test:check-visibilities", {ids}); return deferred.promise; } diff --git a/browser/base/content/test/general/browser_aboutHealthReport.js b/browser/base/content/test/general/browser_aboutHealthReport.js index 4027db223feb..2b7eb1b08741 100644 --- a/browser/base/content/test/general/browser_aboutHealthReport.js +++ b/browser/base/content/test/general/browser_aboutHealthReport.js @@ -68,7 +68,7 @@ var gTests = [ Preferences.set("datareporting.healthreport.about.reportUrl", HTTPS_BASE + "healthreport_testRemoteCommands.html"); }), - run: function(iframe) + run(iframe) { let deferred = Promise.defer(); let results = 0; diff --git a/browser/base/content/test/general/browser_aboutHome.js b/browser/base/content/test/general/browser_aboutHome.js index ba5abf34732c..cf9ed841e481 100644 --- a/browser/base/content/test/general/browser_aboutHome.js +++ b/browser/base/content/test/general/browser_aboutHome.js @@ -495,7 +495,7 @@ add_task(function* () { let oldOpenPrefs = window.openPreferences; let openPrefsPromise = new Promise(resolve => { window.openPreferences = function(pane, params) { - resolve({ pane: pane, params: params }); + resolve({ pane, params }); }; }); @@ -647,7 +647,7 @@ function promiseNewEngine(basename) { return new Promise((resolve, reject) => { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => { try { @@ -656,7 +656,7 @@ function promiseNewEngine(basename) { }); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/general/browser_alltabslistener.js b/browser/base/content/test/general/browser_alltabslistener.js index da5e8ddd1933..622be9cd2eab 100644 --- a/browser/base/content/test/general/browser_alltabslistener.js +++ b/browser/base/content/test/general/browser_alltabslistener.js @@ -4,12 +4,12 @@ const gCompleteState = Ci.nsIWebProgressListener.STATE_STOP + Ci.nsIWebProgressListener.STATE_IS_NETWORK; var gFrontProgressListener = { - onProgressChange: function(aWebProgress, aRequest, + onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { }, - onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { var state = "onStateChange"; info("FrontProgress: " + state + " 0x" + aStateFlags.toString(16)); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -17,7 +17,7 @@ var gFrontProgressListener = { gFrontNotificationsPos++; }, - onLocationChange: function(aWebProgress, aRequest, aLocationURI, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocationURI, aFlags) { var state = "onLocationChange"; info("FrontProgress: " + state + " " + aLocationURI.spec); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -25,10 +25,10 @@ var gFrontProgressListener = { gFrontNotificationsPos++; }, - onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { }, - onSecurityChange: function(aWebProgress, aRequest, aState) { + onSecurityChange(aWebProgress, aRequest, aState) { var state = "onSecurityChange"; info("FrontProgress: " + state + " 0x" + aState.toString(16)); ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener"); @@ -38,7 +38,7 @@ var gFrontProgressListener = { } var gAllProgressListener = { - onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { var state = "onStateChange"; info("AllProgress: " + state + " 0x" + aStateFlags.toString(16)); ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); @@ -53,7 +53,7 @@ var gAllProgressListener = { } }, - onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, + onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) { var state = "onLocationChange"; info("AllProgress: " + state + " " + aLocationURI.spec); @@ -63,12 +63,12 @@ var gAllProgressListener = { gAllNotificationsPos++; }, - onStatusChange: function(aBrowser, aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange(aBrowser, aWebProgress, aRequest, aStatus, aMessage) { var state = "onStatusChange"; ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); }, - onSecurityChange: function(aBrowser, aWebProgress, aRequest, aState) { + onSecurityChange(aBrowser, aWebProgress, aRequest, aState) { var state = "onSecurityChange"; info("AllProgress: " + state + " 0x" + aState.toString(16)); ok(aBrowser == gTestBrowser, state + " notification came from the correct browser"); diff --git a/browser/base/content/test/general/browser_blockHPKP.js b/browser/base/content/test/general/browser_blockHPKP.js index 47106cbb4623..d470a219f58d 100644 --- a/browser/base/content/test/general/browser_blockHPKP.js +++ b/browser/base/content/test/general/browser_blockHPKP.js @@ -60,7 +60,7 @@ function loadPinningPage() { // After the site is pinned try to load with a subdomain site that should // fail to validate var successfulPinningPageListener = { - handleEvent: function() { + handleEvent() { gBrowser.selectedBrowser.removeEventListener("load", this, true); BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kBadPinningDomain).then(function() { return promiseErrorPageLoaded(gBrowser.selectedBrowser); diff --git a/browser/base/content/test/general/browser_bug321000.js b/browser/base/content/test/general/browser_bug321000.js index b30b7101d568..a65b2703ee91 100644 --- a/browser/base/content/test/general/browser_bug321000.js +++ b/browser/base/content/test/general/browser_bug321000.js @@ -49,7 +49,7 @@ function test_paste(aCurrentTest) { // Register input listener. var inputListener = { test: aCurrentTest, - handleEvent: function(event) { + handleEvent(event) { element.removeEventListener(event.type, this, false); is(element.value, this.test.expected, this.test.desc); diff --git a/browser/base/content/test/general/browser_bug356571.js b/browser/base/content/test/general/browser_bug356571.js index 1bfa73ea1587..8af6b4a79003 100644 --- a/browser/base/content/test/general/browser_bug356571.js +++ b/browser/base/content/test/general/browser_bug356571.js @@ -15,7 +15,7 @@ const kPromptServiceFactory = Cm.getClassObject(Cc[kPromptServiceContractID], Ci.nsIFactory); var fakePromptServiceFactory = { - createInstance: function(aOuter, aIid) { + createInstance(aOuter, aIid) { if (aOuter != null) throw Cr.NS_ERROR_NO_AGGREGATION; return promptService.QueryInterface(aIid); @@ -24,7 +24,7 @@ var fakePromptServiceFactory = { var promptService = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]), - alert: function() { + alert() { didFail = true; } }; @@ -47,7 +47,7 @@ const kURIs = [ var gProgressListener = { _runCount: 0, - onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { if ((aStateFlags & kCompleteState) == kCompleteState) { if (++this._runCount != kURIs.length) return; diff --git a/browser/base/content/test/general/browser_bug424101.js b/browser/base/content/test/general/browser_bug424101.js index 8000d2ae9d5e..501448b8d399 100644 --- a/browser/base/content/test/general/browser_bug424101.js +++ b/browser/base/content/test/general/browser_bug424101.js @@ -24,7 +24,7 @@ add_task(function *() { let test = tests[index]; yield ContentTask.spawn(gBrowser.selectedBrowser, - { element: test.element, type: test.type, index: index }, + { element: test.element, type: test.type, index }, function* (arg) { let element = content.document.createElement(arg.element); element.id = "element" + arg.index; diff --git a/browser/base/content/test/general/browser_bug553455.js b/browser/base/content/test/general/browser_bug553455.js index b6004e0d3e5d..e3bfc7854492 100644 --- a/browser/base/content/test/general/browser_bug553455.js +++ b/browser/base/content/test/general/browser_bug553455.js @@ -152,13 +152,13 @@ function waitForInstallDialog() { let window = yield new Promise(resolve => { Services.wm.addListener({ - onOpenWindow: function(aXULWindow) { + onOpenWindow(aXULWindow) { Services.wm.removeListener(this); resolve(aXULWindow); }, - onCloseWindow: function(aXULWindow) { + onCloseWindow(aXULWindow) { }, - onWindowTitleChange: function(aXULWindow, aNewTitle) { + onWindowTitleChange(aXULWindow, aNewTitle) { } }); }); @@ -1055,7 +1055,7 @@ function test_cancel() { let install = notification.notification.options.installs[0]; let cancelledPromise = new Promise(resolve => { install.addListener({ - onDownloadCancelled: function() { + onDownloadCancelled() { install.removeListener(this); resolve(); } @@ -1124,7 +1124,7 @@ function test_failedSecurity() { var gTestStart = null; var XPInstallObserver = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo); info("Observed " + aTopic + " for " + installInfo.installs.length + " installs"); installInfo.installs.forEach(function(aInstall) { diff --git a/browser/base/content/test/general/browser_bug561636.js b/browser/base/content/test/general/browser_bug561636.js index 19e816716faf..585800b9e4c7 100644 --- a/browser/base/content/test/general/browser_bug561636.js +++ b/browser/base/content/test/general/browser_bug561636.js @@ -17,7 +17,7 @@ function checkPopupHide() var gObserver = { QueryInterface : XPCOMUtils.generateQI([Ci.nsIFormSubmitObserver]), - notifyInvalidSubmit : function(aFormElement, aInvalidElements) + notifyInvalidSubmit(aFormElement, aInvalidElements) { } }; diff --git a/browser/base/content/test/general/browser_bug592338.js b/browser/base/content/test/general/browser_bug592338.js index ca9cc361a84e..3744f26e4814 100644 --- a/browser/base/content/test/general/browser_bug592338.js +++ b/browser/base/content/test/general/browser_bug592338.js @@ -144,7 +144,7 @@ function test() { AddonManager.getInstallForURL(TESTROOT + "theme.xpi", function(aInstall) { aInstall.addListener({ - onInstallEnded: function() { + onInstallEnded() { AddonManager.getAddonByID("theme-xpi@tests.mozilla.org", function(aAddon) { isnot(aAddon, null, "Should have installed the test theme."); diff --git a/browser/base/content/test/general/browser_bug676619.js b/browser/base/content/test/general/browser_bug676619.js index a5f49f0d423e..4e3341d76ca3 100644 --- a/browser/base/content/test/general/browser_bug676619.js +++ b/browser/base/content/test/general/browser_bug676619.js @@ -64,7 +64,7 @@ function test() { function addWindowListener(aURL, aCallback) { Services.wm.addListener({ - onOpenWindow: function(aXULWindow) { + onOpenWindow(aXULWindow) { info("window opened, waiting for focus"); Services.wm.removeListener(this); @@ -75,8 +75,8 @@ function addWindowListener(aURL, aCallback) { aCallback(domwindow); }, domwindow); }, - onCloseWindow: function(aXULWindow) { }, - onWindowTitleChange: function(aXULWindow, aNewTitle) { } + onCloseWindow(aXULWindow) { }, + onWindowTitleChange(aXULWindow, aNewTitle) { } }); } @@ -98,7 +98,7 @@ TabOpenListener.prototype = { tab: null, browser: null, - handleEvent: function(event) { + handleEvent(event) { if (event.type == "TabOpen") { gBrowser.tabContainer.removeEventListener("TabOpen", this, false); this.tab = event.originalTarget; diff --git a/browser/base/content/test/general/browser_bug734076.js b/browser/base/content/test/general/browser_bug734076.js index d7aca0250f09..4f0eda31083c 100644 --- a/browser/base/content/test/general/browser_bug734076.js +++ b/browser/base/content/test/general/browser_bug734076.js @@ -15,15 +15,15 @@ add_task(function* () name: "view background image", url: "http://mochi.test:8888/", element: "body", - go: function() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { + go() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { let contentBody = content.document.body; contentBody.style.backgroundImage = "url('" + arg.writeDomainURL + "')"; return "context-viewbgimage"; }); }, - verify: function() { + verify() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for view background image"); @@ -34,8 +34,8 @@ add_task(function* () name: "view image", url: "http://mochi.test:8888/", element: "img", - go: function() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { + go() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { let doc = content.document; let img = doc.createElement("img"); img.height = 100; @@ -46,7 +46,7 @@ add_task(function* () return "context-viewimage"; }); }, - verify: function() { + verify() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for view image"); @@ -57,8 +57,8 @@ add_task(function* () name: "show only this frame", url: "http://mochi.test:8888/", element: "iframe", - go: function() { - return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL: writeDomainURL }, function* (arg) { + go() { + return ContentTask.spawn(gBrowser.selectedBrowser, { writeDomainURL }, function* (arg) { let doc = content.document; let iframe = doc.createElement("iframe"); iframe.setAttribute("src", arg.writeDomainURL); @@ -73,7 +73,7 @@ add_task(function* () }); }); }, - verify: function() { + verify() { return ContentTask.spawn(gBrowser.selectedBrowser, null, function* (arg) { Assert.ok(!content.document.body.textContent, "no domain was inherited for 'show only this frame'"); diff --git a/browser/base/content/test/general/browser_contentAltClick.js b/browser/base/content/test/general/browser_contentAltClick.js index f6922b9efd6f..bce845ca7148 100644 --- a/browser/base/content/test/general/browser_contentAltClick.js +++ b/browser/base/content/test/general/browser_contentAltClick.js @@ -54,7 +54,7 @@ add_task(function* test_alt_click() // When 1 download has been attempted then resolve the promise. let finishedAllDownloads = new Promise( (resolve) => { downloadView = { - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { downloads.push(aDownload); resolve(); }, @@ -83,7 +83,7 @@ add_task(function* test_alt_click_on_xlinks() // When all 2 downloads have been attempted then resolve the promise. let finishedAllDownloads = new Promise( (resolve) => { downloadView = { - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { downloads.push(aDownload); if (downloads.length == 2) { resolve(); diff --git a/browser/base/content/test/general/browser_contentAreaClick.js b/browser/base/content/test/general/browser_contentAreaClick.js index 921416b82385..db91dd11c71c 100644 --- a/browser/base/content/test/general/browser_contentAreaClick.js +++ b/browser/base/content/test/general/browser_contentAreaClick.js @@ -18,8 +18,8 @@ var gTests = [ { desc: "Simple left click", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: {}, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [], @@ -28,8 +28,8 @@ var gTests = [ { desc: "Ctrl/Cmd left click", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: { ctrlKey: true, metaKey: true }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], @@ -41,10 +41,10 @@ var gTests = [ // just be like Alt click. { desc: "Shift+Alt left click", - setup: function() { + setup() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { shiftKey: true, @@ -56,10 +56,10 @@ var gTests = [ { desc: "Shift+Alt left click on XLinks", - setup: function() { + setup() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { shiftKey: true, @@ -71,8 +71,8 @@ var gTests = [ { desc: "Shift click", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: { shiftKey: true }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ], @@ -81,10 +81,10 @@ var gTests = [ { desc: "Alt click", - setup: function() { + setup() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { altKey: true }, @@ -95,10 +95,10 @@ var gTests = [ { desc: "Alt click on XLinks", - setup: function() { + setup() { gPrefService.setBoolPref("browser.altClickSave", true); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.altClickSave"); }, event: { altKey: true }, @@ -109,8 +109,8 @@ var gTests = [ { desc: "Panel click", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: {}, targets: [ "panellink" ], expectedInvokedMethods: [ "urlSecurityCheck", "loadURI" ], @@ -119,8 +119,8 @@ var gTests = [ { desc: "Simple middle click opentab", - setup: function() {}, - clean: function() {}, + setup() {}, + clean() {}, event: { button: 1 }, targets: [ "commonlink", "mathxlink", "svgxlink", "maplink" ], expectedInvokedMethods: [ "urlSecurityCheck", "openLinkIn" ], @@ -129,10 +129,10 @@ var gTests = [ { desc: "Simple middle click openwin", - setup: function() { + setup() { gPrefService.setBoolPref("browser.tabs.opentabfor.middleclick", false); }, - clean: function() { + clean() { gPrefService.clearUserPref("browser.tabs.opentabfor.middleclick"); }, event: { button: 1 }, @@ -143,11 +143,11 @@ var gTests = [ { desc: "Middle mouse paste", - setup: function() { + setup() { gPrefService.setBoolPref("middlemouse.contentLoadURL", true); gPrefService.setBoolPref("general.autoScroll", false); }, - clean: function() { + clean() { gPrefService.clearUserPref("middlemouse.contentLoadURL"); gPrefService.clearUserPref("general.autoScroll"); }, @@ -199,7 +199,7 @@ function test() { // Click handler used to steal click events. var gClickHandler = { - handleEvent: function(event) { + handleEvent(event) { let linkId = event.target.id || event.target.localName; is(event.type, "click", gCurrentTest.desc + ":Handler received a click event on " + linkId); diff --git a/browser/base/content/test/general/browser_contentSearchUI.js b/browser/base/content/test/general/browser_contentSearchUI.js index aa346ed2cedd..9dc5fbcfb612 100644 --- a/browser/base/content/test/general/browser_contentSearchUI.js +++ b/browser/base/content/test/general/browser_contentSearchUI.js @@ -195,28 +195,28 @@ add_task(function* cycleSuggestions() { accelKey: true, }; - let state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + let state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xfoo", ["xfoo", "xbar"], 0, aSelectedButtonIndex); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "x", ["xfoo", "xbar"], -1, aSelectedButtonIndex); }); @@ -249,22 +249,22 @@ add_task(function* cycleOneOffs() { altKey: true, }; - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1); // If the settings button is selected, pressing alt+up/down should select the @@ -274,13 +274,13 @@ add_task(function* cycleOneOffs() { state = yield msg("key", "VK_TAB"); // Settings button selected. checkState(state, "xbar", ["xfoo", "xbar"], 1, 2); - state = yield msg("key", { key: "VK_UP", modifiers: modifiers }); + state = yield msg("key", { key: "VK_UP", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 1); state = yield msg("key", "VK_TAB"); checkState(state, "xbar", ["xfoo", "xbar"], 1, 2); - state = yield msg("key", { key: "VK_DOWN", modifiers: modifiers }); + state = yield msg("key", { key: "VK_DOWN", modifiers }); checkState(state, "xbar", ["xfoo", "xbar"], 1, 0); yield msg("removeLastOneOff"); @@ -418,7 +418,7 @@ add_task(function* search() { // Test typing a query and pressing enter. let p = msg("waitForSearch"); yield msg("key", { key: "x", waitForSuggestions: true }); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); let mesg = yield p; let eventData = { engineName: TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME, @@ -437,7 +437,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("key", "VK_DOWN"); yield msg("key", "VK_DOWN"); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME; @@ -455,7 +455,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("key", "VK_UP"); yield msg("key", "VK_UP"); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); mesg = yield p; delete eventData.selection; eventData.searchString = "x"; @@ -470,7 +470,7 @@ add_task(function* search() { modifiers.button = 0; yield msg("key", { key: "x", waitForSuggestions: true }); yield msg("mousemove", -1); - yield msg("click", { eltIdx: -1, modifiers: modifiers }); + yield msg("click", { eltIdx: -1, modifiers }); mesg = yield p; eventData.originalEvent = modifiers; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_BASENAME; @@ -483,7 +483,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); p = msg("waitForSearch"); yield msg("mousemove", 1); - yield msg("click", { eltIdx: 1, modifiers: modifiers }); + yield msg("click", { eltIdx: 1, modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.selection = { @@ -499,7 +499,7 @@ add_task(function* search() { yield msg("key", { key: "x", waitForSuggestions: true }); p = msg("waitForSearch"); yield msg("mousemove", 3); - yield msg("click", { eltIdx: 3, modifiers: modifiers }); + yield msg("click", { eltIdx: 3, modifiers }); mesg = yield p; eventData.searchString = "x"; eventData.engineName = TEST_ENGINE_PREFIX + " " + TEST_ENGINE_2_BASENAME; @@ -515,7 +515,7 @@ add_task(function* search() { p = msg("waitForSearch"); yield msg("mousemove", 1); yield msg("mousemove", 3); - yield msg("click", { eltIdx: 3, modifiers: modifiers }); + yield msg("click", { eltIdx: 3, modifiers }); mesg = yield p; eventData.searchString = "xfoo" eventData.selection = { @@ -534,7 +534,7 @@ add_task(function* search() { yield msg("key", "VK_DOWN"); yield msg("key", "VK_DOWN"); yield msg("key", "VK_TAB"); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); mesg = yield p; eventData.selection = { index: 1, @@ -554,7 +554,7 @@ add_task(function* search() { yield msg("commitComposition"); delete modifiers.button; p = msg("waitForSearch"); - yield msg("key", { key: "VK_RETURN", modifiers: modifiers }); + yield msg("key", { key: "VK_RETURN", modifiers }); mesg = yield p; eventData.searchString = "x" eventData.originalEvent = modifiers; @@ -583,7 +583,7 @@ add_task(function* search() { modifiers.button = 0; p = msg("waitForSearch"); - yield msg("click", { eltIdx: 1, modifiers: modifiers }); + yield msg("click", { eltIdx: 1, modifiers }); mesg = yield p; eventData.searchString = "xfoo"; eventData.originalEvent = modifiers; @@ -662,8 +662,8 @@ function setUp(aNoEngine) { function msg(type, data = null) { gMsgMan.sendAsyncMessage(TEST_MSG, { - type: type, - data: data, + type, + data, }); let deferred = Promise.defer(); gMsgMan.addMessageListener(TEST_MSG, function onMsg(msgObj) { diff --git a/browser/base/content/test/general/browser_contextmenu.js b/browser/base/content/test/general/browser_contextmenu.js index 3e0135848ee4..88bf6a2f6192 100644 --- a/browser/base/content/test/general/browser_contextmenu.js +++ b/browser/base/content/test/general/browser_contextmenu.js @@ -500,7 +500,7 @@ add_task(function* test_contenteditable() { add_task(function* test_copylinkcommand() { yield test_contextmenu("#test-link", null, { - postCheckContextMenuFn: function*() { + *postCheckContextMenuFn() { document.commandDispatcher .getControllerForCommand("cmd_copyLink") .doCommand("cmd_copyLink"); @@ -562,7 +562,7 @@ add_task(function* test_pagemenu() { "context-viewsource", true, "context-viewinfo", true ], - {postCheckContextMenuFn: function*() { + {*postCheckContextMenuFn() { let item = contextMenu.getElementsByAttribute("generateditemid", "1")[0]; ok(item, "Got generated XUL menu item"); item.doCommand(); @@ -820,11 +820,11 @@ add_task(function* test_click_to_play_blocked_plugin() { "context-viewinfo", true ], { - preCheckContextMenuFn: function*() { + *preCheckContextMenuFn() { pushPrefs(["plugins.click_to_play", true]); setTestPluginEnabledState(Ci.nsIPluginTag.STATE_CLICKTOPLAY); }, - postCheckContextMenuFn: function*() { + *postCheckContextMenuFn() { getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_ENABLED; } } diff --git a/browser/base/content/test/general/browser_devedition.js b/browser/base/content/test/general/browser_devedition.js index d11a26e264be..4369b6b2bcd2 100644 --- a/browser/base/content/test/general/browser_devedition.js +++ b/browser/base/content/test/general/browser_devedition.js @@ -80,7 +80,7 @@ add_task(function* testDevtoolsTheme() { function dummyLightweightTheme(id) { return { - id: id, + id, name: id, headerURL: "resource:///chrome/browser/content/browser/defaultthemes/devedition.header.png", iconURL: "resource:///chrome/browser/content/browser/defaultthemes/devedition.icon.png", diff --git a/browser/base/content/test/general/browser_documentnavigation.js b/browser/base/content/test/general/browser_documentnavigation.js index eb789d0766a9..2047795491c9 100644 --- a/browser/base/content/test/general/browser_documentnavigation.js +++ b/browser/base/content/test/general/browser_documentnavigation.js @@ -60,7 +60,7 @@ function* expectFocusOnF6(backward, expectedDocument, expectedElement, onContent details += "," + contentFM.focusedElement.id; } - sendSyncMessage("BrowserTest:FocusChanged", { details : details }); + sendSyncMessage("BrowserTest:FocusChanged", { details }); }, true); }); } diff --git a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js b/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js index b1dde6b5ae62..01c9389ef997 100644 --- a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js +++ b/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js @@ -114,7 +114,7 @@ var gTests = [ { desc: "F11 key", affectsFullscreenMode: true, - exitFunc: function() { + exitFunc() { executeSoon(() => EventUtils.synthesizeKey("VK_F11", {})); } } diff --git a/browser/base/content/test/general/browser_e10s_about_process.js b/browser/base/content/test/general/browser_e10s_about_process.js index 2b4816754aa2..d3dcc56b9e57 100644 --- a/browser/base/content/test/general/browser_e10s_about_process.js +++ b/browser/base/content/test/general/browser_e10s_about_process.js @@ -27,11 +27,11 @@ function AboutModule() { } AboutModule.prototype = { - newChannel: function(aURI, aLoadInfo) { + newChannel(aURI, aLoadInfo) { throw Components.results.NS_ERROR_NOT_IMPLEMENTED; }, - getURIFlags: function(aURI) { + getURIFlags(aURI) { for (let module of TEST_MODULES) { if (aURI.path.startsWith(module.path)) { return module.flags; @@ -42,7 +42,7 @@ AboutModule.prototype = { return 0; }, - getIndexedDBOriginPostfix: function(aURI) { + getIndexedDBOriginPostfix(aURI) { return null; }, @@ -50,13 +50,13 @@ AboutModule.prototype = { }; var AboutModuleFactory = { - createInstance: function(aOuter, aIID) { + createInstance(aOuter, aIID) { if (aOuter) throw Components.results.NS_ERROR_NO_AGGREGATION; return new AboutModule().QueryInterface(aIID); }, - lockFactory: function(aLock) { + lockFactory(aLock) { throw Components.results.NS_ERROR_NOT_IMPLEMENTED; }, diff --git a/browser/base/content/test/general/browser_fullscreen-window-open.js b/browser/base/content/test/general/browser_fullscreen-window-open.js index f6e0063328c6..169657ff1aa0 100644 --- a/browser/base/content/test/general/browser_fullscreen-window-open.js +++ b/browser/base/content/test/general/browser_fullscreen-window-open.js @@ -66,7 +66,7 @@ function test_open() { title: "test_open", param: "", }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -77,7 +77,7 @@ function test_open_with_size() { title: "test_open_with_size", param: "width=400,height=400", }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -88,7 +88,7 @@ function test_open_with_pos() { title: "test_open_with_pos", param: "top=200,left=200", }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -100,11 +100,11 @@ function test_open_with_outerSize() { title: "test_open_with_outerSize", param: "outerWidth=200,outerHeight=200", }, - successFn: function() { + successFn() { is(window.outerWidth, outerWidth, "Don't change window.outerWidth."); is(window.outerHeight, outerHeight, "Don't change window.outerHeight."); }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -116,11 +116,11 @@ function test_open_with_innerSize() { title: "test_open_with_innerSize", param: "innerWidth=200,innerHeight=200", }, - successFn: function() { + successFn() { is(window.innerWidth, innerWidth, "Don't change window.innerWidth."); is(window.innerHeight, innerHeight, "Don't change window.innerHeight."); }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -131,7 +131,7 @@ function test_open_with_dialog() { title: "test_open_with_dialog", param: "dialog=yes", }, - finalizeFn: function() {}, + finalizeFn() {}, }); } @@ -148,7 +148,7 @@ function test_open_when_open_new_window_by_pref() { title: "test_open_when_open_new_window_by_pref", param: "width=400,height=400", }, - finalizeFn: function() { + finalizeFn() { Services.prefs.clearUserPref(PREF_NAME); }, }); @@ -163,7 +163,7 @@ function test_open_with_pref_to_disable_in_fullscreen() { title: "test_open_with_pref_disabled_in_fullscreen", param: "width=400,height=400", }, - finalizeFn: function() { + finalizeFn() { Services.prefs.setBoolPref(PREF_DISABLE_OPEN_NEW_WINDOW, true); }, }); @@ -177,7 +177,7 @@ function test_open_from_chrome() { title: "test_open_from_chrome", param: "", }, - finalizeFn: function() {} + finalizeFn() {} }); } @@ -251,7 +251,7 @@ function waitForWindowOpen(aOptions) { let listener = new WindowListener(message.title, getBrowserURL(), { onSuccess: aOptions.successFn, - onFinalize: onFinalize, + onFinalize, }); Services.wm.addListener(listener); @@ -292,7 +292,7 @@ function waitForWindowOpenFromChrome(aOptions) { let listener = new WindowListener(message.title, getBrowserURL(), { onSuccess: aOptions.successFn, - onFinalize: onFinalize, + onFinalize, }); Services.wm.addListener(listener); @@ -312,7 +312,7 @@ WindowListener.prototype = { callback_onSuccess: null, callBack_onFinalize: null, - onOpenWindow: function(aXULWindow) { + onOpenWindow(aXULWindow) { Services.wm.removeListener(this); let domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -340,8 +340,8 @@ WindowListener.prototype = { }; domwindow.addEventListener("load", onLoad, true); }, - onCloseWindow: function(aXULWindow) {}, - onWindowTitleChange: function(aXULWindow, aNewTitle) {}, + onCloseWindow(aXULWindow) {}, + onWindowTitleChange(aXULWindow, aNewTitle) {}, QueryInterface: XPCOMUtils.generateQI([Ci.nsIWindowMediatorListener, Ci.nsISupports]), }; diff --git a/browser/base/content/test/general/browser_fxa_oauth.js b/browser/base/content/test/general/browser_fxa_oauth.js index b676d2bd06d9..5babfa638e9e 100644 --- a/browser/base/content/test/general/browser_fxa_oauth.js +++ b/browser/base/content/test/general/browser_fxa_oauth.js @@ -21,7 +21,7 @@ const HTTP_ENDPOINT_WITH_KEYS = "/browser/browser/base/content/test/general/brow var gTests = [ { desc: "FxA OAuth - should open a new tab, complete OAuth flow", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; let properURL = "http://example.com/browser/browser/base/content/test/general/browser_fxa_oauth.html"; @@ -74,7 +74,7 @@ var gTests = [ }, { desc: "FxA OAuth - should open a new tab, complete OAuth flow when forcing auth", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; let properURL = "http://example.com/browser/browser/base/content/test/general/browser_fxa_oauth.html"; @@ -131,7 +131,7 @@ var gTests = [ }, { desc: "FxA OAuth - should receive an error when there's a state mismatch", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -169,7 +169,7 @@ var gTests = [ }, { desc: "FxA OAuth - should be able to request keys during OAuth flow", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -211,7 +211,7 @@ var gTests = [ }, { desc: "FxA OAuth - should not receive keys if not explicitly requested", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; @@ -252,7 +252,7 @@ var gTests = [ }, { desc: "FxA OAuth - should receive an error if keys could not be obtained", - run: function() { + run() { return new Promise(function(resolve, reject) { let tabOpened = false; diff --git a/browser/base/content/test/general/browser_fxa_web_channel.js b/browser/base/content/test/general/browser_fxa_web_channel.js index ad4fb7b57ae4..a87c2338a6b4 100644 --- a/browser/base/content/test/general/browser_fxa_web_channel.js +++ b/browser/base/content/test/general/browser_fxa_web_channel.js @@ -23,7 +23,7 @@ const TEST_CHANNEL_ID = "account_updates_test"; var gTests = [ { desc: "FxA Web Channel - should receive message about profile changes", - run: function* () { + *run() { let client = new FxAccountsWebChannel({ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, @@ -37,7 +37,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: TEST_BASE_URL + "?profile_change" }, function* () { yield promiseObserver; @@ -46,7 +46,7 @@ var gTests = [ }, { desc: "fxa web channel - login messages should notify the fxAccounts object", - run: function* () { + *run() { let promiseLogin = new Promise((resolve, reject) => { let login = (accountData) => { @@ -66,13 +66,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - login: login + login } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: TEST_BASE_URL + "?login" }, function* () { yield promiseLogin; @@ -81,7 +81,7 @@ var gTests = [ }, { desc: "fxa web channel - can_link_account messages should respond", - run: function* () { + *run() { let properUrl = TEST_BASE_URL + "?can_link_account"; let promiseEcho = new Promise((resolve, reject) => { @@ -114,7 +114,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: properUrl }, function* () { yield promiseEcho; @@ -123,7 +123,7 @@ var gTests = [ }, { desc: "fxa web channel - logout messages should notify the fxAccounts object", - run: function* () { + *run() { let promiseLogout = new Promise((resolve, reject) => { let logout = (uid) => { Assert.equal(uid, 'uid'); @@ -136,13 +136,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - logout: logout + logout } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: TEST_BASE_URL + "?logout" }, function* () { yield promiseLogout; @@ -151,7 +151,7 @@ var gTests = [ }, { desc: "fxa web channel - delete messages should notify the fxAccounts object", - run: function* () { + *run() { let promiseDelete = new Promise((resolve, reject) => { let logout = (uid) => { Assert.equal(uid, 'uid'); @@ -164,13 +164,13 @@ var gTests = [ content_uri: TEST_HTTP_PATH, channel_id: TEST_CHANNEL_ID, helpers: { - logout: logout + logout } }); }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: TEST_BASE_URL + "?delete" }, function* () { yield promiseDelete; diff --git a/browser/base/content/test/general/browser_fxaccounts.js b/browser/base/content/test/general/browser_fxaccounts.js index cc7abad9ffdb..ae61ce0f3874 100644 --- a/browser/base/content/test/general/browser_fxaccounts.js +++ b/browser/base/content/test/general/browser_fxaccounts.js @@ -16,7 +16,7 @@ const TEST_ROOT = "http://example.com/browser/browser/base/content/test/general/ // The stub functions. let stubs = { - updateAppMenuItem: function() { + updateAppMenuItem() { return unstubs['updateAppMenuItem'].call(gFxAccounts).then(() => { Services.obs.notifyObservers(null, "test:browser_fxaccounts:updateAppMenuItem", null); }); @@ -25,7 +25,7 @@ const TEST_ROOT = "http://example.com/browser/browser/base/content/test/general/ // due to the promises it fires off at load time and there's no clear way to // know when they are done. // So just ensure openPreferences is called rather than whether it opens. - openPreferences: function() { + openPreferences() { Services.obs.notifyObservers(null, "test:browser_fxaccounts:openPreferences", null); } }; @@ -237,7 +237,7 @@ function setSignedInUser(verified) { sessionToken: "dead", kA: "beef", kB: "cafe", - verified: verified, + verified, oauthTokens: { // a token for the profile server. diff --git a/browser/base/content/test/general/browser_getshortcutoruri.js b/browser/base/content/test/general/browser_getshortcutoruri.js index a318ab6d1f04..7c54ac4975e1 100644 --- a/browser/base/content/test/general/browser_getshortcutoruri.js +++ b/browser/base/content/test/general/browser_getshortcutoruri.js @@ -19,7 +19,7 @@ function keywordResult(aURL, aPostData, aIsUnsafe) { function keyWordData() {} keyWordData.prototype = { - init: function(aKeyWord, aURL, aPostData, aSearchWord) { + init(aKeyWord, aURL, aPostData, aSearchWord) { this.keyword = aKeyWord; this.uri = makeURI(aURL); this.postData = aPostData; diff --git a/browser/base/content/test/general/browser_homeDrop.js b/browser/base/content/test/general/browser_homeDrop.js index 061ea17f0033..32228fca459e 100644 --- a/browser/base/content/test/general/browser_homeDrop.js +++ b/browser/base/content/test/general/browser_homeDrop.js @@ -32,7 +32,7 @@ add_task(function*() { let setHomepagePromise = new Promise(function(resolve) { let observer = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), - observe: function(subject, topic, data) { + observe(subject, topic, data) { is(topic, "nsPref:changed", "observed correct topic"); is(data, HOMEPAGE_PREF, "observed correct data"); let modified = Services.prefs.getComplexValue(HOMEPAGE_PREF, @@ -57,7 +57,7 @@ add_task(function*() { function dropInvalidURI() { return new Promise(resolve => { let consoleListener = { - observe: function(m) { + observe(m) { if (m.message.includes("NS_ERROR_DOM_BAD_URI")) { ok(true, "drop was blocked"); resolve(); diff --git a/browser/base/content/test/general/browser_keywordSearch.js b/browser/base/content/test/general/browser_keywordSearch.js index 4d64febef6d8..ff6ef4a0832f 100644 --- a/browser/base/content/test/general/browser_keywordSearch.js +++ b/browser/base/content/test/general/browser_keywordSearch.js @@ -20,7 +20,7 @@ function test() { waitForExplicitFinish(); let windowObserver = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { ok(false, "Alert window opened"); let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget); diff --git a/browser/base/content/test/general/browser_plainTextLinks.js b/browser/base/content/test/general/browser_plainTextLinks.js index 7a304fce0c89..a6f436dec1df 100644 --- a/browser/base/content/test/general/browser_plainTextLinks.js +++ b/browser/base/content/test/general/browser_plainTextLinks.js @@ -119,7 +119,7 @@ add_task(function *() { let contentAreaContextMenu = document.getElementById("contentAreaContextMenu"); for (let testid = 0; testid < checks.length; testid++) { - let menuPosition = yield ContentTask.spawn(gBrowser.selectedBrowser, { testid: testid }, function* (arg) { + let menuPosition = yield ContentTask.spawn(gBrowser.selectedBrowser, { testid }, function* (arg) { let range = content.tests[arg.testid](); // Get the range of the selection and determine its coordinates. These diff --git a/browser/base/content/test/general/browser_restore_isAppTab.js b/browser/base/content/test/general/browser_restore_isAppTab.js index 3e53efd326f7..1e98ae0dc118 100644 --- a/browser/base/content/test/general/browser_restore_isAppTab.js +++ b/browser/base/content/test/general/browser_restore_isAppTab.js @@ -14,7 +14,7 @@ function getMinidumpDirectory() { // This observer is needed so we can clean up all evidence of the crash so // the testrunner thinks things are peachy. var CrashObserver = { - observe: function(subject, topic, data) { + observe(subject, topic, data) { is(topic, 'ipc:content-shutdown', 'Received correct observer topic.'); ok(subject instanceof Ci.nsIPropertyBag2, 'Subject implements nsIPropertyBag2.'); diff --git a/browser/base/content/test/general/browser_sanitize-timespans.js b/browser/base/content/test/general/browser_sanitize-timespans.js index f1096246c35c..813e72f1af7a 100644 --- a/browser/base/content/test/general/browser_sanitize-timespans.js +++ b/browser/base/content/test/general/browser_sanitize-timespans.js @@ -31,7 +31,7 @@ function promiseDownloadRemoved(list) { let deferred = Promise.defer(); let view = { - onDownloadRemoved: function(download) { + onDownloadRemoved(download) { list.removeView(view); deferred.resolve(); } @@ -58,11 +58,11 @@ function countEntries(name, message, check) { let count; FormHistory.count(obj, { handleResult: result => count = result, - handleError: function(error) { + handleError(error) { deferred.reject(error) throw new Error("Error occurred searching form history: " + error); }, - handleCompletion: function(reason) { + handleCompletion(reason) { if (!reason) { check(count, message); deferred.resolve(); @@ -493,11 +493,11 @@ function* setupFormHistory() { let results = []; FormHistory.search(terms, params, { handleResult: result => results.push(result), - handleError: function(error) { + handleError(error) { deferred.reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion: function(reason) { deferred.resolve(results); } + handleCompletion(reason) { deferred.resolve(results); } }); return deferred.promise; } @@ -505,11 +505,11 @@ function* setupFormHistory() { function update(changes) { let deferred = Promise.defer(); - FormHistory.update(changes, { handleError: function(error) { + FormHistory.update(changes, { handleError(error) { deferred.reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion: function(reason) { deferred.resolve(); } + handleCompletion(reason) { deferred.resolve(); } }); return deferred.promise; } diff --git a/browser/base/content/test/general/browser_sanitizeDialog.js b/browser/base/content/test/general/browser_sanitizeDialog.js index e7708aede954..7b469e76eeb4 100644 --- a/browser/base/content/test/general/browser_sanitizeDialog.js +++ b/browser/base/content/test/general/browser_sanitizeDialog.js @@ -572,7 +572,7 @@ add_task(function* test_offline_cache() { // Check if the cache has been deleted var size = -1; var visitor = { - onCacheStorageInfo: function(aEntryCount, aConsumption, aCapacity, aDiskDirectory) + onCacheStorageInfo(aEntryCount, aConsumption, aCapacity, aDiskDirectory) { size = aConsumption; } @@ -583,8 +583,8 @@ add_task(function* test_offline_cache() { }; var cacheListener = { - onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable: function(entry, isnew, unused, status) { + onCacheEntryCheck() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, + onCacheEntryAvailable(entry, isnew, unused, status) { is(status, Cr.NS_OK); var stream = entry.openOutputStream(0); var content = "content"; @@ -648,7 +648,7 @@ WindowHelper.prototype = { /** * "Presses" the dialog's OK button. */ - acceptDialog: function() { + acceptDialog() { is(this.win.document.documentElement.getButton("accept").disabled, false, "Dialog's OK button should not be disabled"); this.win.document.documentElement.acceptDialog(); @@ -657,7 +657,7 @@ WindowHelper.prototype = { /** * "Presses" the dialog's Cancel button. */ - cancelDialog: function() { + cancelDialog() { this.win.document.documentElement.cancelDialog(); }, @@ -669,7 +669,7 @@ WindowHelper.prototype = { * @param aShouldBeShown * True if you expect the details to be shown and false if hidden */ - checkDetails: function(aShouldBeShown) { + checkDetails(aShouldBeShown) { let button = this.getDetailsButton(); let list = this.getItemList(); let hidden = list.hidden || list.collapsed; @@ -700,7 +700,7 @@ WindowHelper.prototype = { * @param aCheckState * True if the checkbox should be checked, false otherwise */ - checkPrefCheckbox: function(aPrefName, aCheckState) { + checkPrefCheckbox(aPrefName, aCheckState) { var pref = "privacy.cpd." + aPrefName; var cb = this.win.document.querySelectorAll( "#itemList > [preference='" + pref + "']"); @@ -712,7 +712,7 @@ WindowHelper.prototype = { /** * Makes sure all the checkboxes are checked. */ - _checkAllCheckboxesCustom: function(check) { + _checkAllCheckboxesCustom(check) { var cb = this.win.document.querySelectorAll("#itemList > [preference]"); ok(cb.length > 1, "found checkboxes for preferences"); for (var i = 0; i < cb.length; ++i) { @@ -722,39 +722,39 @@ WindowHelper.prototype = { } }, - checkAllCheckboxes: function() { + checkAllCheckboxes() { this._checkAllCheckboxesCustom(true); }, - uncheckAllCheckboxes: function() { + uncheckAllCheckboxes() { this._checkAllCheckboxesCustom(false); }, /** * @return The details progressive disclosure button */ - getDetailsButton: function() { + getDetailsButton() { return this.win.document.getElementById("detailsExpander"); }, /** * @return The dialog's duration dropdown */ - getDurationDropdown: function() { + getDurationDropdown() { return this.win.document.getElementById("sanitizeDurationChoice"); }, /** * @return The item list hidden by the details progressive disclosure button */ - getItemList: function() { + getItemList() { return this.win.document.getElementById("itemList"); }, /** * @return The clear-everything warning box */ - getWarningPanel: function() { + getWarningPanel() { return this.win.document.getElementById("sanitizeEverythingWarningBox"); }, @@ -762,7 +762,7 @@ WindowHelper.prototype = { * @return True if the "Everything" warning panel is visible (as opposed to * the tree) */ - isWarningPanelVisible: function() { + isWarningPanelVisible() { return !this.getWarningPanel().hidden; }, @@ -774,7 +774,7 @@ WindowHelper.prototype = { * caller is expected to call waitForAsyncUpdates at some point; if false is * returned, waitForAsyncUpdates is called automatically. */ - open: function() { + open() { let wh = this; function windowObserver(aSubject, aTopic, aData) { @@ -835,7 +835,7 @@ WindowHelper.prototype = { * @param aDurVal * One of the Sanitizer.TIMESPAN_* values */ - selectDuration: function(aDurVal) { + selectDuration(aDurVal) { this.getDurationDropdown().value = aDurVal; if (aDurVal === Sanitizer.TIMESPAN_EVERYTHING) { is(this.isWarningPanelVisible(), true, @@ -850,7 +850,7 @@ WindowHelper.prototype = { /** * Toggles the details progressive disclosure button. */ - toggleDetails: function() { + toggleDetails() { this.getDetailsButton().click(); } }; @@ -898,11 +898,11 @@ function promiseAddFormEntryWithMinutesAgo(aMinutesAgo) { return new Promise((resolve, reject) => FormHistory.update({ op: "add", fieldname: name, value: "dummy", firstUsed: timestamp }, - { handleError: function(error) { + { handleError(error) { reject(); throw new Error("Error occurred updating form history: " + error); }, - handleCompletion: function(reason) { + handleCompletion(reason) { resolve(name); } }) @@ -918,11 +918,11 @@ function formNameExists(name) let count = 0; FormHistory.count({ fieldname: name }, { handleResult: result => count = result, - handleError: function(error) { + handleError(error) { reject(error); throw new Error("Error occurred searching form history: " + error); }, - handleCompletion: function(reason) { + handleCompletion(reason) { if (!reason) { resolve(count); } diff --git a/browser/base/content/test/general/browser_save_link_when_window_navigates.js b/browser/base/content/test/general/browser_save_link_when_window_navigates.js index 2da54eb92351..103985ac9f6f 100644 --- a/browser/base/content/test/general/browser_save_link_when_window_navigates.js +++ b/browser/base/content/test/general/browser_save_link_when_window_navigates.js @@ -90,13 +90,13 @@ function triggerSave(aWindow, aCallback) { var windowObserver = { - setCallback: function(aCallback) { + setCallback(aCallback) { if (this._callback) { ok(false, "Should only be dealing with one callback at a time."); } this._callback = aCallback; }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic != "domwindowopened") { return; } diff --git a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js index 92fb7bd0392f..6da92c10e478 100644 --- a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js +++ b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js @@ -15,17 +15,17 @@ function createTemporarySaveDirectory() { function promiseNoCacheEntry(filename) { return new Promise((resolve, reject) => { Visitor.prototype = { - onCacheStorageInfo: function(num, consumption) + onCacheStorageInfo(num, consumption) { info("disk storage contains " + num + " entries"); }, - onCacheEntryInfo: function(uri) + onCacheEntryInfo(uri) { let urispec = uri.asciiSpec; info(urispec); is(urispec.includes(filename), false, "web content present in disk cache"); }, - onCacheEntryVisitCompleted: function() + onCacheEntryVisitCompleted() { resolve(); } diff --git a/browser/base/content/test/general/browser_tabfocus.js b/browser/base/content/test/general/browser_tabfocus.js index 96b6b315388b..42552caa5ae4 100644 --- a/browser/base/content/test/general/browser_tabfocus.js +++ b/browser/base/content/test/general/browser_tabfocus.js @@ -53,7 +53,7 @@ function* getFocusedElementForBrowser(browser, dontCheckExtraFocus = false) // additional focus related properties. This is needed as both URLs are // loaded using the same child process and share focus managers. browser.messageManager.sendAsyncMessage("Browser:GetFocusedElement", - { dontCheckExtraFocus : dontCheckExtraFocus }); + { dontCheckExtraFocus }); }); } var focusedWindow = {}; @@ -113,7 +113,7 @@ function focusInChild() } } - sendSyncMessage("Browser:GetCurrentFocus", { details : details }); + sendSyncMessage("Browser:GetCurrentFocus", { details }); }); } @@ -122,7 +122,7 @@ function focusElementInChild(elementid, type) let browser = (elementid.indexOf("1") >= 0) ? browser1 : browser2; if (gMultiProcessBrowser) { browser.messageManager.sendAsyncMessage("Browser:ChangeFocus", - { id: elementid, type: type }); + { id: elementid, type }); } else { browser.contentDocument.getElementById(elementid)[type](); diff --git a/browser/base/content/test/general/browser_tabopen_reflows.js b/browser/base/content/test/general/browser_tabopen_reflows.js index 4eb6c77ab1ab..eed2eecb1417 100644 --- a/browser/base/content/test/general/browser_tabopen_reflows.js +++ b/browser/base/content/test/general/browser_tabopen_reflows.js @@ -113,7 +113,7 @@ add_task(function*() { }); var observer = { - reflow: function(start, end) { + reflow(start, end) { // Gather information about the current code path. let path = (new Error().stack).split("\n").slice(1).map(line => { return line.replace(/:\d+:\d+$/, ""); @@ -136,7 +136,7 @@ var observer = { ok(false, "unexpected uninterruptible reflow '" + pathWithLineNumbers + "'"); }, - reflowInterruptible: function(start, end) { + reflowInterruptible(start, end) { // We're not interested in interruptible reflows. }, diff --git a/browser/base/content/test/general/browser_trackingUI_4.js b/browser/base/content/test/general/browser_trackingUI_4.js index 234b790acb44..ba0478f7f852 100644 --- a/browser/base/content/test/general/browser_trackingUI_4.js +++ b/browser/base/content/test/general/browser_trackingUI_4.js @@ -28,7 +28,7 @@ function waitForSecurityChange(numChanges = 1) { return new Promise(resolve => { let n = 0; let listener = { - onSecurityChange: function() { + onSecurityChange() { n = n + 1; info("Received onSecurityChange event " + n + " of " + numChanges); if (n >= numChanges) { diff --git a/browser/base/content/test/general/browser_trackingUI_6.js b/browser/base/content/test/general/browser_trackingUI_6.js index be47263ba3c1..33a337231f1e 100644 --- a/browser/base/content/test/general/browser_trackingUI_6.js +++ b/browser/base/content/test/general/browser_trackingUI_6.js @@ -4,7 +4,7 @@ function waitForSecurityChange(numChanges = 1) { return new Promise(resolve => { let n = 0; let listener = { - onSecurityChange: function() { + onSecurityChange() { n = n + 1; info("Received onSecurityChange event " + n + " of " + numChanges); if (n >= numChanges) { diff --git a/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js b/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js index eedc7116b30c..2afedba0dac9 100644 --- a/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js +++ b/browser/base/content/test/general/browser_viewSourceInTabOnViewSource.js @@ -1,7 +1,7 @@ function wait_while_tab_is_busy() { return new Promise(resolve => { let progressListener = { - onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) { gBrowser.removeProgressListener(this); setTimeout(resolve, 0); diff --git a/browser/base/content/test/general/browser_web_channel.js b/browser/base/content/test/general/browser_web_channel.js index f1bcd4711bd7..ab7eaaf21f8d 100644 --- a/browser/base/content/test/general/browser_web_channel.js +++ b/browser/base/content/test/general/browser_web_channel.js @@ -20,7 +20,7 @@ const HTTP_REDIRECTED_IFRAME_PATH = "http://example.org"; var gTests = [ { desc: "WebChannel generic message", - run: function* () { + *run() { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("generic", Services.io.newURI(HTTP_PATH, null, null)); @@ -38,7 +38,7 @@ var gTests = [ }, { desc: "WebChannel generic message in a private window.", - run: function* () { + *run() { let promiseTestDone = new Promise(function(resolve, reject) { let channel = new WebChannel("generic", Services.io.newURI(HTTP_PATH, null, null)); channel.listen(function(id, message, target) { @@ -58,7 +58,7 @@ var gTests = [ }, { desc: "WebChannel two way communication", - run: function* () { + *run() { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("twoway", Services.io.newURI(HTTP_PATH, null, null)); @@ -85,7 +85,7 @@ var gTests = [ }, { desc: "WebChannel two way communication in an iframe", - run: function* () { + *run() { let parentChannel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); let iframeChannel = new WebChannel("twoway", Services.io.newURI(HTTP_IFRAME_PATH, null, null)); let promiseTestDone = new Promise(function(resolve, reject) { @@ -108,7 +108,7 @@ var gTests = [ }); }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?iframe" }, function* () { yield promiseTestDone; @@ -119,7 +119,7 @@ var gTests = [ }, { desc: "WebChannel response to a redirected iframe", - run: function* () { + *run() { /** * This test checks that WebChannel responses are only sent * to an iframe if the iframe has not redirected to another origin. @@ -172,7 +172,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?iframe_pre_redirect" }, function* () { yield promiseTestDone; @@ -183,7 +183,7 @@ var gTests = [ }, { desc: "WebChannel multichannel", - run: function* () { + *run() { return new Promise(function(resolve, reject) { let tab; let channel = new WebChannel("multichannel", Services.io.newURI(HTTP_PATH, null, null)); @@ -200,7 +200,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send, using system principal", - run: function* () { + *run() { let channel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); // an unsolicted message is sent from Chrome->Content which is then @@ -230,7 +230,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send, using target origin's principal", - run: function* () { + *run() { let targetURI = Services.io.newURI(HTTP_PATH, null, null); let channel = new WebChannel("echo", targetURI); @@ -263,7 +263,7 @@ var gTests = [ }, { desc: "WebChannel unsolicited send with principal mismatch", - run: function* () { + *run() { let targetURI = Services.io.newURI(HTTP_PATH, null, null); let channel = new WebChannel("echo", targetURI); @@ -284,7 +284,7 @@ var gTests = [ }); yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, + gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?unsolicited" }, function* (targetBrowser) { @@ -314,7 +314,7 @@ var gTests = [ }, { desc: "WebChannel non-window target", - run: function* () { + *run() { /** * This test ensures messages can be received from and responses * sent to non-window elements. @@ -350,7 +350,7 @@ var gTests = [ }, { desc: "WebChannel disallows non-string message from non-whitelisted origin", - run: function* () { + *run() { /** * This test ensures that non-string messages can't be sent via WebChannels. * We create a page (on a non-whitelisted origin) which should send us two @@ -377,7 +377,7 @@ var gTests = [ }, { desc: "WebChannel allows both string and non-string message from whitelisted origin", - run: function* () { + *run() { /** * Same process as above, but we whitelist the origin before loading the page, * and expect to get *both* messages back (each exactly once). @@ -419,7 +419,7 @@ var gTests = [ }, { desc: "WebChannel errors handling the message are delivered back to content", - run: function* () { + *run() { const ERRNO_UNKNOWN_ERROR = 999; // WebChannel.jsm doesn't export this. // The channel where we purposely fail responding to a command. @@ -455,7 +455,7 @@ var gTests = [ }, { desc: "WebChannel errors due to an invalid channel are delivered back to content", - run: function* () { + *run() { const ERRNO_NO_SUCH_CHANNEL = 2; // WebChannel.jsm doesn't export this. // The channel where we see the response when the content sees the error let echoChannel = new WebChannel("echo", Services.io.newURI(HTTP_PATH, null, null)); diff --git a/browser/base/content/test/general/browser_windowactivation.js b/browser/base/content/test/general/browser_windowactivation.js index cac9e8866d6c..4759bb68b80c 100644 --- a/browser/base/content/test/general/browser_windowactivation.js +++ b/browser/base/content/test/general/browser_windowactivation.js @@ -109,8 +109,8 @@ function reallyRunTests() { function sendGetBackgroundRequest(ifChanged) { - browser1.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged: ifChanged }); - browser2.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged: ifChanged }); + browser1.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged }); + browser2.messageManager.sendAsyncMessage("Test:GetBackgroundColor", { ifChanged }); } function runOtherWindowTests() { @@ -177,7 +177,7 @@ function childFunction() if (oldColor != color || !ifChanged) { expectingResponse = false; oldColor = color; - sendAsyncMessage("Test:BackgroundColorChanged", { color: color }); + sendAsyncMessage("Test:BackgroundColorChanged", { color }); } }, 20); } diff --git a/browser/base/content/test/general/browser_windowopen_reflows.js b/browser/base/content/test/general/browser_windowopen_reflows.js index 8d82b715a5d4..c5b3d15f3065 100644 --- a/browser/base/content/test/general/browser_windowopen_reflows.js +++ b/browser/base/content/test/general/browser_windowopen_reflows.js @@ -73,7 +73,7 @@ function test() { } var observer = { - reflow: function(start, end) { + reflow(start, end) { // Gather information about the current code path. let stack = new Error().stack; let path = stack.split("\n").slice(1).map(line => { @@ -99,7 +99,7 @@ var observer = { ok(false, "unexpected uninterruptible reflow '" + pathWithLineNumbers + "'"); }, - reflowInterruptible: function(start, end) { + reflowInterruptible(start, end) { // We're not interested in interruptible reflows. }, diff --git a/browser/base/content/test/general/contentSearchUI.js b/browser/base/content/test/general/contentSearchUI.js index bbb9a2d85b87..87851f65c4e3 100644 --- a/browser/base/content/test/general/contentSearchUI.js +++ b/browser/base/content/test/general/contentSearchUI.js @@ -15,7 +15,7 @@ addMessageListener(TEST_MSG, msg => { var messageHandlers = { - init: function() { + init() { Services.search.currentEngine = Services.search.getEngineByName(ENGINE_NAME); let input = content.document.querySelector("input"); gController = @@ -29,19 +29,19 @@ var messageHandlers = { }); }, - key: function(arg) { + key(arg) { let keyName = typeof(arg) == "string" ? arg : arg.key; content.synthesizeKey(keyName, arg.modifiers || {}); let wait = arg.waitForSuggestions ? waitForSuggestions : cb => cb(); wait(ack.bind(null, "key")); }, - startComposition: function(arg) { + startComposition(arg) { content.synthesizeComposition({ type: "compositionstart", data: "" }); ack("startComposition"); }, - changeComposition: function(arg) { + changeComposition(arg) { let data = typeof(arg) == "string" ? arg : arg.data; content.synthesizeCompositionChange({ composition: { @@ -56,31 +56,31 @@ var messageHandlers = { wait(ack.bind(null, "changeComposition")); }, - commitComposition: function() { + commitComposition() { content.synthesizeComposition({ type: "compositioncommitasis" }); ack("commitComposition"); }, - focus: function() { + focus() { gController.input.focus(); ack("focus"); }, - blur: function() { + blur() { gController.input.blur(); ack("blur"); }, - waitForSearch: function() { + waitForSearch() { waitForContentSearchEvent("Search", aData => ack("waitForSearch", aData)); }, - waitForSearchSettings: function() { + waitForSearchSettings() { waitForContentSearchEvent("ManageEngines", aData => ack("waitForSearchSettings", aData)); }, - mousemove: function(itemIndex) { + mousemove(itemIndex) { let row; if (itemIndex == -1) { row = gController._table.firstChild; @@ -102,7 +102,7 @@ var messageHandlers = { content.synthesizeMouseAtCenter(row, event); }, - click: function(arg) { + click(arg) { let eltIdx = typeof(arg) == "object" ? arg.eltIdx : arg; let row; if (eltIdx == -1) { @@ -121,12 +121,12 @@ var messageHandlers = { ack("click"); }, - addInputValueToFormHistory: function() { + addInputValueToFormHistory() { gController.addInputValueToFormHistory(); ack("addInputValueToFormHistory"); }, - addDuplicateOneOff: function() { + addDuplicateOneOff() { let btn = gController._oneOffButtons[gController._oneOffButtons.length - 1]; let newBtn = btn.cloneNode(true); btn.parentNode.appendChild(newBtn); @@ -134,12 +134,12 @@ var messageHandlers = { ack("addDuplicateOneOff"); }, - removeLastOneOff: function() { + removeLastOneOff() { gController._oneOffButtons.pop().remove(); ack("removeLastOneOff"); }, - reset: function() { + reset() { // Reset both the input and suggestions by select all + delete. If there was // no text entered, this won't have any effect, so also escape to ensure the // suggestions table is closed. diff --git a/browser/base/content/test/general/head.js b/browser/base/content/test/general/head.js index 7becbbf91ceb..3bdd3f6fb710 100644 --- a/browser/base/content/test/general/head.js +++ b/browser/base/content/test/general/head.js @@ -307,9 +307,9 @@ function waitForAsyncUpdates(aCallback, aScope, aArguments) { let commit = db.createAsyncStatement("COMMIT"); commit.executeAsync({ - handleResult: function() {}, - handleError: function() {}, - handleCompletion: function(aReason) { + handleResult() {}, + handleError() {}, + handleCompletion(aReason) { aCallback.apply(scope, args); } }); @@ -418,7 +418,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows } let progressListener = { - onStateChange: function(webProgress, req, flags, status) { + onStateChange(webProgress, req, flags, status) { dump("waitForDocLoadAndStopIt: onStateChange " + flags.toString(16) + ": " + req.name + "\n"); if (webProgress.isTopLevel && @@ -470,7 +470,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows function waitForDocLoadComplete(aBrowser = gBrowser) { return new Promise(resolve => { let listener = { - onStateChange: function(webProgress, req, flags, status) { + onStateChange(webProgress, req, flags, status) { let docStop = Ci.nsIWebProgressListener.STATE_IS_NETWORK | Ci.nsIWebProgressListener.STATE_STOP; info("Saw state " + flags.toString(16) + " and status " + status.toString(16)); @@ -918,12 +918,12 @@ function promiseNewSearchEngine(basename) { info("Waiting for engine to be added: " + basename); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => Services.search.removeEngine(engine)); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { Assert.ok(false, "addEngine failed with error code " + errCode); reject(); }, @@ -966,7 +966,7 @@ function isSecurityState(expectedState) { function promiseOnBookmarkItemAdded(aExpectedURI) { return new Promise((resolve, reject) => { let bookmarksObserver = { - onItemAdded: function(aItemId, aFolderId, aIndex, aItemType, aURI) { + onItemAdded(aItemId, aFolderId, aIndex, aItemType, aURI) { info("Added a bookmark to " + aURI.spec); PlacesUtils.bookmarks.removeObserver(bookmarksObserver); if (aURI.equals(aExpectedURI)) { @@ -976,12 +976,12 @@ function promiseOnBookmarkItemAdded(aExpectedURI) { reject(new Error("Added an unexpected bookmark")); } }, - onBeginUpdateBatch: function() {}, - onEndUpdateBatch: function() {}, - onItemRemoved: function() {}, - onItemChanged: function() {}, - onItemVisited: function() {}, - onItemMoved: function() {}, + onBeginUpdateBatch() {}, + onEndUpdateBatch() {}, + onItemRemoved() {}, + onItemChanged() {}, + onItemVisited() {}, + onItemMoved() {}, QueryInterface: XPCOMUtils.generateQI([ Ci.nsINavBookmarkObserver, ]) @@ -1006,7 +1006,7 @@ function* loadBadCertPage(url) { // When the certificate exception dialog has opened, click the button to add // an exception. let certExceptionDialogObserver = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "cert-exception-ui-ready") { Services.obs.removeObserver(this, "cert-exception-ui-ready"); let certExceptionDialog = getCertExceptionDialog(EXCEPTION_DIALOG_URI); @@ -1073,7 +1073,7 @@ function setupRemoteClientsFixture(fixture) { Object.getOwnPropertyDescriptor(gFxAccounts, "remoteClients").get; Object.defineProperty(gFxAccounts, "remoteClients", { - get: function() { return fixture; } + get() { return fixture; } }); return oldRemoteClientsGetter; } diff --git a/browser/base/content/test/general/offlineByDefault.js b/browser/base/content/test/general/offlineByDefault.js index 72f7e52a01bc..fe6418f84f25 100644 --- a/browser/base/content/test/general/offlineByDefault.js +++ b/browser/base/content/test/general/offlineByDefault.js @@ -1,7 +1,7 @@ var offlineByDefault = { defaultValue: false, prefBranch: SpecialPowers.Cc["@mozilla.org/preferences-service;1"].getService(SpecialPowers.Ci.nsIPrefBranch), - set: function(allow) { + set(allow) { try { this.defaultValue = this.prefBranch.getBoolPref("offline-apps.allow_by_default"); } catch (e) { @@ -9,7 +9,7 @@ var offlineByDefault = { } this.prefBranch.setBoolPref("offline-apps.allow_by_default", allow); }, - reset: function() { + reset() { this.prefBranch.setBoolPref("offline-apps.allow_by_default", this.defaultValue); } } diff --git a/browser/base/content/test/general/parsingTestHelpers.jsm b/browser/base/content/test/general/parsingTestHelpers.jsm index 69c764483ec8..fc8b620300a9 100644 --- a/browser/base/content/test/general/parsingTestHelpers.jsm +++ b/browser/base/content/test/general/parsingTestHelpers.jsm @@ -86,7 +86,7 @@ function iterateOverPath(path, extensions) { try { // Iterate through the directory yield iterator.forEach(pathEntryIterator); - resolve({files: files, subdirs: subdirs}); + resolve({files, subdirs}); } catch (ex) { reject(ex); } finally { diff --git a/browser/base/content/test/newtab/browser_newtab_bug722273.js b/browser/base/content/test/newtab/browser_newtab_bug722273.js index 9a61a09f6491..1a6c9a401756 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug722273.js +++ b/browser/base/content/test/newtab/browser_newtab_bug722273.js @@ -38,13 +38,13 @@ function promiseAddFakeVisits() { let place = { uri: makeURI(URL), title: "fake site", - visits: visits + visits }; return new Promise((resolve, reject) => { PlacesUtils.asyncHistory.updatePlaces(place, { handleError: () => reject(new Error("Couldn't add visit")), - handleResult: function() {}, - handleCompletion: function() { + handleResult() {}, + handleCompletion() { NewTabUtils.links.populateCache(function() { NewTabUtils.allPages.update(); resolve(); diff --git a/browser/base/content/test/newtab/browser_newtab_bug725996.js b/browser/base/content/test/newtab/browser_newtab_bug725996.js index e0de809c8f86..253ef4bddc08 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug725996.js +++ b/browser/base/content/test/newtab/browser_newtab_bug725996.js @@ -9,7 +9,7 @@ add_task(function* () { yield* checkGrid("0,1,2,3,4,5,6,7,8"); function doDrop(data) { - return ContentTask.spawn(gBrowser.selectedBrowser, { data: data }, function*(args) { + return ContentTask.spawn(gBrowser.selectedBrowser, { data }, function*(args) { let dataTransfer = new content.DataTransfer("dragstart", false); dataTransfer.mozSetDataAt("text/x-moz-url", args.data, 0); let event = content.document.createEvent("DragEvent"); diff --git a/browser/base/content/test/newtab/browser_newtab_bug991210.js b/browser/base/content/test/newtab/browser_newtab_bug991210.js index f51360563964..6e0d0fe73c12 100644 --- a/browser/base/content/test/newtab/browser_newtab_bug991210.js +++ b/browser/base/content/test/newtab/browser_newtab_bug991210.js @@ -7,10 +7,10 @@ add_task(function* () { // add a test provider that waits for load let afterLoadProvider = { - getLinks: function(callback) { + getLinks(callback) { this.callback = callback; }, - addObserver: function() {}, + addObserver() {}, }; NewTabUtils.links.addProvider(afterLoadProvider); diff --git a/browser/base/content/test/newtab/browser_newtab_drag_drop.js b/browser/base/content/test/newtab/browser_newtab_drag_drop.js index da9d89de7459..bb38b8e82be3 100644 --- a/browser/base/content/test/newtab/browser_newtab_drag_drop.js +++ b/browser/base/content/test/newtab/browser_newtab_drag_drop.js @@ -76,7 +76,7 @@ add_task(function* () { function doDragEvent(sourceIndex, dropIndex) { return ContentTask.spawn(gBrowser.selectedBrowser, - { sourceIndex: sourceIndex, dropIndex: dropIndex }, function*(args) { + { sourceIndex, dropIndex }, function*(args) { let dataTransfer = new content.DataTransfer("dragstart", false); let event = content.document.createEvent("DragEvent"); event.initDragEvent("dragstart", true, true, content, 0, 0, 0, 0, 0, diff --git a/browser/base/content/test/newtab/browser_newtab_search.js b/browser/base/content/test/newtab/browser_newtab_search.js index 17f98bb71e3c..06339b52bed6 100644 --- a/browser/base/content/test/newtab/browser_newtab_search.js +++ b/browser/base/content/test/newtab/browser_newtab_search.js @@ -211,12 +211,12 @@ function promiseNewSearchEngine({name: basename, numLogos}) { let addEnginePromise = new Promise((resolve, reject) => { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); gNewEngines.push(engine); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/newtab/head.js b/browser/base/content/test/newtab/head.js index ab72161c5362..0c0ff02c1a0b 100644 --- a/browser/base/content/test/newtab/head.js +++ b/browser/base/content/test/newtab/head.js @@ -220,8 +220,8 @@ function fillHistory(aLinks) { PlacesUtils.asyncHistory.updatePlaces(place, { handleError: () => ok(false, "couldn't add visit to history"), - handleResult: function() {}, - handleCompletion: function() { + handleResult() {}, + handleCompletion() { if (--numLinks == 0) { resolve(); } diff --git a/browser/base/content/test/plugins/blocklist_proxy.js b/browser/base/content/test/plugins/blocklist_proxy.js index d0aa0e8e48e6..4eb281e03f13 100644 --- a/browser/base/content/test/plugins/blocklist_proxy.js +++ b/browser/base/content/test/plugins/blocklist_proxy.js @@ -19,7 +19,7 @@ var BlocklistProxy = { Ci.nsIBlocklistService, Ci.nsITimerCallback]), - init: function() { + init() { if (!this._uuid) { this._uuid = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator) @@ -30,7 +30,7 @@ var BlocklistProxy = { } }, - uninit: function() { + uninit() { if (this._uuid) { Cm.nsIComponentRegistrar.unregisterFactory(this._uuid, this); Cm.nsIComponentRegistrar.registerFactory(Components.ID(kBlocklistServiceUUID), @@ -41,33 +41,33 @@ var BlocklistProxy = { } }, - notify: function(aTimer) { + notify(aTimer) { }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { }, - isAddonBlocklisted: function(aAddon, aAppVersion, aToolkitVersion) { + isAddonBlocklisted(aAddon, aAppVersion, aToolkitVersion) { return false; }, - getAddonBlocklistState: function(aAddon, aAppVersion, aToolkitVersion) { + getAddonBlocklistState(aAddon, aAppVersion, aToolkitVersion) { return 0; // STATE_NOT_BLOCKED }, - getPluginBlocklistState: function(aPluginTag, aAppVersion, aToolkitVersion) { + getPluginBlocklistState(aPluginTag, aAppVersion, aToolkitVersion) { return 0; // STATE_NOT_BLOCKED }, - getAddonBlocklistURL: function(aAddon, aAppVersion, aToolkitVersion) { + getAddonBlocklistURL(aAddon, aAppVersion, aToolkitVersion) { return ""; }, - getPluginBlocklistURL: function(aPluginTag) { + getPluginBlocklistURL(aPluginTag) { return ""; }, - getPluginInfoURL: function(aPluginTag) { + getPluginInfoURL(aPluginTag) { return ""; }, } diff --git a/browser/base/content/test/plugins/browser_bug797677.js b/browser/base/content/test/plugins/browser_bug797677.js index f1bd15b7716f..dd972c91e623 100644 --- a/browser/base/content/test/plugins/browser_bug797677.js +++ b/browser/base/content/test/plugins/browser_bug797677.js @@ -22,7 +22,7 @@ add_task(function* () { let consoleService = Cc["@mozilla.org/consoleservice;1"] .getService(Ci.nsIConsoleService); let errorListener = { - observe: function(aMessage) { + observe(aMessage) { if (aMessage.message.includes("NS_ERROR_FAILURE")) gConsoleErrors++; } diff --git a/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js b/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js index c834b17215bc..31e741eb3205 100644 --- a/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js +++ b/browser/base/content/test/plugins/browser_pluginCrashReportNonDeterminism.js @@ -68,7 +68,7 @@ function preparePlugin(browser, pluginFallbackState) { // Somehow, I'm able to get away with overriding the getter for // this XPCOM object. Probably because I've got chrome privledges. Object.defineProperty(plugin, "pluginFallbackType", { - get: function() { + get() { return contentPluginFallbackState; } }); @@ -162,7 +162,7 @@ add_task(function* testChromeHearsPluginCrashFirst() { // actually crashing the plugin again. We hack around this by overriding // the pluginFallbackType again. Object.defineProperty(plugin, "pluginFallbackType", { - get: function() { + get() { return Ci.nsIObjectLoadingContent.PLUGIN_CRASHED; }, }); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification.js b/browser/base/content/test/popupNotifications/browser_popupNotification.js index 860179d68463..044a58939f86 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification.js @@ -17,37 +17,37 @@ function test() { var tests = [ { id: "Test#1", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.mainActionClicked, "mainAction was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.secondaryActionClicked, "secondaryAction was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2b", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions.push({ label: "Extra Secondary Action", @@ -56,18 +56,18 @@ var tests = [ }); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 1); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.extraSecondaryActionClicked, "extra secondary action was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#2c", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions.push({ label: "Extra Secondary Action", @@ -80,26 +80,26 @@ var tests = [ }); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 2); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.extraSecondaryActionClicked, "extra secondary action was clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, { id: "Test#3", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -108,7 +108,7 @@ var tests = [ // test opening a notification for a background browser // Note: test 4 to 6 share a tab. { id: "Test#4", - run: function* () { + *run() { let tab = gBrowser.addTab("http://example.com/"); yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); isnot(gBrowser.selectedTab, tab, "new tab isn't selected"); @@ -125,18 +125,18 @@ var tests = [ }, // now select that browser and test to see that the notification appeared { id: "Test#5", - run: function() { + run() { this.oldSelectedTab = gBrowser.selectedTab; gBrowser.selectedTab = gBrowser.tabs[gBrowser.tabs.length - 1]; }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, wrongBrowserNotificationObject); is(PopupNotifications.isPanelOpen, true, "isPanelOpen getter doesn't lie"); // switch back to the old browser gBrowser.selectedTab = this.oldSelectedTab; }, - onHidden: function(popup) { + onHidden(popup) { // actually remove the notification to prevent it from reappearing ok(wrongBrowserNotificationObject.dismissalCallbackTriggered, "dismissal callback triggered due to tab switch"); wrongBrowserNotification.remove(); @@ -146,7 +146,7 @@ var tests = [ }, // test that the removed notification isn't shown on browser re-select { id: "Test#6", - run: function* () { + *run() { let promiseTopic = promiseTopicObserved("PopupNotifications-updateNotShowing"); gBrowser.selectedTab = gBrowser.tabs[gBrowser.tabs.length - 1]; yield promiseTopic; @@ -158,24 +158,24 @@ var tests = [ // Test that two notifications with the same ID result in a single displayed // notification. { id: "Test#7", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); // Show the same notification twice this.notification1 = showNotification(this.notifyObj); this.notification2 = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); this.notification2.remove(); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, // Test that two notifications with different IDs are displayed { id: "Test#8", - run: function() { + run() { this.testNotif1 = new BasicNotification(this.id); this.testNotif1.message += " 1"; showNotification(this.testNotif1); @@ -184,7 +184,7 @@ var tests = [ this.testNotif2.id += "-2"; showNotification(this.testNotif2); }, - onShown: function(popup) { + onShown(popup) { is(popup.childNodes.length, 2, "two notifications are shown"); // Trigger the main command for the first notification, and the secondary // for the second. Need to do mainCommand first since the secondaryCommand @@ -193,7 +193,7 @@ var tests = [ is(popup.childNodes.length, 1, "only one notification left"); triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.testNotif1.mainActionClicked, "main action #1 was clicked"); ok(!this.testNotif1.secondaryActionClicked, "secondary action #1 wasn't clicked"); ok(!this.testNotif1.dismissalCallbackTriggered, "dismissal callback #1 wasn't called"); @@ -206,16 +206,16 @@ var tests = [ // Test notification without mainAction or secondaryActions, it should fall back // to a default button that dismisses the notification in place of the main action. { id: "Test#9", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction = null; this.notifyObj.secondaryActions = null; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -225,17 +225,17 @@ var tests = [ // to a default button that dismisses the notification in place of the main action // and ignore the passed secondaryActions. { id: "Test#10", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction = null; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { let notification = popup.childNodes[0]; is(notification.getAttribute("secondarybuttonhidden"), "true", "secondary button is hidden"); triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -243,7 +243,7 @@ var tests = [ }, // Test two notifications with different anchors { id: "Test#11", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.firstNotification = showNotification(this.notifyObj); this.notifyObj2 = new BasicNotification(this.id); @@ -252,14 +252,14 @@ var tests = [ // Second showNotification() overrides the first this.secondNotification = showNotification(this.notifyObj2); }, - onShown: function(popup) { + onShown(popup) { // This also checks that only one element is shown. checkPopup(popup, this.notifyObj2); is(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor shouldn't be visible"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { // Remove the notifications this.firstNotification.remove(); this.secondNotification.remove(); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_2.js b/browser/base/content/test/popupNotifications/browser_popupNotification_2.js index 4366d7ed7b37..21df05a55c3f 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_2.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_2.js @@ -14,16 +14,16 @@ function test() { var tests = [ // Test optional params { id: "Test#1", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions = undefined; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -31,19 +31,19 @@ var tests = [ }, // Test that icons appear { id: "Test#2", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.id = "geolocation"; this.notifyObj.anchorID = "geo-notification-icon"; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); isnot(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor should be visible"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { let icon = document.getElementById("geo-notification-icon"); isnot(icon.boxObject.width, 0, "geo anchor should be visible after dismissal"); @@ -55,7 +55,7 @@ var tests = [ // Test that persistence allows the notification to persist across reloads { id: "Test#3", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -64,7 +64,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); @@ -72,7 +72,7 @@ var tests = [ this.complete = true; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.complete, "Should only have hidden the notification after 3 page loads"); ok(this.notifyObj.removedCallbackTriggered, "removal callback triggered"); gBrowser.removeTab(gBrowser.selectedTab); @@ -81,7 +81,7 @@ var tests = [ }, // Test that a timeout allows the notification to persist across reloads { id: "Test#4", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -91,7 +91,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); @@ -100,7 +100,7 @@ var tests = [ this.complete = true; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.complete, "Should only have hidden the notification after the timeout was passed"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -110,7 +110,7 @@ var tests = [ // Test that setting persistWhileVisible allows a visible notification to // persist across location changes { id: "Test#5", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -119,7 +119,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); @@ -128,7 +128,7 @@ var tests = [ this.complete = true; dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.complete, "Should only have hidden the notification after it was dismissed"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -138,7 +138,7 @@ var tests = [ // Test that nested icon nodes correctly activate popups { id: "Test#6", - run: function() { + run() { // Add a temporary box as the anchor with a button this.box = document.createElement("box"); PopupNotifications.iconBox.appendChild(this.box); @@ -160,18 +160,18 @@ var tests = [ // amount. EventUtils.synthesizeMouse(button, 4, 4, {}); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification.remove(); this.box.parentNode.removeChild(this.box); } }, // Test that popupnotifications without popups have anchor icons shown { id: "Test#7", - run: function* () { + *run() { let notifyObj = new BasicNotification(this.id); notifyObj.anchorID = "geo-notification-icon"; notifyObj.addOptions({neverShow: true}); @@ -185,16 +185,16 @@ var tests = [ }, // Test notification close button { id: "Test#9", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; EventUtils.synthesizeMouseAtCenter(notification.closebutton, {}); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); @@ -202,17 +202,17 @@ var tests = [ }, // Test notification when chrome is hidden { id: "Test#10", - run: function() { + run() { window.locationbar.visible = false; this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); is(popup.anchorNode.className, "tabbrowser-tab", "notification anchored to tab"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered"); this.notification.remove(); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js b/browser/base/content/test/popupNotifications/browser_popupNotification_3.js index 9476cc5e60ad..74a917afa9fb 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_3.js @@ -14,25 +14,25 @@ function test() { var tests = [ // Test notification is removed when dismissed if removeOnDismissal is true { id: "Test#1", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.addOptions({ removeOnDismissal: true }); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback wasn't triggered"); ok(this.notifyObj.removedCallbackTriggered, "removed callback triggered"); } }, // Test multiple notification icons are shown { id: "Test#2", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -43,7 +43,7 @@ var tests = [ this.notifyObj2.anchorID = "geo-notification-icon"; this.notification2 = showNotification(this.notifyObj2); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj2); // check notifyObj1 anchor icon is showing @@ -55,7 +55,7 @@ var tests = [ dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification1.remove(); ok(this.notifyObj1.removedCallbackTriggered, "removed callback triggered"); @@ -65,7 +65,7 @@ var tests = [ }, // Test that multiple notification icons are removed when switching tabs { id: "Test#3", - run: function* () { + *run() { // show the notification on old tab. this.notifyObjOld = new BasicNotification(this.id); this.notifyObjOld.anchorID = "default-notification-icon"; @@ -80,7 +80,7 @@ var tests = [ this.notifyObjNew.anchorID = "geo-notification-icon"; this.notificationNew = showNotification(this.notifyObjNew); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObjNew); // check notifyObjOld anchor icon is removed @@ -92,7 +92,7 @@ var tests = [ dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notificationNew.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -102,14 +102,14 @@ var tests = [ }, // test security delay - too early { id: "Test#4", - run: function() { + run() { // Set the security delay to 100s PopupNotifications.buttonDelay = 100000; this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); @@ -119,21 +119,21 @@ var tests = [ }); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked because it was too soon"); ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); } }, // test security delay - after delay { id: "Test#5", - run: function() { + run() { // Set the security delay to 10ms PopupNotifications.buttonDelay = 10; this.notifyObj = new BasicNotification(this.id); showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); // Wait until after the delay to trigger the main action @@ -142,7 +142,7 @@ var tests = [ }, 500); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.mainActionClicked, "mainAction was clicked after the delay"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback was not triggered"); PopupNotifications.buttonDelay = PREF_SECURITY_DELAY_INITIAL; @@ -150,7 +150,7 @@ var tests = [ }, // reload removes notification { id: "Test#6", - run: function* () { + *run() { yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); let notifyObj = new BasicNotification(this.id); notifyObj.options.eventCallback = function(eventName) { @@ -167,7 +167,7 @@ var tests = [ }, // location change in background tab removes notification { id: "Test#7", - run: function* () { + *run() { let oldSelectedTab = gBrowser.selectedTab; let newTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); gBrowser.selectedTab = oldSelectedTab; @@ -192,7 +192,7 @@ var tests = [ }, // Popup notification anchor shouldn't disappear when a notification with the same ID is re-added in a background tab { id: "Test#8", - run: function* () { + *run() { yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.com/"); let originalTab = gBrowser.selectedTab; let bgTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -227,7 +227,7 @@ var tests = [ }, // location change in an embedded frame should not remove a notification { id: "Test#9", - run: function* () { + *run() { yield promiseTabLoadEvent(gBrowser.selectedTab, "data:text/html;charset=utf8,"); this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.eventCallback = function(eventName) { @@ -237,7 +237,7 @@ var tests = [ }; showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { let self = this; let progressListener = { onLocationChange: function onLocationChange() { @@ -259,11 +259,11 @@ var tests = [ content.document.getElementById("iframe") .setAttribute("src", "http://example.org/"); }, - onHidden: function() {} + onHidden() {} }, // Popup Notifications should catch exceptions from callbacks { id: "Test#10", - run: function() { + run() { this.testNotif1 = new BasicNotification(this.id); this.testNotif1.message += " 1"; this.notification1 = showNotification(this.testNotif1); @@ -285,11 +285,11 @@ var tests = [ }; this.notification2 = showNotification(this.testNotif2); }, - onShown: function(popup) { + onShown(popup) { is(popup.childNodes.length, 2, "two notifications are shown"); dismissNotification(popup); }, - onHidden: function() { + onHidden() { this.notification1.remove(); this.notification2.remove(); } diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_4.js b/browser/base/content/test/popupNotifications/browser_popupNotification_4.js index 466670cf1d33..4780d52afcb3 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_4.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_4.js @@ -14,41 +14,41 @@ function test() { var tests = [ // Popup Notifications main actions should catch exceptions from callbacks { id: "Test#1", - run: function() { + run() { this.testNotif = new ErrorNotification(this.id); showNotification(this.testNotif); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.testNotif); triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.testNotif.mainActionClicked, "main action has been triggered"); } }, // Popup Notifications secondary actions should catch exceptions from callbacks { id: "Test#2", - run: function() { + run() { this.testNotif = new ErrorNotification(this.id); showNotification(this.testNotif); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.testNotif); triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.testNotif.secondaryActionClicked, "secondary action has been triggered"); } }, // Existing popup notification shouldn't disappear when adding a dismissed notification { id: "Test#3", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; this.notification1 = showNotification(this.notifyObj1); }, - onShown: function(popup) { + onShown(popup) { // Now show a dismissed notification, and check that it doesn't clobber // the showing one. this.notifyObj2 = new BasicNotification(this.id); @@ -67,14 +67,14 @@ var tests = [ dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification1.remove(); this.notification2.remove(); } }, // Showing should be able to modify the popup data { id: "Test#4", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); let normalCallback = this.notifyObj.options.eventCallback; this.notifyObj.options.eventCallback = function(eventName) { @@ -85,18 +85,18 @@ var tests = [ }; showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { // checkPopup checks for the matching label. Note that this assumes that // this.notifyObj.mainAction is the same as notification.mainAction, // which could be a problem if we ever decided to deep-copy. checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden: function() { } + onHidden() { } }, // Moving a tab to a new window should remove non-swappable notifications. { id: "Test#5", - run: function* () { + *run() { yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); let notifyObj = new BasicNotification(this.id); @@ -124,7 +124,7 @@ var tests = [ }, // Moving a tab to a new window should preserve swappable notifications. { id: "Test#6", - run: function* () { + *run() { yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); let notifyObj = new BasicNotification(this.id); let originalCallback = notifyObj.options.eventCallback; @@ -165,16 +165,16 @@ var tests = [ }, // the main action callback can keep the notification. { id: "Test#8", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction.dismiss = true; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); ok(!this.notifyObj.removedCallbackTriggered, "removed callback wasn't triggered"); this.notification.remove(); @@ -182,16 +182,16 @@ var tests = [ }, // a secondary action callback can keep the notification. { id: "Test#9", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions[0].dismiss = true; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); ok(!this.notifyObj.removedCallbackTriggered, "removed callback wasn't triggered"); this.notification.remove(); @@ -199,7 +199,7 @@ var tests = [ }, // returning true in the showing callback should dismiss the notification. { id: "Test#10", - run: function() { + run() { let notifyObj = new BasicNotification(this.id); let originalCallback = notifyObj.options.eventCallback; notifyObj.options.eventCallback = function(eventName) { diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_5.js b/browser/base/content/test/popupNotifications/browser_popupNotification_5.js index 99cb6b824447..83c0aebe6e02 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_5.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_5.js @@ -16,11 +16,11 @@ var gNotification; var tests = [ // panel updates should fire the showing and shown callbacks again. { id: "Test#1", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); this.notifyObj.showingCallbackTriggered = false; @@ -35,11 +35,11 @@ var tests = [ this.notification.remove(); }, - onHidden: function() { } + onHidden() { } }, // A first dismissed notification shouldn't stop _update from showing a second notification { id: "Test#2", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -55,16 +55,16 @@ var tests = [ this.notification2.dismissed = false; PopupNotifications._update(); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj2); this.notification1.remove(); this.notification2.remove(); }, - onHidden: function(popup) { } + onHidden(popup) { } }, // The anchor icon should be shown for notifications in background windows. { id: "Test#3", - run: function* () { + *run() { let notifyObj = new BasicNotification(this.id); notifyObj.options.dismissed = true; @@ -84,7 +84,7 @@ var tests = [ // Test that persistent doesn't allow the notification to persist after // navigation. { id: "Test#4", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -93,7 +93,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; yield promiseTabLoadEvent(gBrowser.selectedTab, "http://example.org/"); @@ -105,7 +105,7 @@ var tests = [ this.complete = true; triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(!this.complete, "Should have hidden the notification after navigation"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -115,7 +115,7 @@ var tests = [ // Test that persistent allows the notification to persist until explicitly // dismissed. { id: "Test#5", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); this.notifyObj = new BasicNotification(this.id); @@ -124,7 +124,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.complete = false; // Notification should persist after attempt to dismiss by clicking on the @@ -136,7 +136,7 @@ var tests = [ this.complete = true; triggerSecondaryCommand(popup, 0); }, - onHidden: function(popup) { + onHidden(popup) { ok(this.complete, "Should have hidden the notification after clicking Not Now"); this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); @@ -146,16 +146,16 @@ var tests = [ // Test that persistent panels are still open after switching to another tab // and back. { id: "Test#6a", - run: function* () { + *run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.persistent = true; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); }, - onHidden: function(popup) { + onHidden(popup) { ok(true, "Should have hidden the notification after tab switch"); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -164,7 +164,7 @@ var tests = [ // Second part of the previous test that compensates for the limitation in // runNextTest that expects a single onShown/onHidden invocation per test. { id: "Test#6b", - run: function* () { + *run() { let id = PopupNotifications.panel.firstChild.getAttribute("popupid"); ok(id.endsWith("Test#6a"), "Should have found the notification from Test6a"); ok(PopupNotifications.isPanelOpen, "Should have shown the popup again after getting back to the tab"); @@ -176,7 +176,7 @@ var tests = [ // Test that persistent panels are still open after switching to another // window and back. { id: "Test#7", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -213,7 +213,7 @@ var tests = [ }, // Test that only the first persistent notification is shown on update { id: "Test#8", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -228,16 +228,16 @@ var tests = [ PopupNotifications._update(); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj1); this.notification1.remove(); this.notification2.remove(); }, - onHidden: function(popup) { } + onHidden(popup) { } }, // Test that persistent notifications are shown stacked by anchor on update { id: "Test#9", - run: function() { + run() { this.notifyObj1 = new BasicNotification(this.id); this.notifyObj1.id += "_1"; this.notifyObj1.anchorID = "default-notification-icon"; @@ -258,7 +258,7 @@ var tests = [ PopupNotifications._update(); }, - onShown: function(popup) { + onShown(popup) { let notifications = popup.childNodes; is(notifications.length, 2, "two notifications displayed"); let [notification1, notification2] = notifications; @@ -269,6 +269,6 @@ var tests = [ this.notification2.remove(); this.notification3.remove(); }, - onHidden: function(popup) { } + onHidden(popup) { } }, ]; diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js b/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js index 0516164d8236..41b55db04b2a 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js @@ -37,25 +37,25 @@ var gNotification; var tests = [ // Test that passing the checkbox field shows the checkbox. { id: "show_checkbox", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", }; gNotification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; checkCheckbox(notification.checkbox, "This is a checkbox"); triggerMainCommand(popup); }, - onHidden: function() { } + onHidden() { } }, // Test checkbox being checked by default { id: "checkbox_checked", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "Check this", @@ -63,18 +63,18 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; checkCheckbox(notification.checkbox, "Check this", true); triggerMainCommand(popup); }, - onHidden: function() { } + onHidden() { } }, // Test checkbox passing the checkbox state on mainAction { id: "checkbox_passCheckboxChecked_mainAction", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.mainAction.callback = ({checkboxChecked}) => this.mainActionChecked = checkboxChecked; this.notifyObj.options.checkbox = { @@ -82,7 +82,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -92,14 +92,14 @@ var tests = [ checkCheckbox(checkbox, "This is a checkbox", true); triggerMainCommand(popup); }, - onHidden: function() { + onHidden() { is(this.mainActionChecked, true, "mainAction callback is passed the correct checkbox value"); } }, // Test checkbox passing the checkbox state on secondaryAction { id: "checkbox_passCheckboxChecked_secondaryAction", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.secondaryActions = [{ label: "Test Secondary", @@ -111,7 +111,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -121,14 +121,14 @@ var tests = [ checkCheckbox(checkbox, "This is a checkbox", true); triggerSecondaryCommand(popup, 0); }, - onHidden: function() { + onHidden() { is(this.secondaryActionChecked, true, "secondaryAction callback is passed the correct checkbox value"); } }, // Test checkbox preserving its state through re-opening the doorhanger { id: "checkbox_reopen", - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", @@ -139,7 +139,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -148,7 +148,7 @@ var tests = [ EventUtils.synthesizeMouseAtCenter(checkbox, {}); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { let icon = document.getElementById("default-notification-icon"); EventUtils.synthesizeMouseAtCenter(icon, {}); let notification = popup.childNodes[0]; @@ -165,11 +165,11 @@ var tests = [ [true, false].forEach(function(checked) { tests.push( { id: `checkbox_disableMainAction_${state}_${checked ? 'checked' : 'unchecked'}`, - run: function() { + run() { this.notifyObj = new BasicNotification(this.id); this.notifyObj.options.checkbox = { label: "This is a checkbox", - checked: checked, + checked, [state]: { disableMainAction: true, warningLabel: "Testing disable", @@ -177,7 +177,7 @@ var tests = [ }; gNotification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { checkPopup(popup, this.notifyObj); let notification = popup.childNodes[0]; let checkbox = notification.checkbox; @@ -200,7 +200,7 @@ var tests = [ } triggerMainCommand(popup); }, - onHidden: function() { } + onHidden() { } } ); }); diff --git a/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js b/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js index 1065ac6aacef..30ce48bddead 100644 --- a/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_no_anchors.js @@ -15,7 +15,7 @@ var tests = [ // Test that popupnotifications are anchored to the identity icon on // about:blank, where anchor icons are hidden. { id: "Test#1", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"); @@ -23,7 +23,7 @@ var tests = [ this.notifyObj.anchorID = "geo-notification-icon"; this.notification = showNotification(this.notifyObj); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); is(document.getElementById("geo-notification-icon").boxObject.width, 0, "geo anchor shouldn't be visible"); @@ -31,7 +31,7 @@ var tests = [ "notification anchored to identity icon"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -40,7 +40,7 @@ var tests = [ // Test that popupnotifications are anchored to the identity icon after // navigation to about:blank. { id: "Test#2", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); @@ -51,7 +51,7 @@ var tests = [ }); this.notification = showNotification(this.notifyObj); }, - onShown: function* (popup) { + *onShown(popup) { yield promiseTabLoadEvent(gBrowser.selectedTab, "about:blank"); checkPopup(popup, this.notifyObj); @@ -61,7 +61,7 @@ var tests = [ "notification anchored to identity icon"); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -70,7 +70,7 @@ var tests = [ // Test that dismissed popupnotifications cannot be opened on about:blank, but // can be opened after navigation. { id: "Test#3", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"); @@ -92,11 +92,11 @@ var tests = [ EventUtils.synthesizeMouse(document.getElementById("geo-notification-icon"), 0, 0, {}); }, - onShown: function(popup) { + onShown(popup) { checkPopup(popup, this.notifyObj); dismissNotification(popup); }, - onHidden: function(popup) { + onHidden(popup) { this.notification.remove(); gBrowser.removeTab(gBrowser.selectedTab); gBrowser.selectedTab = this.oldSelectedTab; @@ -106,7 +106,7 @@ var tests = [ // editing the URL in the location bar, and restored to their anchors when the // URL is reverted. { id: "Test#4", - run: function* () { + *run() { this.oldSelectedTab = gBrowser.selectedTab; yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); diff --git a/browser/base/content/test/social/browser_aboutHome_activation.js b/browser/base/content/test/social/browser_aboutHome_activation.js index 9b3d599ba0eb..5d7dada0f9bc 100644 --- a/browser/base/content/test/social/browser_aboutHome_activation.js +++ b/browser/base/content/test/social/browser_aboutHome_activation.js @@ -57,7 +57,7 @@ var gTests = [ { desc: "Test activation with enable panel", - snippet: snippet, + snippet, panel: true }, diff --git a/browser/base/content/test/social/browser_addons.js b/browser/base/content/test/social/browser_addons.js index c57314282013..c5bf44dd6c1b 100644 --- a/browser/base/content/test/social/browser_addons.js +++ b/browser/base/content/test/social/browser_addons.js @@ -57,26 +57,26 @@ function installListener(next, aManifest) { }); return { - onInstalling: function(addon) { + onInstalling(addon) { is(expectEvent, "onInstalling", "install started"); is(addon.manifest.origin, aManifest.origin, "provider about to be installed"); ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs"); expectEvent = "onInstalled"; }, - onInstalled: function(addon) { + onInstalled(addon) { is(addon.manifest.origin, aManifest.origin, "provider installed"); ok(addon.installDate.getTime() > 0, "addon has installDate"); ok(addon.updateDate.getTime() > 0, "addon has updateDate"); ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs"); expectEvent = "onUninstalling"; }, - onUninstalling: function(addon) { + onUninstalling(addon) { is(expectEvent, "onUninstalling", "uninstall started"); is(addon.manifest.origin, aManifest.origin, "provider about to be uninstalled"); ok(Services.prefs.prefHasUserValue(prefname), "manifest is in user-prefs"); expectEvent = "onUninstalled"; }, - onUninstalled: function(addon) { + onUninstalled(addon) { is(expectEvent, "onUninstalled", "provider has been uninstalled"); is(addon.manifest.origin, aManifest.origin, "provider uninstalled"); ok(!Services.prefs.prefHasUserValue(prefname), "manifest is not in user-prefs"); @@ -86,25 +86,25 @@ function installListener(next, aManifest) { } var tests = { - testHTTPInstallFailure: function(next) { + testHTTPInstallFailure(next) { let installFrom = "http://example.com"; is(SocialService.getOriginActivationType(installFrom), "foreign", "testing foriegn install"); let data = { origin: installFrom, url: installFrom + "/activate", - manifest: manifest, - window: window + manifest, + window } Social.installProvider(data, function(addonManifest) { ok(!addonManifest, "unable to install provider over http"); next(); }); }, - testAddonEnableToggle: function(next) { + testAddonEnableToggle(next) { let expectEvent; let prefname = getManifestPrefname(manifest); let listener = { - onEnabled: function(addon) { + onEnabled(addon) { is(expectEvent, "onEnabled", "provider onEnabled"); ok(!addon.userDisabled, "provider enabled"); executeSoon(function() { @@ -112,11 +112,11 @@ var tests = { addon.userDisabled = true; }); }, - onEnabling: function(addon) { + onEnabling(addon) { is(expectEvent, "onEnabling", "provider onEnabling"); expectEvent = "onEnabled"; }, - onDisabled: function(addon) { + onDisabled(addon) { is(expectEvent, "onDisabled", "provider onDisabled"); ok(addon.userDisabled, "provider disabled"); AddonManager.removeAddonListener(listener); @@ -124,7 +124,7 @@ var tests = { Services.prefs.clearUserPref(prefname); executeSoon(next); }, - onDisabling: function(addon) { + onDisabling(addon) { is(expectEvent, "onDisabling", "provider onDisabling"); expectEvent = "onDisabled"; } @@ -148,7 +148,7 @@ var tests = { next(); }); }, - testProviderEnableToggle: function(next) { + testProviderEnableToggle(next) { // enable and disabel a provider from the SocialService interface, check // that the addon manager is updated @@ -156,22 +156,22 @@ var tests = { let prefname = getManifestPrefname(manifest); let listener = { - onEnabled: function(addon) { + onEnabled(addon) { is(expectEvent, "onEnabled", "provider onEnabled"); is(addon.manifest.origin, manifest.origin, "provider enabled"); ok(!addon.userDisabled, "provider !userDisabled"); }, - onEnabling: function(addon) { + onEnabling(addon) { is(expectEvent, "onEnabling", "provider onEnabling"); is(addon.manifest.origin, manifest.origin, "provider about to be enabled"); expectEvent = "onEnabled"; }, - onDisabled: function(addon) { + onDisabled(addon) { is(expectEvent, "onDisabled", "provider onDisabled"); is(addon.manifest.origin, manifest.origin, "provider disabled"); ok(addon.userDisabled, "provider userDisabled"); }, - onDisabling: function(addon) { + onDisabling(addon) { is(expectEvent, "onDisabling", "provider onDisabling"); is(addon.manifest.origin, manifest.origin, "provider about to be disabled"); expectEvent = "onDisabled"; @@ -190,7 +190,7 @@ var tests = { }); }); }, - testDirectoryInstall: function(next) { + testDirectoryInstall(next) { AddonManager.addAddonListener(installListener(next, manifest2)); BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown").then(() => { @@ -205,7 +205,7 @@ var tests = { origin: manifest2.origin, url: manifest2.origin + "/directory", manifest: manifest2, - window: window + window } Social.installProvider(data, function(addonManifest) { Services.prefs.clearUserPref("social.directories"); diff --git a/browser/base/content/test/social/browser_blocklist.js b/browser/base/content/test/social/browser_blocklist.js index 074583498fc6..9a340b633738 100644 --- a/browser/base/content/test/social/browser_blocklist.js +++ b/browser/base/content/test/social/browser_blocklist.js @@ -66,7 +66,7 @@ function test() { } var tests = { - testSimpleBlocklist: function(next) { + testSimpleBlocklist(next) { // this really just tests adding and clearing our blocklist for later tests setAndUpdateBlocklist(blocklistURL).then(() => { ok(Services.blocklist.isAddonBlocklisted(SocialService.createWrapper(manifest_bad)), "blocking 'blocked'"); @@ -77,7 +77,7 @@ var tests = { }); }); }, - testAddingNonBlockedProvider: function(next) { + testAddingNonBlockedProvider(next) { function finishTest(isgood) { ok(isgood, "adding non-blocked provider ok"); Services.prefs.clearUserPref("social.manifest.good"); @@ -103,7 +103,7 @@ var tests = { } }); }, - testAddingBlockedProvider: function(next) { + testAddingBlockedProvider(next) { function finishTest(good) { ok(good, "Unable to add blocklisted provider"); Services.prefs.clearUserPref("social.manifest.blocked"); @@ -124,7 +124,7 @@ var tests = { } }); }, - testInstallingBlockedProvider: function(next) { + testInstallingBlockedProvider(next) { function finishTest(good) { ok(good, "Unable to install blocklisted provider"); resetBlocklist().then(next); @@ -138,7 +138,7 @@ var tests = { origin: manifest_bad.origin, url: activationURL, manifest: manifest_bad, - window: window + window } Social.installProvider(data, function(addonManifest) { finishTest(false); @@ -148,10 +148,10 @@ var tests = { } }); }, - testBlockingExistingProvider: function(next) { + testBlockingExistingProvider(next) { let listener = { _window: null, - onOpenWindow: function(aXULWindow) { + onOpenWindow(aXULWindow) { Services.wm.removeListener(this); this._window = aXULWindow; let domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -177,8 +177,8 @@ var tests = { }); }, false); }, - onCloseWindow: function(aXULWindow) { }, - onWindowTitleChange: function(aXULWindow, aNewTitle) { } + onCloseWindow(aXULWindow) { }, + onWindowTitleChange(aXULWindow, aNewTitle) { } }; Services.wm.addListener(listener); diff --git a/browser/base/content/test/social/browser_share.js b/browser/base/content/test/social/browser_share.js index 91de49b16857..74414b7dd86e 100644 --- a/browser/base/content/test/social/browser_share.js +++ b/browser/base/content/test/social/browser_share.js @@ -135,7 +135,7 @@ function hasoptions(testOptions, options) { } var tests = { - testShareDisabledOnActivation: function(next) { + testShareDisabledOnActivation(next) { // starting on about:blank page, share should be visible but disabled when // adding provider is(gBrowser.currentURI.spec, "about:blank"); @@ -157,7 +157,7 @@ var tests = { SocialService.disableProvider(manifest.origin, next); }); }, - testShareEnabledOnActivation: function(next) { + testShareEnabledOnActivation(next) { // starting from *some* page, share should be visible and enabled when // activating provider // initialize the button into the navbar @@ -180,7 +180,7 @@ var tests = { }); }); }, - testSharePage: function(next) { + testSharePage(next) { let testTab; let testIndex = 0; let testData = corpus[testIndex++]; @@ -222,7 +222,7 @@ var tests = { } executeSoon(runOneTest); }, - testShareMicroformats: function(next) { + testShareMicroformats(next) { // initialize the button into the navbar CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR); // ensure correct state @@ -305,7 +305,7 @@ var tests = { }); }); }, - testSharePanelActivation: function(next) { + testSharePanelActivation(next) { let testTab; // cleared in the cleanup function Services.prefs.setCharPref("social.directories", "https://example.com"); @@ -352,7 +352,7 @@ var tests = { SocialShare.sharePage(); }); }, - testSharePanelDialog: function(next) { + testSharePanelDialog(next) { let testTab; // initialize the button into the navbar CustomizableUI.addWidgetToArea("social-share-button", CustomizableUI.AREA_NAVBAR); diff --git a/browser/base/content/test/social/browser_social_activation.js b/browser/base/content/test/social/browser_social_activation.js index 02c9b924f93f..63b8b938e996 100644 --- a/browser/base/content/test/social/browser_social_activation.js +++ b/browser/base/content/test/social/browser_social_activation.js @@ -186,7 +186,7 @@ function test() { } var tests = { - testActivationWrongOrigin: function(next) { + testActivationWrongOrigin(next) { // At this stage none of our providers exist, so we expect failure. Services.prefs.setBoolPref("social.remote-install.enabled", false); activateProvider(gTestDomains[0], function() { @@ -199,7 +199,7 @@ var tests = { }); }, - testIFrameActivation: function(next) { + testIFrameActivation(next) { activateIFrameProvider(gTestDomains[0], function() { is(SocialUI.enabled, false, "SocialUI is not enabled"); let panel = document.getElementById("servicesInstall-notification"); @@ -209,7 +209,7 @@ var tests = { }); }, - testActivationFirstProvider: function(next) { + testActivationFirstProvider(next) { // first up we add a manifest entry for a single provider. activateOneProvider(gProviders[0], false, function() { // we deactivated leaving no providers left, so Social is disabled. @@ -218,7 +218,7 @@ var tests = { }); }, - testActivationMultipleProvider: function(next) { + testActivationMultipleProvider(next) { // The trick with this test is to make sure that Social.providers[1] is // the current provider when doing the undo - this makes sure that the // Social code doesn't fallback to Social.providers[0], which it will @@ -237,7 +237,7 @@ var tests = { }); }, - testAddonManagerDoubleInstall: function(next) { + testAddonManagerDoubleInstall(next) { // Create a new tab and load about:addons let addonsTab = gBrowser.addTab(); gBrowser.selectedTab = addonsTab; diff --git a/browser/base/content/test/social/social_crash_content_helper.js b/browser/base/content/test/social/social_crash_content_helper.js index 4698b6957b4f..1a876c3d6a14 100644 --- a/browser/base/content/test/social/social_crash_content_helper.js +++ b/browser/base/content/test/social/social_crash_content_helper.js @@ -14,11 +14,11 @@ var crash = function() { // this will crash when called. var TestHelper = { - init: function() { + init() { addMessageListener("social-test:crash", this); }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "social-test:crash": privateNoteIntentionalCrash(); diff --git a/browser/base/content/test/urlbar/Panel.jsm b/browser/base/content/test/urlbar/Panel.jsm index ee1fd2ed93c9..2e5eccadf5cc 100644 --- a/browser/base/content/test/urlbar/Panel.jsm +++ b/browser/base/content/test/urlbar/Panel.jsm @@ -105,8 +105,8 @@ this.Panel.prototype = { let url = controller.getValueAt(idx); let action = this.urlbar._parseActionUrl(url); this._emit("result", { - url: url, - action: action, + url, + action, image: controller.getImageAt(idx), title: controller.getCommentAt(idx), type: controller.getStyleAt(idx), diff --git a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js b/browser/base/content/test/urlbar/browser_autocomplete_no_title.js index 8d608550b313..49e8f4609c9b 100644 --- a/browser/base/content/test/urlbar/browser_autocomplete_no_title.js +++ b/browser/base/content/test/urlbar/browser_autocomplete_no_title.js @@ -2,7 +2,7 @@ add_task(function*() { let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla"); let uri = NetUtil.newURI("http://bug1060642.example.com/beards/are/pretty/great"); - yield PlacesTestUtils.addVisits([{uri: uri, title: ""}]); + yield PlacesTestUtils.addVisits([{uri, title: ""}]); yield promiseAutocompleteResultPopup("bug1060642"); ok(gURLBar.popup.richlistbox.children.length > 1, "Should get at least 2 results"); diff --git a/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js b/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js index 8a69b4b44c54..b6440b327bc2 100644 --- a/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js +++ b/browser/base/content/test/urlbar/browser_autocomplete_tag_star_visibility.js @@ -10,7 +10,7 @@ add_task(function*() { PlacesUtils.bookmarks.DEFAULT_INDEX, `test ${tagName}`); PlacesUtils.tagging.tagURI(uri, [tagName]); - yield PlacesTestUtils.addVisits([{uri: uri, title: `Test page with tag ${tagName}`}]); + yield PlacesTestUtils.addVisits([{uri, title: `Test page with tag ${tagName}`}]); } // We use different tags for each part of the test, as otherwise the diff --git a/browser/base/content/test/urlbar/browser_bug556061.js b/browser/base/content/test/urlbar/browser_bug556061.js index 4c6ac5bf5230..d57e92c372d1 100644 --- a/browser/base/content/test/urlbar/browser_bug556061.js +++ b/browser/base/content/test/urlbar/browser_bug556061.js @@ -28,7 +28,7 @@ function cleanup() { var tests = [ { expected: testURL, - setup: function() { + setup() { gURLBar.value = testActionURL; gURLBar.valueIsTyped = true; is(gURLBar.value, testActionURL, "gURLBar starts with the correct real value"); @@ -39,37 +39,37 @@ var tests = [ gURLBar.select(); goDoCommand("cmd_copy"); }, - success: function() { + success() { is(gURLBar.value, testActionURL, "gURLBar.value didn't change when copying"); } }, { expected: testURL.substring(0, 10), - setup: function() { + setup() { // Set selectionStart/End manually and make sure it matches the substring gURLBar.selectionStart = 0; gURLBar.selectionEnd = 10; goDoCommand("cmd_copy"); }, - success: function() { + success() { is(gURLBar.value, testActionURL, "gURLBar.value didn't change when copying"); } }, { expected: testURL, - setup: function() { + setup() { // Setup for cut test... // Select all gURLBar.select(); goDoCommand("cmd_cut"); }, - success: function() { + success() { is(gURLBar.value, "", "gURLBar.value is now empty"); } }, { expected: testURL.substring(testURL.length - 10, testURL.length), - setup: function() { + setup() { // Reset urlbar value gURLBar.value = testActionURL; gURLBar.valueIsTyped = true; @@ -82,7 +82,7 @@ var tests = [ gURLBar.selectionEnd = testURL.length; goDoCommand("cmd_cut"); }, - success: function() { + success() { is(gURLBar.value, testURL.substring(0, testURL.length - 10), "gURLBar.value has the correct value"); } } diff --git a/browser/base/content/test/urlbar/browser_bug623155.js b/browser/base/content/test/urlbar/browser_bug623155.js index dd6ff8c85399..1d355395fcec 100644 --- a/browser/base/content/test/urlbar/browser_bug623155.js +++ b/browser/base/content/test/urlbar/browser_bug623155.js @@ -58,7 +58,7 @@ function test() { } var gWebProgressListener = { - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (aIID.equals(Components.interfaces.nsIWebProgressListener) || aIID.equals(Components.interfaces.nsISupportsWeakReference) || aIID.equals(Components.interfaces.nsISupports)) @@ -75,7 +75,7 @@ var gWebProgressListener = { // onSecurityChange: function() {}, // ---------------------------------------------------------------------------- - onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { if (!aRequest) { // This is bug 673752, or maybe initial "about:blank". return; diff --git a/browser/base/content/test/urlbar/browser_search_favicon.js b/browser/base/content/test/urlbar/browser_search_favicon.js index a8e6dbbcd957..4ab7bfd6ec73 100644 --- a/browser/base/content/test/urlbar/browser_search_favicon.js +++ b/browser/base/content/test/urlbar/browser_search_favicon.js @@ -23,7 +23,7 @@ add_task(function*() { Services.search.currentEngine = gEngine; let uri = NetUtil.newURI("http://s.example.com/search?q=foo&client=1"); - yield PlacesTestUtils.addVisits({ uri: uri, title: "Foo - SearchEngine Search" }); + yield PlacesTestUtils.addVisits({ uri, title: "Foo - SearchEngine Search" }); yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla"); diff --git a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js b/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js index 6fde02895311..5b5fd3e6d1e9 100644 --- a/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js +++ b/browser/base/content/test/urlbar/browser_tabMatchesInAwesomebar.js @@ -171,12 +171,12 @@ function checkAutocompleteResults(aExpected, aCallback) searchParam: "enable-actions", popupOpen: false, minResultsForPopup: 0, - invalidate: function() {}, + invalidate() {}, disableAutoComplete: false, completeDefaultIndex: false, get popup() { return this; }, - onSearchBegin: function() {}, - onSearchComplete: function() + onSearchBegin() {}, + onSearchComplete() { info("Found " + gController.matchCount + " matches."); // Check to see the expected uris and titles match up (in any order) @@ -202,9 +202,9 @@ function checkAutocompleteResults(aExpected, aCallback) executeSoon(aCallback); }, - setSelectedIndex: function() {}, + setSelectedIndex() {}, get searchCount() { return this.searches.length; }, - getSearchAt: function(aIndex) { return this.searches[aIndex]; }, + getSearchAt(aIndex) { return this.searches[aIndex]; }, QueryInterface: XPCOMUtils.generateQI([ Ci.nsIAutoCompleteInput, Ci.nsIAutoCompletePopup, diff --git a/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js b/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js index 05c54ba251f3..102c65efd948 100644 --- a/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js +++ b/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js @@ -184,18 +184,18 @@ function promiseMessage(type, data, numExpectedAcks = 1) { let ackMsgName = "TestMessageAck"; let msgID = gNextMessageID++; gMsgMan.sendAsyncMessage(testMsgName, { - type: type, + type, messageID: msgID, - data: data, + data, }); let ackPromises = []; for (let i = 0; i < numExpectedAcks; i++) { let ackIndex = i; ackPromises.push(new Promise(resolve => { info("Waiting for message ack: " + JSON.stringify({ - type: type, - msgID: msgID, - ackIndex: ackIndex, + type, + msgID, + ackIndex, })); gMsgMan.addMessageListener(ackMsgName, function onMsg(msg) { // Messages have IDs so that an ack can be correctly paired with the @@ -207,9 +207,9 @@ function promiseMessage(type, data, numExpectedAcks = 1) { return; } info("Received message ack: " + JSON.stringify({ - type: type, + type, msgID: msg.data.messageID, - ackIndex: ackIndex, + ackIndex, })); gMsgMan.removeMessageListener(ackMsgName, onMsg); resolve(msg.data.data); diff --git a/browser/base/content/test/urlbar/browser_urlbarCopying.js b/browser/base/content/test/urlbar/browser_urlbarCopying.js index 8c1d262d6d3b..aa7289f4c0c5 100644 --- a/browser/base/content/test/urlbar/browser_urlbarCopying.js +++ b/browser/base/content/test/urlbar/browser_urlbarCopying.js @@ -153,7 +153,7 @@ var tests = [ copyExpected: "data:text/html,(%C3%A9 %25P", }, { - setup: function() { Services.prefs.setBoolPref(decodeURLpref, true); }, + setup() { Services.prefs.setBoolPref(decodeURLpref, true); }, loadURL: "http://example.com/%D0%B1%D0%B8%D0%BE%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D1%8F", expectedURL: toUnicode("example.com/биография"), copyExpected: toUnicode("http://example.com/биография") diff --git a/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js b/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js index 8c28401eae0e..485c9ec0db05 100644 --- a/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js +++ b/browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js @@ -188,7 +188,7 @@ function getActionAtIndex(index) { } let [, type, paramStr] = mozActionMatch; return { - type: type, + type, params: JSON.parse(paramStr), }; } diff --git a/browser/base/content/test/urlbar/head.js b/browser/base/content/test/urlbar/head.js index d1288a8db751..cb39ce9262c6 100644 --- a/browser/base/content/test/urlbar/head.js +++ b/browser/base/content/test/urlbar/head.js @@ -46,7 +46,7 @@ function waitForDocLoadAndStopIt(aExpectedURL, aBrowser = gBrowser.selectedBrows } let progressListener = { - onStateChange: function(webProgress, req, flags, status) { + onStateChange(webProgress, req, flags, status) { dump("waitForDocLoadAndStopIt: onStateChange " + flags.toString(16) + ": " + req.name + "\n"); if (webProgress.isTopLevel && @@ -190,12 +190,12 @@ function promiseNewSearchEngine(basename) { info("Waiting for engine to be added: " + basename); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); registerCleanupFunction(() => Services.search.removeEngine(engine)); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { Assert.ok(false, "addEngine failed with error code " + errCode); reject(); }, diff --git a/browser/base/content/test/urlbar/urlbarAddonIframe.js b/browser/base/content/test/urlbar/urlbarAddonIframe.js index d25ab0bc95c4..3f8f9a83aa78 100644 --- a/browser/base/content/test/urlbar/urlbarAddonIframe.js +++ b/browser/base/content/test/urlbar/urlbarAddonIframe.js @@ -45,7 +45,7 @@ function ack(originalEventDetail, ackData = null, ackIndex = 0) { dispatchEvent(new CustomEvent("TestEventAck", { detail: { messageID: originalEventDetail.messageID, - ackIndex: ackIndex, + ackIndex, data: ackData, }, })); diff --git a/browser/base/content/utilityOverlay.js b/browser/base/content/utilityOverlay.js index a8f5e747b2c8..ab7849e6db5c 100644 --- a/browser/base/content/utilityOverlay.js +++ b/browser/base/content/utilityOverlay.js @@ -383,7 +383,7 @@ function openLinkIn(url, where, params) { } targetBrowser.loadURIWithFlags(url, { - flags: flags, + flags, referrerURI: aNoReferrer ? null : aReferrerURI, referrerPolicy: aReferrerPolicy, postData: aPostData, diff --git a/browser/base/content/web-panels.js b/browser/base/content/web-panels.js index ceb0016fdff6..3bf8c726e6fc 100644 --- a/browser/base/content/web-panels.js +++ b/browser/base/content/web-panels.js @@ -13,12 +13,12 @@ function getPanelBrowser() } var panelProgressListener = { - onProgressChange : function(aWebProgress, aRequest, + onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { }, - onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus) + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { if (!aRequest) return; @@ -38,17 +38,17 @@ var panelProgressListener = { } , - onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { UpdateBackForwardCommands(getPanelBrowser().webNavigation); }, - onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) { + onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { }, - onSecurityChange : function(aWebProgress, aRequest, aState) { + onSecurityChange(aWebProgress, aRequest, aState) { }, - QueryInterface : function(aIID) + QueryInterface(aIID) { if (aIID.equals(Ci.nsIWebProgressListener) || aIID.equals(Ci.nsISupportsWeakReference) || diff --git a/browser/base/content/webrtcIndicator.js b/browser/base/content/webrtcIndicator.js index a8bb64367c48..9b4d78066a44 100644 --- a/browser/base/content/webrtcIndicator.js +++ b/browser/base/content/webrtcIndicator.js @@ -129,7 +129,7 @@ function onFirefoxButtonClick(event) { var PositionHandler = { positionCustomized: false, threshold: 10, - adjustPosition: function() { + adjustPosition() { if (!this.positionCustomized) { // Center the window horizontally on the screen (not the available area). // Until we have moved the window to y=0, 'screen.width' may give a value @@ -150,14 +150,14 @@ var PositionHandler = { this.setXPosition(window.screenX); } }, - setXPosition: function(desiredX) { + setXPosition(desiredX) { // Ensure the indicator isn't moved outside the available area of the screen. desiredX = Math.max(desiredX, screen.availLeft); let maxX = screen.availLeft + screen.availWidth - document.documentElement.clientWidth; window.moveTo(Math.min(desiredX, maxX), screen.availTop); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "mousedown": if (aEvent.button != 0 || aEvent.defaultPrevented) diff --git a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js index 310a94166610..580d29843dc3 100644 --- a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js +++ b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js @@ -98,22 +98,22 @@ function OpenCacheEntry(key, where, flags, lci) CacheListener.prototype = { _appCache: null, - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Components.interfaces.nsICacheEntryOpenCallback) || iid.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_ERROR_NO_INTERFACE; }, - onCacheEntryCheck: function(entry, appCache) { + onCacheEntryCheck(entry, appCache) { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable: function(entry, isnew, appCache, status) { + onCacheEntryAvailable(entry, isnew, appCache, status) { resolve(); }, - run: function() { + run() { let storage = getCacheStorage(where, lci, this._appCache); storage.asyncOpenURI(key, "", flags, this); } diff --git a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js index 9875c8aa1b73..e874494ec462 100644 --- a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js +++ b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js @@ -78,7 +78,7 @@ function allRegistered() { function promiseAllRegistered() { return new Promise(function(resolve) { let listener = { - onRegister: function() { + onRegister() { if (allRegistered()) { swm.removeListener(listener); resolve(); @@ -92,11 +92,11 @@ function promiseAllRegistered() { function promiseUnregister(info) { return new Promise(function(resolve) { swm.unregister(info.principal, { - unregisterSucceeded: function(aState) { + unregisterSucceeded(aState) { ok(aState, "ServiceWorkerRegistration exists"); resolve(); }, - unregisterFailed: function(aState) { + unregisterFailed(aState) { ok(false, "unregister should succeed"); } }, info.scope); diff --git a/browser/components/customizableui/CustomizableUI.jsm b/browser/components/customizableui/CustomizableUI.jsm index a9cef9dd1a34..81f4da46b2da 100644 --- a/browser/components/customizableui/CustomizableUI.jsm +++ b/browser/components/customizableui/CustomizableUI.jsm @@ -170,7 +170,7 @@ XPCOMUtils.defineLazyGetter(this, "log", () => { }); var CustomizableUIInternal = { - initialize: function() { + initialize() { log.debug("Initializing"); this.addListener(this); @@ -323,13 +323,13 @@ var CustomizableUIInternal = { return toolbars; }, - _defineBuiltInWidgets: function() { + _defineBuiltInWidgets() { for (let widgetDefinition of CustomizableWidgets) { this.createBuiltinWidget(widgetDefinition); } }, - _introduceNewBuiltinWidgets: function() { + _introduceNewBuiltinWidgets() { // We should still enter even if gSavedState.currentVersion >= kVersion // because the per-widget pref facility is independent of versioning. if (!gSavedState) { @@ -389,7 +389,7 @@ var CustomizableUIInternal = { * _markObsoleteBuiltinButtonsSeen * when upgrading, ensure obsoleted buttons are in seen state. */ - _markObsoleteBuiltinButtonsSeen: function() { + _markObsoleteBuiltinButtonsSeen() { if (!gSavedState) return; let currentVersion = gSavedState.currentVersion; @@ -405,7 +405,7 @@ var CustomizableUIInternal = { } }, - _placeNewDefaultWidgetsInArea: function(aArea) { + _placeNewDefaultWidgetsInArea(aArea) { let futurePlacedWidgets = gFuturePlacements.get(aArea); let savedPlacements = gSavedState && gSavedState.placements && gSavedState.placements[aArea]; let defaultPlacements = gAreas.get(aArea).get("defaultPlacements"); @@ -459,7 +459,7 @@ var CustomizableUIInternal = { this.saveState(); }, - wrapWidget: function(aWidgetId) { + wrapWidget(aWidgetId) { if (gGroupWrapperCache.has(aWidgetId)) { return gGroupWrapperCache.get(aWidgetId); } @@ -484,7 +484,7 @@ var CustomizableUIInternal = { return wrapper; }, - registerArea: function(aName, aProperties, aInternalCaller) { + registerArea(aName, aProperties, aInternalCaller) { if (typeof aName != "string" || !/^[a-z0-9-_]{1,}$/i.test(aName)) { throw new Error("Invalid area name"); } @@ -563,7 +563,7 @@ var CustomizableUIInternal = { } }, - unregisterArea: function(aName, aDestroyPlacements) { + unregisterArea(aName, aDestroyPlacements) { if (typeof aName != "string" || !/^[a-z0-9-_]{1,}$/i.test(aName)) { throw new Error("Invalid area name"); } @@ -605,7 +605,7 @@ var CustomizableUIInternal = { } }, - registerToolbarNode: function(aToolbar, aExistingChildren) { + registerToolbarNode(aToolbar, aExistingChildren) { let area = aToolbar.id; if (gBuildAreas.has(area) && gBuildAreas.get(area).has(aToolbar)) { return; @@ -677,7 +677,7 @@ var CustomizableUIInternal = { } }, - buildArea: function(aArea, aPlacements, aAreaNode) { + buildArea(aArea, aPlacements, aAreaNode) { let document = aAreaNode.ownerDocument; let window = document.defaultView; let inPrivateWindow = PrivateBrowsingUtils.isWindowPrivate(window); @@ -813,7 +813,7 @@ var CustomizableUIInternal = { } }, - addPanelCloseListeners: function(aPanel) { + addPanelCloseListeners(aPanel) { gELS.addSystemEventListener(aPanel, "click", this, false); gELS.addSystemEventListener(aPanel, "keypress", this, false); let win = aPanel.ownerGlobal; @@ -823,7 +823,7 @@ var CustomizableUIInternal = { gPanelsForWindow.get(win).add(this._getPanelForNode(aPanel)); }, - removePanelCloseListeners: function(aPanel) { + removePanelCloseListeners(aPanel) { gELS.removeSystemEventListener(aPanel, "click", this, false); gELS.removeSystemEventListener(aPanel, "keypress", this, false); let win = aPanel.ownerGlobal; @@ -833,7 +833,7 @@ var CustomizableUIInternal = { } }, - ensureButtonContextMenu: function(aNode, aAreaNode) { + ensureButtonContextMenu(aNode, aAreaNode) { const kPanelItemContextMenu = "customizationPanelItemContextMenu"; let currentContextMenu = aNode.getAttribute("context") || @@ -851,7 +851,7 @@ var CustomizableUIInternal = { } }, - getWidgetProvider: function(aWidgetId) { + getWidgetProvider(aWidgetId) { if (this.isSpecialWidget(aWidgetId)) { return CustomizableUI.PROVIDER_SPECIAL; } @@ -871,7 +871,7 @@ var CustomizableUIInternal = { return CustomizableUI.PROVIDER_XUL; }, - getWidgetNode: function(aWidgetId, aWindow) { + getWidgetNode(aWidgetId, aWindow) { let document = aWindow.document; if (this.isSpecialWidget(aWidgetId)) { @@ -904,7 +904,7 @@ var CustomizableUIInternal = { return [null, null]; }, - registerMenuPanel: function(aPanelContents) { + registerMenuPanel(aPanelContents) { if (gBuildAreas.has(CustomizableUI.AREA_PANEL) && gBuildAreas.get(CustomizableUI.AREA_PANEL).has(aPanelContents)) { return; @@ -935,7 +935,7 @@ var CustomizableUIInternal = { this.registerBuildArea(CustomizableUI.AREA_PANEL, aPanelContents); }, - onWidgetAdded: function(aWidgetId, aArea, aPosition) { + onWidgetAdded(aWidgetId, aArea, aPosition) { this.insertNode(aWidgetId, aArea, aPosition, true); if (!gResetting) { @@ -943,7 +943,7 @@ var CustomizableUIInternal = { } }, - onWidgetRemoved: function(aWidgetId, aArea) { + onWidgetRemoved(aWidgetId, aArea) { let areaNodes = gBuildAreas.get(aArea); if (!areaNodes) { return; @@ -1003,18 +1003,18 @@ var CustomizableUIInternal = { } }, - onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { this.insertNode(aWidgetId, aArea, aNewPosition); if (!gResetting) { this._clearPreviousUIState(); } }, - onCustomizeEnd: function(aWindow) { + onCustomizeEnd(aWindow) { this._clearPreviousUIState(); }, - registerBuildArea: function(aArea, aNode) { + registerBuildArea(aArea, aNode) { // We ensure that the window is registered to have its customization data // cleaned up when unloading. let window = aNode.ownerGlobal; @@ -1039,7 +1039,7 @@ var CustomizableUIInternal = { customizableNode.classList.add("customization-target"); }, - registerBuildWindow: function(aWindow) { + registerBuildWindow(aWindow) { if (!gBuildWindows.has(aWindow)) { gBuildWindows.set(aWindow, new Set()); @@ -1050,7 +1050,7 @@ var CustomizableUIInternal = { } }, - unregisterBuildWindow: function(aWindow) { + unregisterBuildWindow(aWindow) { aWindow.removeEventListener("unload", this); aWindow.removeEventListener("command", this, true); gPanelsForWindow.delete(aWindow); @@ -1093,7 +1093,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWindowClosed", aWindow); }, - setLocationAttributes: function(aNode, aArea) { + setLocationAttributes(aNode, aArea) { let props = gAreas.get(aArea); if (!props) { throw new Error("Expected area " + aArea + " to have a properties Map " + @@ -1109,12 +1109,12 @@ var CustomizableUIInternal = { } }, - removeLocationAttributes: function(aNode) { + removeLocationAttributes(aNode) { aNode.removeAttribute("cui-areatype"); aNode.removeAttribute("cui-anchorid"); }, - insertNode: function(aWidgetId, aArea, aPosition, isNew) { + insertNode(aWidgetId, aArea, aPosition, isNew) { let areaNodes = gBuildAreas.get(aArea); if (!areaNodes) { return; @@ -1134,7 +1134,7 @@ var CustomizableUIInternal = { } }, - insertNodeInWindow: function(aWidgetId, aAreaNode, isNew) { + insertNodeInWindow(aWidgetId, aAreaNode, isNew) { let window = aAreaNode.ownerGlobal; let showInPrivateBrowsing = gPalette.has(aWidgetId) ? gPalette.get(aWidgetId).showInPrivateBrowsing @@ -1166,7 +1166,7 @@ var CustomizableUIInternal = { } }, - findInsertionPoints: function(aNode, aAreaNode) { + findInsertionPoints(aNode, aAreaNode) { let areaId = aAreaNode.id; let props = gAreas.get(areaId); @@ -1191,14 +1191,14 @@ var CustomizableUIInternal = { return [container, null]; }, - insertWidgetBefore: function(aNode, aNextNode, aContainer, aArea) { + insertWidgetBefore(aNode, aNextNode, aContainer, aArea) { this.notifyListeners("onWidgetBeforeDOMChange", aNode, aNextNode, aContainer); this.setLocationAttributes(aNode, aArea); aContainer.insertBefore(aNode, aNextNode); this.notifyListeners("onWidgetAfterDOMChange", aNode, aNextNode, aContainer); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "command": if (!this._originalEventInPanel(aEvent)) { @@ -1216,7 +1216,7 @@ var CustomizableUIInternal = { } }, - _originalEventInPanel: function(aEvent) { + _originalEventInPanel(aEvent) { let e = aEvent.sourceEvent; if (!e) { return false; @@ -1230,14 +1230,14 @@ var CustomizableUIInternal = { return !!panels && panels.has(node); }, - isSpecialWidget: function(aId) { + isSpecialWidget(aId) { return (aId.startsWith(kSpecialWidgetPfx) || aId.startsWith("separator") || aId.startsWith("spring") || aId.startsWith("spacer")); }, - ensureSpecialWidgetId: function(aId) { + ensureSpecialWidgetId(aId) { let nodeType = aId.match(/spring|spacer|separator/)[0]; // If the ID we were passed isn't a generated one, generate one now: if (nodeType == aId) { @@ -1247,7 +1247,7 @@ var CustomizableUIInternal = { return aId; }, - createSpecialWidget: function(aId, aDocument) { + createSpecialWidget(aId, aDocument) { let nodeName = "toolbar" + aId.match(/spring|spacer|separator/)[0]; let node = aDocument.createElementNS(kNSXUL, nodeName); node.id = this.ensureSpecialWidgetId(aId); @@ -1260,7 +1260,7 @@ var CustomizableUIInternal = { /* Find a XUL-provided widget in a window. Don't try to use this * for an API-provided widget or a special widget. */ - findWidgetInWindow: function(aId, aWindow) { + findWidgetInWindow(aId, aWindow) { if (!gBuildWindows.has(aWindow)) { throw new Error("Build window not registered"); } @@ -1322,7 +1322,7 @@ var CustomizableUIInternal = { return null; }, - buildWidget: function(aDocument, aWidget) { + buildWidget(aDocument, aWidget) { if (aDocument.documentURI != kExpectedWindowURL) { throw new Error("buildWidget was called for a non-browser window!"); } @@ -1417,7 +1417,7 @@ var CustomizableUIInternal = { return node; }, - getLocalizedProperty: function(aWidget, aProp, aFormatArgs, aDef) { + getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef) { const kReqStringProps = ["label"]; if (typeof aWidget == "string") { @@ -1456,7 +1456,7 @@ var CustomizableUIInternal = { return def; }, - addShortcut: function(aShortcutNode, aTargetNode = aShortcutNode) { + addShortcut(aShortcutNode, aTargetNode = aShortcutNode) { // Detect if we've already been here before. if (aTargetNode.hasAttribute("shortcut")) return; @@ -1478,7 +1478,7 @@ var CustomizableUIInternal = { aTargetNode.setAttribute("shortcut", ShortcutUtils.prettifyShortcut(shortcut)); }, - handleWidgetCommand: function(aWidget, aNode, aEvent) { + handleWidgetCommand(aWidget, aNode, aEvent) { log.debug("handleWidgetCommand"); if (aWidget.type == "button") { @@ -1509,7 +1509,7 @@ var CustomizableUIInternal = { } }, - handleWidgetClick: function(aWidget, aNode, aEvent) { + handleWidgetClick(aWidget, aNode, aEvent) { log.debug("handleWidgetClick"); if (aWidget.onClick) { try { @@ -1523,7 +1523,7 @@ var CustomizableUIInternal = { } }, - _getPanelForNode: function(aNode) { + _getPanelForNode(aNode) { let panel = aNode; while (panel && panel.localName != "panel") panel = panel.parentNode; @@ -1536,7 +1536,7 @@ var CustomizableUIInternal = { * We also check for being outside of any toolbaritem/toolbarbutton, ie on a blank * part of the menu. */ - _isOnInteractiveElement: function(aEvent) { + _isOnInteractiveElement(aEvent) { function getMenuPopupForDescendant(aNode) { let lastPopup = null; while (aNode && aNode.parentNode && @@ -1652,14 +1652,14 @@ var CustomizableUIInternal = { return inInput || !inItem; }, - hidePanelForNode: function(aNode) { + hidePanelForNode(aNode) { let panel = this._getPanelForNode(aNode); if (panel) { panel.hidePopup(); } }, - maybeAutoHidePanel: function(aEvent) { + maybeAutoHidePanel(aEvent) { if (aEvent.type == "keypress") { if (aEvent.keyCode != aEvent.DOM_VK_RETURN) { return; @@ -1714,7 +1714,7 @@ var CustomizableUIInternal = { this.hidePanelForNode(aEvent.target); }, - getUnusedWidgets: function(aWindowPalette) { + getUnusedWidgets(aWindowPalette) { let window = aWindowPalette.ownerGlobal; let isWindowPrivate = PrivateBrowsingUtils.isWindowPrivate(window); // We use a Set because there can be overlap between the widgets in @@ -1745,7 +1745,7 @@ var CustomizableUIInternal = { return [...widgets]; }, - getPlacementOfWidget: function(aWidgetId, aOnlyRegistered, aDeadAreas) { + getPlacementOfWidget(aWidgetId, aOnlyRegistered, aDeadAreas) { if (aOnlyRegistered && !this.widgetExists(aWidgetId)) { return null; } @@ -1756,14 +1756,14 @@ var CustomizableUIInternal = { } let index = placements.indexOf(aWidgetId); if (index != -1) { - return { area: area, position: index }; + return { area, position: index }; } } return null; }, - widgetExists: function(aWidgetId) { + widgetExists(aWidgetId) { if (gPalette.has(aWidgetId) || this.isSpecialWidget(aWidgetId)) { return true; } @@ -1778,7 +1778,7 @@ var CustomizableUIInternal = { return true; }, - addWidgetToArea: function(aWidgetId, aArea, aPosition, aInitialAdd) { + addWidgetToArea(aWidgetId, aArea, aPosition, aInitialAdd) { if (!gAreas.has(aArea)) { throw new Error("Unknown customization area: " + aArea); } @@ -1852,7 +1852,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetAdded", aWidgetId, aArea, aPosition); }, - removeWidgetFromArea: function(aWidgetId) { + removeWidgetFromArea(aWidgetId) { let oldPlacement = this.getPlacementOfWidget(aWidgetId, false, true); if (!oldPlacement) { return; @@ -1881,7 +1881,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetRemoved", aWidgetId, oldPlacement.area); }, - moveWidgetWithinArea: function(aWidgetId, aPosition) { + moveWidgetWithinArea(aWidgetId, aPosition) { let oldPlacement = this.getPlacementOfWidget(aWidgetId); if (!oldPlacement) { return; @@ -1930,7 +1930,7 @@ var CustomizableUIInternal = { // built lazily - and therefore wouldn't otherwise result in restoring its // state immediately when a browser window opens, which is important for // other consumers of this API. - loadSavedState: function() { + loadSavedState() { let state = null; try { state = Services.prefs.getCharPref(kPrefCustomizationState); @@ -1967,7 +1967,7 @@ var CustomizableUIInternal = { gNewElementCount = gSavedState.newElementCount || 0; }, - restoreStateForArea: function(aArea, aLegacyState) { + restoreStateForArea(aArea, aLegacyState) { let placementsPreexisted = gPlacements.has(aArea); this.beginBatchUpdate(); @@ -2031,7 +2031,7 @@ var CustomizableUIInternal = { } }, - saveState: function() { + saveState() { if (gInBatchStack || !gDirty) { return; } @@ -2061,7 +2061,7 @@ var CustomizableUIInternal = { gDirty = false; }, - serializerHelper: function(aKey, aValue) { + serializerHelper(aKey, aValue) { if (typeof aValue == "object" && aValue.constructor.name == "Map") { let result = {}; for (let [mapKey, mapValue] of aValue) @@ -2076,11 +2076,11 @@ var CustomizableUIInternal = { return aValue; }, - beginBatchUpdate: function() { + beginBatchUpdate() { gInBatchStack++; }, - endBatchUpdate: function(aForceDirty) { + endBatchUpdate(aForceDirty) { gInBatchStack--; if (aForceDirty === true) { gDirty = true; @@ -2092,11 +2092,11 @@ var CustomizableUIInternal = { } }, - addListener: function(aListener) { + addListener(aListener) { gListeners.add(aListener); }, - removeListener: function(aListener) { + removeListener(aListener) { if (aListener == this) { return; } @@ -2104,7 +2104,7 @@ var CustomizableUIInternal = { gListeners.delete(aListener); }, - notifyListeners: function(aEvent, ...aArgs) { + notifyListeners(aEvent, ...aArgs) { if (gRestoring) { return; } @@ -2120,7 +2120,7 @@ var CustomizableUIInternal = { } }, - _dispatchToolboxEventToWindow: function(aEventType, aDetails, aWindow) { + _dispatchToolboxEventToWindow(aEventType, aDetails, aWindow) { let evt = new aWindow.CustomEvent(aEventType, { bubbles: true, cancelable: true, @@ -2129,7 +2129,7 @@ var CustomizableUIInternal = { aWindow.gNavToolbox.dispatchEvent(evt); }, - dispatchToolboxEvent: function(aEventType, aDetails = {}, aWindow = null) { + dispatchToolboxEvent(aEventType, aDetails = {}, aWindow = null) { if (aWindow) { this._dispatchToolboxEventToWindow(aEventType, aDetails, aWindow); return; @@ -2139,7 +2139,7 @@ var CustomizableUIInternal = { } }, - createWidget: function(aProperties) { + createWidget(aProperties) { let widget = this.normalizeWidget(aProperties, CustomizableUI.SOURCE_EXTERNAL); // XXXunf This should probably throw. if (!widget) { @@ -2256,7 +2256,7 @@ var CustomizableUIInternal = { return widget.id; }, - createBuiltinWidget: function(aData) { + createBuiltinWidget(aData) { // This should only ever be called on startup, before any windows are // opened - so we know there's no build areas to handle. Also, builtin // widgets are expected to be (mostly) static, so shouldn't affect the @@ -2291,7 +2291,7 @@ var CustomizableUIInternal = { }, // Returns true if the area will eventually lazily restore (but hasn't yet). - isAreaLazy: function(aArea) { + isAreaLazy(aArea) { if (gPlacements.has(aArea)) { return false; } @@ -2299,7 +2299,7 @@ var CustomizableUIInternal = { }, // XXXunf Log some warnings here, when the data provided isn't up to scratch. - normalizeWidget: function(aData, aSource) { + normalizeWidget(aData, aSource) { let widget = { implementation: aData, source: aSource || CustomizableUI.SOURCE_EXTERNAL, @@ -2400,7 +2400,7 @@ var CustomizableUIInternal = { return widget; }, - wrapWidgetEventHandler: function(aEventName, aWidget) { + wrapWidgetEventHandler(aEventName, aWidget) { if (typeof aWidget.implementation[aEventName] != "function") { aWidget[aEventName] = null; return; @@ -2422,7 +2422,7 @@ var CustomizableUIInternal = { }; }, - destroyWidget: function(aWidgetId) { + destroyWidget(aWidgetId) { let widget = gPalette.get(aWidgetId); if (!widget) { gGroupWrapperCache.delete(aWidgetId); @@ -2489,7 +2489,7 @@ var CustomizableUIInternal = { this.notifyListeners("onWidgetDestroyed", aWidgetId); }, - getCustomizeTargetForArea: function(aArea, aWindow) { + getCustomizeTargetForArea(aArea, aWindow) { let buildAreaNodes = gBuildAreas.get(aArea); if (!buildAreaNodes) { return null; @@ -2504,7 +2504,7 @@ var CustomizableUIInternal = { return null; }, - reset: function() { + reset() { gResetting = true; this._resetUIState(); @@ -2524,7 +2524,7 @@ var CustomizableUIInternal = { gResetting = false; }, - _resetUIState: function() { + _resetUIState() { try { gUIStateBeforeReset.drawInTitlebar = Services.prefs.getBoolPref(kPrefDrawInTitlebar); gUIStateBeforeReset.uiCustomizationState = Services.prefs.getCharPref(kPrefCustomizationState); @@ -2550,7 +2550,7 @@ var CustomizableUIInternal = { } }, - _resetExtraToolbars: function(aFilter = null) { + _resetExtraToolbars(aFilter = null) { let firstWindow = true; // Only need to unregister and persist once for (let [win, ] of gBuildWindows) { let toolbox = win.gNavToolbox; @@ -2572,7 +2572,7 @@ var CustomizableUIInternal = { } }, - _rebuildRegisteredAreas: function() { + _rebuildRegisteredAreas() { for (let [areaId, areaNodes] of gBuildAreas) { let placements = gPlacements.get(areaId); let isFirstChangedToolbar = true; @@ -2595,7 +2595,7 @@ var CustomizableUIInternal = { /** * Undoes a previous reset, restoring the state of the UI to the state prior to the reset. */ - undoReset: function() { + undoReset() { if (gUIStateBeforeReset.uiCustomizationState == null || gUIStateBeforeReset.drawInTitlebar == null) { return; @@ -2627,13 +2627,13 @@ var CustomizableUIInternal = { gUndoResetting = false; }, - _clearPreviousUIState: function() { + _clearPreviousUIState() { Object.getOwnPropertyNames(gUIStateBeforeReset).forEach((prop) => { gUIStateBeforeReset[prop] = null; }); }, - removeExtraToolbar: function(aToolbarId) { + removeExtraToolbar(aToolbarId) { this._resetExtraToolbars(aToolbarId); }, @@ -2641,7 +2641,7 @@ var CustomizableUIInternal = { * @param {String|Node} aWidget - widget ID or a widget node (preferred for performance). * @return {Boolean} whether the widget is removable */ - isWidgetRemovable: function(aWidget) { + isWidgetRemovable(aWidget) { let widgetId; let widgetNode; if (typeof aWidget == "string") { @@ -2684,7 +2684,7 @@ var CustomizableUIInternal = { return true; }, - canWidgetMoveToArea: function(aWidgetId, aArea) { + canWidgetMoveToArea(aWidgetId, aArea) { let placement = this.getPlacementOfWidget(aWidgetId); if (placement && placement.area != aArea) { // Special widgets can't move to the menu panel. @@ -2699,7 +2699,7 @@ var CustomizableUIInternal = { return true; }, - ensureWidgetPlacedInWindow: function(aWidgetId, aWindow) { + ensureWidgetPlacedInWindow(aWidgetId, aWindow) { let placement = this.getPlacementOfWidget(aWidgetId); if (!placement) { return false; @@ -2799,7 +2799,7 @@ var CustomizableUIInternal = { return true; }, - setToolbarVisibility: function(aToolbarId, aIsVisible) { + setToolbarVisibility(aToolbarId, aIsVisible) { // We only persist the attribute the first time. let isFirstChangedToolbar = true; for (let window of CustomizableUI.windows) { @@ -3003,14 +3003,14 @@ this.CustomizableUI = { * or by a window closing. The aReason parameter indicates which of * these is the case. */ - addListener: function(aListener) { + addListener(aListener) { CustomizableUIInternal.addListener(aListener); }, /** * Remove a listener added with addListener * @param aListener the listener object to remove */ - removeListener: function(aListener) { + removeListener(aListener) { CustomizableUIInternal.removeListener(aListener); }, @@ -3036,7 +3036,7 @@ this.CustomizableUI = { * Specify null to ensure that reset/inDefaultArea don't care * about a toolbar's collapsed state */ - registerArea: function(aName, aProperties) { + registerArea(aName, aProperties) { CustomizableUIInternal.registerArea(aName, aProperties); }, /** @@ -3055,7 +3055,7 @@ this.CustomizableUI = { * allow the user to customize it in customize mode, or otherwise deal * with it, until the area has been registered. */ - registerToolbarNode: function(aToolbar, aExistingChildren) { + registerToolbarNode(aToolbar, aExistingChildren) { CustomizableUIInternal.registerToolbarNode(aToolbar, aExistingChildren); }, /** @@ -3063,7 +3063,7 @@ this.CustomizableUI = { * apart from the built-in PanelUI. * @param aPanel the panel DOM node being registered. */ - registerMenuPanel: function(aPanel) { + registerMenuPanel(aPanel) { CustomizableUIInternal.registerMenuPanel(aPanel); }, /** @@ -3087,7 +3087,7 @@ this.CustomizableUI = { * @param aDestroyPlacements whether to destroy the placements information * for the area, too. */ - unregisterArea: function(aName, aDestroyPlacements) { + unregisterArea(aName, aDestroyPlacements) { CustomizableUIInternal.unregisterArea(aName, aDestroyPlacements); }, /** @@ -3112,7 +3112,7 @@ this.CustomizableUI = { * pass a position, the widget will be added to the end * of the area. */ - addWidgetToArea: function(aWidgetId, aArea, aPosition) { + addWidgetToArea(aWidgetId, aArea, aPosition) { CustomizableUIInternal.addWidgetToArea(aWidgetId, aArea, aPosition); }, /** @@ -3124,7 +3124,7 @@ this.CustomizableUI = { * * @param aWidgetId the ID of the widget to remove */ - removeWidgetFromArea: function(aWidgetId) { + removeWidgetFromArea(aWidgetId) { CustomizableUIInternal.removeWidgetFromArea(aWidgetId); }, /** @@ -3142,7 +3142,7 @@ this.CustomizableUI = { * widgets will be interpreted to mean moving the widget to * respectively the first or last position. */ - moveWidgetWithinArea: function(aWidgetId, aPosition) { + moveWidgetWithinArea(aWidgetId, aPosition) { CustomizableUIInternal.moveWidgetWithinArea(aWidgetId, aPosition); }, /** @@ -3161,7 +3161,7 @@ this.CustomizableUI = { * presumably you yourself need to create the widget in all the windows * and need to loop through them anyway. */ - ensureWidgetPlacedInWindow: function(aWidgetId, aWindow) { + ensureWidgetPlacedInWindow(aWidgetId, aWindow) { return CustomizableUIInternal.ensureWidgetPlacedInWindow(aWidgetId, aWindow); }, /** @@ -3176,7 +3176,7 @@ this.CustomizableUI = { * Firefox session, customization state is never saved. Typically, you * would do this using a try...finally block. */ - beginBatchUpdate: function() { + beginBatchUpdate() { CustomizableUIInternal.beginBatchUpdate(); }, /** @@ -3191,7 +3191,7 @@ this.CustomizableUI = { * @param aForceDirty force CustomizableUI to flush to the prefs file when * all batch updates have finished. */ - endBatchUpdate: function(aForceDirty) { + endBatchUpdate(aForceDirty) { CustomizableUIInternal.endBatchUpdate(aForceDirty); }, /** @@ -3267,7 +3267,7 @@ this.CustomizableUI = { * @param aProperties the specifications for the widget. * @return a wrapper around the created widget (see getWidget) */ - createWidget: function(aProperties) { + createWidget(aProperties) { return CustomizableUIInternal.wrapWidget( CustomizableUIInternal.createWidget(aProperties) ); @@ -3283,7 +3283,7 @@ this.CustomizableUI = { * * @param aWidgetId the ID of the widget to destroy */ - destroyWidget: function(aWidgetId) { + destroyWidget(aWidgetId) { CustomizableUIInternal.destroyWidget(aWidgetId); }, /** @@ -3346,7 +3346,7 @@ this.CustomizableUI = { * is no guarantee the widget exists because we cannot know in * advance if a XUL widget exists or not. */ - getWidget: function(aWidgetId) { + getWidget(aWidgetId) { return CustomizableUIInternal.wrapWidget(aWidgetId); }, /** @@ -3363,7 +3363,7 @@ this.CustomizableUI = { * * @return an array of widget wrappers (see getWidget) */ - getUnusedWidgets: function(aWindowPalette) { + getUnusedWidgets(aWindowPalette) { return CustomizableUIInternal.getUnusedWidgets(aWindowPalette).map( CustomizableUIInternal.wrapWidget, CustomizableUIInternal @@ -3380,7 +3380,7 @@ this.CustomizableUI = { * NB: will throw if called too early (before placements have been fetched) * or if the area is not currently known to CustomizableUI. */ - getWidgetIdsInArea: function(aArea) { + getWidgetIdsInArea(aArea) { if (!gAreas.has(aArea)) { throw new Error("Unknown customization area: " + aArea); } @@ -3406,7 +3406,7 @@ this.CustomizableUI = { * NB: will throw if called too early (before placements have been fetched) * or if the area is not currently known to CustomizableUI. */ - getWidgetsInArea: function(aArea) { + getWidgetsInArea(aArea) { return this.getWidgetIdsInArea(aArea).map( CustomizableUIInternal.wrapWidget, CustomizableUIInternal @@ -3430,7 +3430,7 @@ this.CustomizableUI = { * @return TYPE_TOOLBAR or TYPE_MENU_PANEL depending on the area, null if * the area is unknown. */ - getAreaType: function(aArea) { + getAreaType(aArea) { let area = gAreas.get(aArea); return area ? area.get("type") : null; }, @@ -3441,7 +3441,7 @@ this.CustomizableUI = { * @return `true` or `false` depending on the area, null if the area is unknown, * or its collapsed state cannot normally be controlled by the user */ - isToolbarDefaultCollapsed: function(aArea) { + isToolbarDefaultCollapsed(aArea) { let area = gAreas.get(aArea); return area ? area.get("defaultCollapsed") : null; }, @@ -3469,7 +3469,7 @@ this.CustomizableUI = { * @param aWindow the window where you want to fetch the DOM node. * @return the customize target DOM node for aArea in aWindow */ - getCustomizeTargetForArea: function(aArea, aWindow) { + getCustomizeTargetForArea(aArea, aWindow) { return CustomizableUIInternal.getCustomizeTargetForArea(aArea, aWindow); }, /** @@ -3479,7 +3479,7 @@ this.CustomizableUI = { * explicitly requests it. Firefox does this when the user clicks the * "Restore Defaults" button in customize mode. */ - reset: function() { + reset() { CustomizableUIInternal.reset(); }, @@ -3487,7 +3487,7 @@ this.CustomizableUI = { * Undo the previous reset, can only be called immediately after a reset. * @return a promise that will be resolved when the operation is complete. */ - undoReset: function() { + undoReset() { CustomizableUIInternal.undoReset(); }, @@ -3498,7 +3498,7 @@ this.CustomizableUI = { * other consumers. * @param aToolbarId the ID of the toolbar to remove */ - removeExtraToolbar: function(aToolbarId) { + removeExtraToolbar(aToolbarId) { CustomizableUIInternal.removeExtraToolbar(aToolbarId); }, @@ -3532,7 +3532,7 @@ this.CustomizableUI = { * * null // if the widget is not placed anywhere (ie in the palette) */ - getPlacementOfWidget: function(aWidgetId, aOnlyRegistered = true, aDeadAreas = false) { + getPlacementOfWidget(aWidgetId, aOnlyRegistered = true, aDeadAreas = false) { return CustomizableUIInternal.getPlacementOfWidget(aWidgetId, aOnlyRegistered, aDeadAreas); }, /** @@ -3553,7 +3553,7 @@ this.CustomizableUI = { * @return true if the widget can be removed from its area, * false otherwise. */ - isWidgetRemovable: function(aWidgetId) { + isWidgetRemovable(aWidgetId) { return CustomizableUIInternal.isWidgetRemovable(aWidgetId); }, /** @@ -3566,7 +3566,7 @@ this.CustomizableUI = { * @return true if this is possible, false if it is not. The same caveats as * for isWidgetRemovable apply, however, if no windows are open. */ - canWidgetMoveToArea: function(aWidgetId, aArea) { + canWidgetMoveToArea(aWidgetId, aArea) { return CustomizableUIInternal.canWidgetMoveToArea(aWidgetId, aArea); }, /** @@ -3587,7 +3587,7 @@ this.CustomizableUI = { * @param aToolbarId the toolbar whose visibility should be adjusted * @param aIsVisible whether the toolbar should be visible */ - setToolbarVisibility: function(aToolbarId, aIsVisible) { + setToolbarVisibility(aToolbarId, aIsVisible) { CustomizableUIInternal.setToolbarVisibility(aToolbarId, aIsVisible); }, @@ -3614,7 +3614,7 @@ this.CustomizableUI = { * otherwise we'll return the empty string * */ - getLocalizedProperty: function(aWidget, aProp, aFormatArgs, aDef) { + getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef) { return CustomizableUIInternal.getLocalizedProperty(aWidget, aProp, aFormatArgs, aDef); }, @@ -3627,7 +3627,7 @@ this.CustomizableUI = { * attribute will be set. If NULL, the shortcut will be * set on aShortcutNode; */ - addShortcut: function(aShortcutNode, aTargetNode) { + addShortcut(aShortcutNode, aTargetNode) { return CustomizableUIInternal.addShortcut(aShortcutNode, aTargetNode); }, /** @@ -3636,7 +3636,7 @@ this.CustomizableUI = { * * @param aNode a node whose panel should be closed; */ - hidePanelForNode: function(aNode) { + hidePanelForNode(aNode) { CustomizableUIInternal.hidePanelForNode(aNode); }, /** @@ -3645,7 +3645,7 @@ this.CustomizableUI = { * @param aWidgetId the widget ID to check. * @return true if the widget is 'special', false otherwise. */ - isSpecialWidget: function(aWidgetId) { + isSpecialWidget(aWidgetId) { return CustomizableUIInternal.isSpecialWidget(aWidgetId); }, /** @@ -3655,7 +3655,7 @@ this.CustomizableUI = { * * @param aPanel the panel to which listeners should be attached. */ - addPanelCloseListeners: function(aPanel) { + addPanelCloseListeners(aPanel) { CustomizableUIInternal.addPanelCloseListeners(aPanel); }, /** @@ -3665,7 +3665,7 @@ this.CustomizableUI = { * * @param aPanel the panel from which listeners should be removed. */ - removePanelCloseListeners: function(aPanel) { + removePanelCloseListeners(aPanel) { CustomizableUIInternal.removePanelCloseListeners(aPanel); }, /** @@ -3675,7 +3675,7 @@ this.CustomizableUI = { * @param aWidgetId the ID of the widget that is being dragged to an area. * @param aArea the ID of the area to which the widget is being dragged. */ - onWidgetDrag: function(aWidgetId, aArea) { + onWidgetDrag(aWidgetId, aArea) { CustomizableUIInternal.notifyListeners("onWidgetDrag", aWidgetId, aArea); }, /** @@ -3683,7 +3683,7 @@ this.CustomizableUI = { * Customize Mode only, do not use otherwise. * @param aWindow the window entering customize mode */ - notifyStartCustomizing: function(aWindow) { + notifyStartCustomizing(aWindow) { CustomizableUIInternal.notifyListeners("onCustomizeStart", aWindow); }, /** @@ -3691,7 +3691,7 @@ this.CustomizableUI = { * Customize Mode only, do not use otherwise. * @param aWindow the window exiting customize mode */ - notifyEndCustomizing: function(aWindow) { + notifyEndCustomizing(aWindow) { CustomizableUIInternal.notifyListeners("onCustomizeEnd", aWindow); }, @@ -3703,7 +3703,7 @@ this.CustomizableUI = { * @param aDetails optional, the details of the event. * @param aWindow optional, the window in which to send the event. */ - dispatchToolboxEvent: function(aEvent, aDetails = {}, aWindow = null) { + dispatchToolboxEvent(aEvent, aDetails = {}, aWindow = null) { CustomizableUIInternal.dispatchToolboxEvent(aEvent, aDetails, aWindow); }, @@ -3713,7 +3713,7 @@ this.CustomizableUI = { * @param aAreaId the ID of an area to check for overflowable-ness * @return true if the area is overflowable, false otherwise. */ - isAreaOverflowable: function(aAreaId) { + isAreaOverflowable(aAreaId) { let area = gAreas.get(aAreaId); return area ? area.get("type") == this.TYPE_TOOLBAR && area.get("overflowable") : false; @@ -3728,7 +3728,7 @@ this.CustomizableUI = { * menu panel, "palette" if it is in the (visible!) customization * palette, undefined otherwise. */ - getPlaceForItem: function(aElement) { + getPlaceForItem(aElement) { let place; let node = aElement; while (node && !place) { @@ -3748,7 +3748,7 @@ this.CustomizableUI = { * Check if a toolbar is builtin or not. * @param aToolbarId the ID of the toolbar you want to check */ - isBuiltinToolbar: function(aToolbarId) { + isBuiltinToolbar(aToolbarId) { return CustomizableUIInternal._builtinToolbars.has(aToolbarId); }, }; @@ -4038,7 +4038,7 @@ OverflowableToolbar.prototype = { initialized: false, _forceOnOverflow: false, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "browser-delayed-startup-finished" && aSubject == this._toolbar.ownerGlobal) { Services.obs.removeObserver(this, "browser-delayed-startup-finished"); @@ -4046,7 +4046,7 @@ OverflowableToolbar.prototype = { } }, - init: function() { + init() { let doc = this._toolbar.ownerDocument; let window = doc.defaultView; window.addEventListener("resize", this); @@ -4075,7 +4075,7 @@ OverflowableToolbar.prototype = { this.initialized = true; }, - uninit: function() { + uninit() { this._toolbar.removeEventListener("overflow", this._toolbar); this._toolbar.removeEventListener("underflow", this._toolbar); this._toolbar.removeAttribute("overflowable"); @@ -4099,7 +4099,7 @@ OverflowableToolbar.prototype = { CustomizableUIInternal.removePanelCloseListeners(this._panel); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "aftercustomization": this._enable(); @@ -4128,7 +4128,7 @@ OverflowableToolbar.prototype = { } }, - show: function() { + show() { if (this._panel.state == "open") { return Promise.resolve(); } @@ -4151,7 +4151,7 @@ OverflowableToolbar.prototype = { }); }, - _onClickChevron: function(aEvent) { + _onClickChevron(aEvent) { if (this._chevron.open) { this._panel.hidePopup(); this._chevron.open = false; @@ -4160,7 +4160,7 @@ OverflowableToolbar.prototype = { } }, - _onPanelHiding: function(aEvent) { + _onPanelHiding(aEvent) { this._chevron.open = false; this._panel.removeEventListener("dragover", this); this._panel.removeEventListener("dragend", this); @@ -4169,7 +4169,7 @@ OverflowableToolbar.prototype = { gELS.removeSystemEventListener(contextMenu, 'command', this, true); }, - onOverflow: function(aEvent) { + onOverflow(aEvent) { // The rangeParent check is here because of bug 1111986 and ensuring that // overflow events from the bookmarks toolbar items or similar things that // manage their own overflow don't trigger an overflow on the entire toolbar @@ -4202,7 +4202,7 @@ OverflowableToolbar.prototype = { win.UpdateUrlbarSearchSplitterState(); }, - _onResize: function(aEvent) { + _onResize(aEvent) { if (!this._lazyResizeHandler) { this._lazyResizeHandler = new DeferredTask(this._onLazyResize.bind(this), LAZY_RESIZE_INTERVAL_MS); @@ -4210,7 +4210,7 @@ OverflowableToolbar.prototype = { this._lazyResizeHandler.arm(); }, - _moveItemsBackToTheirOrigin: function(shouldMoveAllItems) { + _moveItemsBackToTheirOrigin(shouldMoveAllItems) { let placements = gPlacements.get(this._toolbar.id); while (this._list.firstChild) { let child = this._list.firstChild; @@ -4256,7 +4256,7 @@ OverflowableToolbar.prototype = { } }, - _onLazyResize: function() { + _onLazyResize() { if (!this._enabled) return; @@ -4267,7 +4267,7 @@ OverflowableToolbar.prototype = { } }, - _disable: function() { + _disable() { this._enabled = false; this._moveItemsBackToTheirOrigin(true); if (this._lazyResizeHandler) { @@ -4275,12 +4275,12 @@ OverflowableToolbar.prototype = { } }, - _enable: function() { + _enable() { this._enabled = true; this.onOverflow(); }, - onWidgetBeforeDOMChange: function(aNode, aNextNode, aContainer) { + onWidgetBeforeDOMChange(aNode, aNextNode, aContainer) { if (aContainer != this._target && aContainer != this._list) { return; } @@ -4303,7 +4303,7 @@ OverflowableToolbar.prototype = { } }, - onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer) { + onWidgetAfterDOMChange(aNode, aNextNode, aContainer) { if (aContainer != this._target && aContainer != this._list) { return; } @@ -4358,7 +4358,7 @@ OverflowableToolbar.prototype = { } }, - findOverflowedInsertionPoints: function(aNode) { + findOverflowedInsertionPoints(aNode) { let newNodeCanOverflow = aNode.getAttribute("overflows") != "false"; let areaId = this._toolbar.id; let placements = gPlacements.get(areaId); @@ -4391,7 +4391,7 @@ OverflowableToolbar.prototype = { return [containerForAppending, null]; }, - getContainerFor: function(aNode) { + getContainerFor(aNode) { if (aNode.getAttribute("overflowedItem") == "true") { return this._list; } @@ -4399,7 +4399,7 @@ OverflowableToolbar.prototype = { }, _hideTimeoutId: null, - _showWithTimeout: function() { + _showWithTimeout() { this.show().then(function() { let window = this._toolbar.ownerGlobal; if (this._hideTimeoutId) { diff --git a/browser/components/customizableui/CustomizableWidgets.jsm b/browser/components/customizableui/CustomizableWidgets.jsm index 6b1dc8ea1af6..6f30303afb49 100644 --- a/browser/components/customizableui/CustomizableWidgets.jsm +++ b/browser/components/customizableui/CustomizableWidgets.jsm @@ -178,7 +178,7 @@ const CustomizableWidgets = [ shortcutId: "key_gotoHistory", tooltiptext: "history-panelmenu.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { // Populate our list of history const kMaxResults = 15; let doc = aEvent.target.ownerDocument; @@ -204,7 +204,7 @@ const CustomizableWidgets = [ PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase) .asyncExecuteLegacyQueries([query], 1, options, { - handleResult: function(aResultSet) { + handleResult(aResultSet) { let onItemCommand = function(aItemCommandEvent) { // Only handle the click event for middle clicks, we're using the command // event otherwise. @@ -237,10 +237,10 @@ const CustomizableWidgets = [ } items.appendChild(fragment); }, - handleError: function(aError) { + handleError(aError) { log.debug("History view tried to show but had an error: " + aError); }, - handleCompletion: function(aReason) { + handleCompletion(aReason) { log.debug("History view is being shown!"); }, }); @@ -280,7 +280,7 @@ const CustomizableWidgets = [ } recentlyClosedWindows.appendChild(windowsFragment); }, - onCreated: function(aNode) { + onCreated(aNode) { // Middle clicking recently closed items won't close the panel - cope: let onRecentlyClosedClick = function(aEvent) { if (aEvent.button == 1) { @@ -293,7 +293,7 @@ const CustomizableWidgets = [ recentlyClosedTabs.addEventListener("click", onRecentlyClosedClick); recentlyClosedWindows.addEventListener("click", onRecentlyClosedClick); }, - onViewHiding: function(aEvent) { + onViewHiding(aEvent) { log.debug("History view is being hidden!"); } }, { @@ -466,7 +466,7 @@ const CustomizableWidgets = [ appendTo.appendChild(messageLabel); return messageLabel; }, - _appendClient: function(client, attachFragment) { + _appendClient(client, attachFragment) { let doc = attachFragment.ownerDocument; // Create the element for the remote client. let clientItem = doc.createElementNS(kNSXUL, "label"); @@ -510,7 +510,7 @@ const CustomizableWidgets = [ id: "privatebrowsing-button", shortcutId: "key_privatebrowsing", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(e) { + onCommand(e) { let win = e.target.ownerGlobal; win.OpenBrowserWindow({private: true}); } @@ -519,7 +519,7 @@ const CustomizableWidgets = [ shortcutId: "key_savePage", tooltiptext: "save-page-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; win.saveBrowser(win.gBrowser.selectedBrowser); } @@ -528,7 +528,7 @@ const CustomizableWidgets = [ shortcutId: "key_find", tooltiptext: "find-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; if (win.gFindBar) { win.gFindBar.onFindCommand(); @@ -539,7 +539,7 @@ const CustomizableWidgets = [ shortcutId: "openFileKb", tooltiptext: "open-file-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; win.BrowserOpenFileWindow(); } @@ -548,7 +548,7 @@ const CustomizableWidgets = [ type: "view", viewId: "PanelUI-sidebar", tooltiptext: "sidebar-button.tooltiptext2", - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { // Populate the subview with whatever menuitems are in the // sidebar menu. We skip menu elements, because the menu panel has no way // of dealing with those right now. @@ -565,7 +565,7 @@ const CustomizableWidgets = [ id: "social-share-button", // custom build our button so we can attach to the share command type: "custom", - onBuild: function(aDocument) { + onBuild(aDocument) { let node = aDocument.createElementNS(kNSXUL, "toolbarbutton"); node.setAttribute("id", this.id); node.classList.add("toolbarbutton-1"); @@ -607,7 +607,7 @@ const CustomizableWidgets = [ shortcutId: "key_openAddons", tooltiptext: "add-ons-button.tooltiptext3", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; win.BrowserOpenAddonsMgr(); } @@ -616,7 +616,7 @@ const CustomizableWidgets = [ type: "custom", tooltiptext: "zoom-controls.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onBuild: function(aDocument) { + onBuild(aDocument) { const kPanelId = "PanelUI-popup"; let areaType = CustomizableUI.getAreaType(this.currentArea); let inPanel = areaType == CustomizableUI.TYPE_MENU_PANEL; @@ -768,13 +768,13 @@ const CustomizableWidgets = [ container.removeEventListener("TabSelect", updateZoomResetButton); }.bind(this), - onCustomizeStart: function(aWindow) { + onCustomizeStart(aWindow) { if (aWindow.document == aDocument) { updateZoomResetButton(); } }, - onCustomizeEnd: function(aWindow) { + onCustomizeEnd(aWindow) { if (aWindow.document == aDocument) { updateZoomResetButton(); } @@ -796,7 +796,7 @@ const CustomizableWidgets = [ type: "custom", tooltiptext: "edit-controls.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onBuild: function(aDocument) { + onBuild(aDocument) { let buttons = [{ id: "cut-button", command: "cmd_cut", @@ -894,7 +894,7 @@ const CustomizableWidgets = [ viewId: "PanelUI-feeds", tooltiptext: "feed-button.tooltiptext2", defaultArea: CustomizableUI.AREA_PANEL, - onClick: function(aEvent) { + onClick(aEvent) { let win = aEvent.target.ownerGlobal; let feeds = win.gBrowser.selectedBrowser.feeds; @@ -908,7 +908,7 @@ const CustomizableWidgets = [ CustomizableUI.hidePanelForNode(aEvent.target); } }, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { let doc = aEvent.target.ownerDocument; let container = doc.getElementById("PanelUI-feeds"); let gotView = doc.defaultView.FeedHandler.buildFeedList(container, true); @@ -920,7 +920,7 @@ const CustomizableWidgets = [ return; } }, - onCreated: function(node) { + onCreated(node) { let win = node.ownerGlobal; let selectedBrowser = win.gBrowser.selectedBrowser; let feeds = selectedBrowser && selectedBrowser.feeds; @@ -935,12 +935,12 @@ const CustomizableWidgets = [ viewId: "PanelUI-characterEncodingView", tooltiptext: "characterencoding-button2.tooltiptext", defaultArea: CustomizableUI.AREA_PANEL, - maybeDisableMenu: function(aDocument) { + maybeDisableMenu(aDocument) { let window = aDocument.defaultView; return !(window.gBrowser && window.gBrowser.selectedBrowser.mayEnableCharacterEncodingMenu); }, - populateList: function(aDocument, aContainerId, aSection) { + populateList(aDocument, aContainerId, aSection) { let containerElem = aDocument.getElementById(aContainerId); containerElem.addEventListener("command", this.onCommand, false); @@ -957,7 +957,7 @@ const CustomizableWidgets = [ containerElem.appendChild(elem); } }, - updateCurrentCharset: function(aDocument) { + updateCurrentCharset(aDocument) { let currentCharset = aDocument.defaultView.gBrowser.selectedBrowser.characterSet; currentCharset = CharsetMenu.foldCharset(currentCharset); @@ -967,7 +967,7 @@ const CustomizableWidgets = [ this._updateElements(elements, currentCharset); }, - updateCurrentDetector: function(aDocument) { + updateCurrentDetector(aDocument) { let detectorContainer = aDocument.getElementById("PanelUI-characterEncodingView-autodetect"); let currentDetector; try { @@ -977,7 +977,7 @@ const CustomizableWidgets = [ this._updateElements(detectorContainer.childNodes, currentDetector); }, - _updateElements: function(aElements, aCurrentItem) { + _updateElements(aElements, aCurrentItem) { if (!aElements.length) { return; } @@ -995,7 +995,7 @@ const CustomizableWidgets = [ } } }, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { let document = aEvent.target.ownerDocument; let autoDetectLabelId = "PanelUI-characterEncodingView-autodetect-label"; @@ -1016,7 +1016,7 @@ const CustomizableWidgets = [ this.updateCurrentDetector(document); this.updateCurrentCharset(document); }, - onCommand: function(aEvent) { + onCommand(aEvent) { let node = aEvent.target; if (!node.hasAttribute || !node.section) { return; @@ -1044,7 +1044,7 @@ const CustomizableWidgets = [ window.BrowserCharsetReload(); } }, - onCreated: function(aNode) { + onCreated(aNode) { const kPanelId = "PanelUI-popup"; let document = aNode.ownerDocument; @@ -1095,7 +1095,7 @@ const CustomizableWidgets = [ }, { id: "email-link-button", tooltiptext: "email-link-button.tooltiptext3", - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.view; win.MailIntegration.sendLinkForBrowser(win.gBrowser.selectedBrowser) } @@ -1104,7 +1104,7 @@ const CustomizableWidgets = [ type: "view", viewId: "PanelUI-containers", hasObserver: false, - onCreated: function(aNode) { + onCreated(aNode) { let doc = aNode.ownerDocument; let win = doc.defaultView; let items = doc.getElementById("PanelUI-containersItems"); @@ -1129,7 +1129,7 @@ const CustomizableWidgets = [ this.hasObserver = true; } }, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { let doc = aEvent.target.ownerDocument; let items = doc.getElementById("PanelUI-containersItems"); @@ -1187,7 +1187,7 @@ const CustomizableWidgets = [ let preferencesButton = { id: "preferences-button", defaultArea: CustomizableUI.AREA_PANEL, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.target.ownerGlobal; win.openPreferences(); } @@ -1209,7 +1209,7 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { type: "view", viewId: "PanelUI-panicView", _sanitizer: null, - _ensureSanitizer: function() { + _ensureSanitizer() { if (!this.sanitizer) { let scope = {}; Services.scriptloader.loadSubScript("chrome://browser/content/sanitize.js", @@ -1219,11 +1219,11 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { this._sanitizer.ignoreTimespan = false; } }, - _getSanitizeRange: function(aDocument) { + _getSanitizeRange(aDocument) { let group = aDocument.getElementById("PanelUI-panic-timeSpan"); return this._Sanitizer.getClearRange(+group.value); }, - forgetButtonCalled: function(aEvent) { + forgetButtonCalled(aEvent) { let doc = aEvent.target.ownerDocument; this._ensureSanitizer(); this._sanitizer.range = this._getSanitizeRange(doc); @@ -1249,18 +1249,18 @@ if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) { } }); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "command": this.forgetButtonCalled(aEvent); break; } }, - onViewShowing: function(aEvent) { + onViewShowing(aEvent) { let forgetButton = aEvent.target.querySelector("#PanelUI-panic-view-button"); forgetButton.addEventListener("command", this); }, - onViewHiding: function(aEvent) { + onViewHiding(aEvent) { let forgetButton = aEvent.target.querySelector("#PanelUI-panic-view-button"); forgetButton.removeEventListener("command", this); }, @@ -1272,12 +1272,12 @@ if (AppConstants.E10S_TESTING_ONLY) { CustomizableWidgets.push({ id: "e10s-button", defaultArea: CustomizableUI.AREA_PANEL, - onBuild: function(aDocument) { + onBuild(aDocument) { let node = aDocument.createElementNS(kNSXUL, "toolbarbutton"); node.setAttribute("label", CustomizableUI.getLocalizedProperty(this, "label")); node.setAttribute("tooltiptext", CustomizableUI.getLocalizedProperty(this, "tooltiptext")); }, - onCommand: function(aEvent) { + onCommand(aEvent) { let win = aEvent.view; win.OpenBrowserWindow({remote: false}); }, diff --git a/browser/components/customizableui/CustomizeMode.jsm b/browser/components/customizableui/CustomizeMode.jsm index 655756cfb2f5..888708ac65ff 100644 --- a/browser/components/customizableui/CustomizeMode.jsm +++ b/browser/components/customizableui/CustomizeMode.jsm @@ -130,13 +130,13 @@ CustomizeMode.prototype = { return this.window.CustomizationHandler; }, - uninit: function() { + uninit() { if (AppConstants.CAN_DRAW_IN_TITLEBAR) { Services.prefs.removeObserver(kDrawInTitlebarPref, this); } }, - toggle: function() { + toggle() { if (this._handler.isEnteringCustomizeMode || this._handler.isExitingCustomizeMode) { this._wantToBeInCustomizeMode = !this._wantToBeInCustomizeMode; return; @@ -148,7 +148,7 @@ CustomizeMode.prototype = { } }, - _updateLWThemeButtonIcon: function() { + _updateLWThemeButtonIcon() { let lwthemeButton = this.document.getElementById("customization-lwtheme-button"); let lwthemeIcon = this.document.getAnonymousElementByAttribute(lwthemeButton, "class", "button-icon"); @@ -156,7 +156,7 @@ CustomizeMode.prototype = { "url(" + LightweightThemeManager.currentTheme.iconURL + ")" : ""; }, - setTab: function(aTab) { + setTab(aTab) { if (gTab == aTab) { return; } @@ -186,7 +186,7 @@ CustomizeMode.prototype = { } }, - enter: function() { + enter() { this._wantToBeInCustomizeMode = true; if (this._customizing || this._handler.isEnteringCustomizeMode) { @@ -380,7 +380,7 @@ CustomizeMode.prototype = { }.bind(this)); }, - exit: function() { + exit() { this._wantToBeInCustomizeMode = false; if (!this._customizing || this._handler.isExitingCustomizeMode) { @@ -557,7 +557,7 @@ CustomizeMode.prototype = { * phases, there is a "customizing" attribute set on the main-window to simplify * excluding certain styles while in any phase of customize mode. */ - _doTransition: function(aEntering) { + _doTransition(aEntering) { let deck = this.document.getElementById("content-deck"); let customizeTransitionEndPromise = new Promise(resolve => { let customizeTransitionEnd = (aEvent) => { @@ -603,7 +603,7 @@ CustomizeMode.prototype = { return customizeTransitionEndPromise; }, - updateLWTStyling: function(aData) { + updateLWTStyling(aData) { let docElement = this.document.documentElement; if (!aData) { let lwt = docElement._lightweightTheme; @@ -654,7 +654,7 @@ CustomizeMode.prototype = { docElement.style.removeProperty("background-color"); }, - removeLWTStyling: function() { + removeLWTStyling() { let affectedNodes = AppConstants.platform == "macosx" ? ["tab-view-deck", "titlebar"] : ["tab-view-deck"]; @@ -671,11 +671,11 @@ CustomizeMode.prototype = { } }, - _getHeaderImageRef: function(aData) { + _getHeaderImageRef(aData) { return "url(\"" + aData.headerURL.replace(/"/g, '\\"') + "\")"; }, - maybeShowTip: function(aAnchor) { + maybeShowTip(aAnchor) { let shown = false; const kShownPref = "browser.customizemode.tip0.shown"; try { @@ -711,11 +711,11 @@ CustomizeMode.prototype = { Services.prefs.setBoolPref(kShownPref, true); }, - hideTip: function() { + hideTip() { this.tipPanel.hidePopup(); }, - _getCustomizableChildForNode: function(aNode) { + _getCustomizableChildForNode(aNode) { // NB: adjusted from _getCustomizableParent to keep that method fast // (it's used during drags), and avoid multiple DOM loops let areas = CustomizableUI.areas; @@ -746,7 +746,7 @@ CustomizeMode.prototype = { return null; }, - addToToolbar: function(aNode) { + addToToolbar(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -757,7 +757,7 @@ CustomizeMode.prototype = { } }, - addToPanel: function(aNode) { + addToPanel(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -768,7 +768,7 @@ CustomizeMode.prototype = { } }, - removeFromArea: function(aNode) { + removeFromArea(aNode) { aNode = this._getCustomizableChildForNode(aNode); if (aNode.localName == "toolbarpaletteitem" && aNode.firstChild) { aNode = aNode.firstChild; @@ -779,7 +779,7 @@ CustomizeMode.prototype = { } }, - populatePalette: function() { + populatePalette() { let fragment = this.document.createDocumentFragment(); let toolboxPalette = this.window.gNavToolbox.palette; @@ -805,7 +805,7 @@ CustomizeMode.prototype = { // Would ensure no weird interactions/event handling from original node, // and makes it possible to put this in a lazy-loaded iframe/real tab // while still getting rid of the need for overlays. - makePaletteItem: function(aWidget, aPlace) { + makePaletteItem(aWidget, aPlace) { let widgetNode = aWidget.forWindow(this.window).node; if (!widgetNode) { log.error("Widget with id " + aWidget.id + " does not return a valid node"); @@ -821,7 +821,7 @@ CustomizeMode.prototype = { return wrapper; }, - depopulatePalette: function() { + depopulatePalette() { return Task.spawn(function*() { this.visiblePalette.hidden = true; let paletteChild = this.visiblePalette.firstChild; @@ -851,7 +851,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - isCustomizableItem: function(aNode) { + isCustomizableItem(aNode) { return aNode.localName == "toolbarbutton" || aNode.localName == "toolbaritem" || aNode.localName == "toolbarseparator" || @@ -859,11 +859,11 @@ CustomizeMode.prototype = { aNode.localName == "toolbarspacer"; }, - isWrappedToolbarItem: function(aNode) { + isWrappedToolbarItem(aNode) { return aNode.localName == "toolbarpaletteitem"; }, - deferredWrapToolbarItem: function(aNode, aPlace) { + deferredWrapToolbarItem(aNode, aPlace) { return new Promise(resolve => { dispatchFunction(() => { let wrapper = this.wrapToolbarItem(aNode, aPlace); @@ -872,7 +872,7 @@ CustomizeMode.prototype = { }); }, - wrapToolbarItem: function(aNode, aPlace) { + wrapToolbarItem(aNode, aPlace) { if (!this.isCustomizableItem(aNode)) { return aNode; } @@ -890,7 +890,7 @@ CustomizeMode.prototype = { return wrapper; }, - createOrUpdateWrapper: function(aNode, aPlace, aIsUpdate) { + createOrUpdateWrapper(aNode, aPlace, aIsUpdate) { let wrapper; if (aIsUpdate && aNode.parentNode && aNode.parentNode.localName == "toolbarpaletteitem") { wrapper = aNode.parentNode; @@ -980,7 +980,7 @@ CustomizeMode.prototype = { return wrapper; }, - deferredUnwrapToolbarItem: function(aWrapper) { + deferredUnwrapToolbarItem(aWrapper) { return new Promise(resolve => { dispatchFunction(() => { let item = null; @@ -994,7 +994,7 @@ CustomizeMode.prototype = { }); }, - unwrapToolbarItem: function(aWrapper) { + unwrapToolbarItem(aWrapper) { if (aWrapper.nodeName != "toolbarpaletteitem") { return aWrapper; } @@ -1045,7 +1045,7 @@ CustomizeMode.prototype = { return toolbarItem; }, - _wrapToolbarItem: function*(aArea) { + *_wrapToolbarItem(aArea) { let target = CustomizableUI.getCustomizeTargetForArea(aArea, this.window); if (!target || this.areas.has(target)) { return null; @@ -1061,7 +1061,7 @@ CustomizeMode.prototype = { return target; }, - _wrapToolbarItemSync: function(aArea) { + _wrapToolbarItemSync(aArea) { let target = CustomizableUI.getCustomizeTargetForArea(aArea, this.window); if (!target || this.areas.has(target)) { return null; @@ -1082,13 +1082,13 @@ CustomizeMode.prototype = { return target; }, - _wrapToolbarItems: function*() { + *_wrapToolbarItems() { for (let area of CustomizableUI.areas) { yield this._wrapToolbarItem(area); } }, - _addDragHandlers: function(aTarget) { + _addDragHandlers(aTarget) { aTarget.addEventListener("dragstart", this, true); aTarget.addEventListener("dragover", this, true); aTarget.addEventListener("dragexit", this, true); @@ -1096,7 +1096,7 @@ CustomizeMode.prototype = { aTarget.addEventListener("dragend", this, true); }, - _wrapItemsInArea: function(target) { + _wrapItemsInArea(target) { for (let child of target.children) { if (this.isCustomizableItem(child)) { this.wrapToolbarItem(child, CustomizableUI.getPlaceForItem(child)); @@ -1104,7 +1104,7 @@ CustomizeMode.prototype = { } }, - _removeDragHandlers: function(aTarget) { + _removeDragHandlers(aTarget) { aTarget.removeEventListener("dragstart", this, true); aTarget.removeEventListener("dragover", this, true); aTarget.removeEventListener("dragexit", this, true); @@ -1112,7 +1112,7 @@ CustomizeMode.prototype = { aTarget.removeEventListener("dragend", this, true); }, - _unwrapItemsInArea: function(target) { + _unwrapItemsInArea(target) { for (let toolbarItem of target.children) { if (this.isWrappedToolbarItem(toolbarItem)) { this.unwrapToolbarItem(toolbarItem); @@ -1120,7 +1120,7 @@ CustomizeMode.prototype = { } }, - _unwrapToolbarItems: function() { + _unwrapToolbarItems() { return Task.spawn(function*() { for (let target of this.areas) { for (let toolbarItem of target.children) { @@ -1134,7 +1134,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - _removeExtraToolbarsIfEmpty: function() { + _removeExtraToolbarsIfEmpty() { let toolbox = this.window.gNavToolbox; for (let child of toolbox.children) { if (child.hasAttribute("customindex")) { @@ -1146,7 +1146,7 @@ CustomizeMode.prototype = { } }, - persistCurrentSets: function(aSetBeforePersisting) { + persistCurrentSets(aSetBeforePersisting) { let document = this.document; let toolbars = document.querySelectorAll("toolbar[customizable='true'][currentset]"); for (let toolbar of toolbars) { @@ -1159,7 +1159,7 @@ CustomizeMode.prototype = { } }, - reset: function() { + reset() { this.resetting = true; // Disable the reset button temporarily while resetting: let btn = this.document.getElementById("customization-reset-button"); @@ -1190,7 +1190,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - undoReset: function() { + undoReset() { this.resetting = true; return Task.spawn(function*() { @@ -1214,7 +1214,7 @@ CustomizeMode.prototype = { }.bind(this)).then(null, log.error); }, - _onToolbarVisibilityChange: function(aEvent) { + _onToolbarVisibilityChange(aEvent) { let toolbar = aEvent.target; if (aEvent.detail.visible && toolbar.getAttribute("customizable") == "true") { toolbar.setAttribute("customizing", "true"); @@ -1225,19 +1225,19 @@ CustomizeMode.prototype = { this.updateLWTStyling(); }, - onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { this._onUIChange(); }, - onWidgetAdded: function(aWidgetId, aArea, aPosition) { + onWidgetAdded(aWidgetId, aArea, aPosition) { this._onUIChange(); }, - onWidgetRemoved: function(aWidgetId, aArea) { + onWidgetRemoved(aWidgetId, aArea) { this._onUIChange(); }, - onWidgetBeforeDOMChange: function(aNodeToChange, aSecondaryNode, aContainer) { + onWidgetBeforeDOMChange(aNodeToChange, aSecondaryNode, aContainer) { if (aContainer.ownerGlobal != this.window || this.resetting) { return; } @@ -1254,7 +1254,7 @@ CustomizeMode.prototype = { } }, - onWidgetAfterDOMChange: function(aNodeToChange, aSecondaryNode, aContainer) { + onWidgetAfterDOMChange(aNodeToChange, aSecondaryNode, aContainer) { if (aContainer.ownerGlobal != this.window || this.resetting) { return; } @@ -1284,7 +1284,7 @@ CustomizeMode.prototype = { } }, - onWidgetDestroyed: function(aWidgetId) { + onWidgetDestroyed(aWidgetId) { let wrapper = this.document.getElementById("wrapper-" + aWidgetId); if (wrapper) { let wasInPanel = wrapper.parentNode == this.panelUIContents; @@ -1295,7 +1295,7 @@ CustomizeMode.prototype = { } }, - onWidgetAfterCreation: function(aWidgetId, aArea) { + onWidgetAfterCreation(aWidgetId, aArea) { // If the node was added to an area, we would have gotten an onWidgetAdded notification, // plus associated DOM change notifications, so only do stuff for the palette: if (!aArea) { @@ -1309,7 +1309,7 @@ CustomizeMode.prototype = { } }, - onAreaNodeRegistered: function(aArea, aContainer) { + onAreaNodeRegistered(aArea, aContainer) { if (aContainer.ownerDocument == this.document) { this._wrapItemsInArea(aContainer); this._addDragHandlers(aContainer); @@ -1318,7 +1318,7 @@ CustomizeMode.prototype = { } }, - onAreaNodeUnregistered: function(aArea, aContainer, aReason) { + onAreaNodeUnregistered(aArea, aContainer, aReason) { if (aContainer.ownerDocument == this.document && aReason == CustomizableUI.REASON_AREA_UNREGISTERED) { this._unwrapItemsInArea(aContainer); this._removeDragHandlers(aContainer); @@ -1327,18 +1327,18 @@ CustomizeMode.prototype = { } }, - openAddonsManagerThemes: function(aEvent) { + openAddonsManagerThemes(aEvent) { aEvent.target.parentNode.parentNode.hidePopup(); this.window.BrowserOpenAddonsMgr('addons://list/theme'); }, - getMoreThemes: function(aEvent) { + getMoreThemes(aEvent) { aEvent.target.parentNode.parentNode.hidePopup(); let getMoreURL = Services.urlFormatter.formatURLPref("lightweightThemes.getMoreURL"); this.window.openUILinkIn(getMoreURL, "tab"); }, - onLWThemesMenuShowing: function(aEvent) { + onLWThemesMenuShowing(aEvent) { const DEFAULT_THEME_ID = "{972ce4c6-7e08-4474-a285-3208198ce6fd}"; const RECENT_LWT_COUNT = 5; @@ -1443,7 +1443,7 @@ CustomizeMode.prototype = { }.bind(this)); }, - _clearLWThemesMenu: function(panel) { + _clearLWThemesMenu(panel) { let footer = this.document.getElementById("customization-lwtheme-menu-footer"); let recommendedLabel = this.document.getElementById("customization-lwtheme-menu-recommended"); for (let element of [footer, recommendedLabel]) { @@ -1457,7 +1457,7 @@ CustomizeMode.prototype = { panel.removeAttribute("height"); }, - _onUIChange: function() { + _onUIChange() { this._changed = true; if (!this.resetting) { this._updateResetButton(); @@ -1467,22 +1467,22 @@ CustomizeMode.prototype = { CustomizableUI.dispatchToolboxEvent("customizationchange"); }, - _updateEmptyPaletteNotice: function() { + _updateEmptyPaletteNotice() { let paletteItems = this.visiblePalette.getElementsByTagName("toolbarpaletteitem"); this.paletteEmptyNotice.hidden = !!paletteItems.length; }, - _updateResetButton: function() { + _updateResetButton() { let btn = this.document.getElementById("customization-reset-button"); btn.disabled = CustomizableUI.inDefaultState; }, - _updateUndoResetButton: function() { + _updateUndoResetButton() { let undoResetButton = this.document.getElementById("customization-undo-reset-button"); undoResetButton.hidden = !CustomizableUI.canUndoReset; }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "toolbarvisibilitychange": this._onToolbarVisibilityChange(aEvent); @@ -1525,7 +1525,7 @@ CustomizeMode.prototype = { } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "nsPref:changed": this._updateResetButton(); @@ -1547,7 +1547,7 @@ CustomizeMode.prototype = { } }, - _updateTitlebarButton: function() { + _updateTitlebarButton() { if (!AppConstants.CAN_DRAW_IN_TITLEBAR) { return; } @@ -1564,7 +1564,7 @@ CustomizeMode.prototype = { } }, - toggleTitlebar: function(aShouldShowTitlebar) { + toggleTitlebar(aShouldShowTitlebar) { if (!AppConstants.CAN_DRAW_IN_TITLEBAR) { return; } @@ -1572,7 +1572,7 @@ CustomizeMode.prototype = { Services.prefs.setBoolPref(kDrawInTitlebarPref, !aShouldShowTitlebar); }, - _onDragStart: function(aEvent) { + _onDragStart(aEvent) { __dumpDragData(aEvent); let item = aEvent.target; while (item && item.localName != "toolbarpaletteitem") { @@ -1629,7 +1629,7 @@ CustomizeMode.prototype = { this._dragInitializeTimeout = this.window.setTimeout(this._initializeDragAfterMove, 0); }, - _onDragOver: function(aEvent) { + _onDragOver(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1726,7 +1726,7 @@ CustomizeMode.prototype = { aEvent.stopPropagation(); }, - _onDragDrop: function(aEvent) { + _onDragDrop(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1779,7 +1779,7 @@ CustomizeMode.prototype = { this._showPanelCustomizationPlaceholders(); }, - _applyDrop: function(aEvent, aTargetArea, aOriginArea, aDraggedItemId, aTargetNode) { + _applyDrop(aEvent, aTargetArea, aOriginArea, aDraggedItemId, aTargetNode) { let document = aEvent.target.ownerDocument; let draggedItem = document.getElementById(aDraggedItemId); draggedItem.hidden = false; @@ -1908,7 +1908,7 @@ CustomizeMode.prototype = { } }, - _onDragExit: function(aEvent) { + _onDragExit(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1929,7 +1929,7 @@ CustomizeMode.prototype = { /** * To workaround bug 460801 we manually forward the drop event here when dragend wouldn't be fired. */ - _onDragEnd: function(aEvent) { + _onDragEnd(aEvent) { if (this._isUnwantedDragDrop(aEvent)) { return; } @@ -1966,7 +1966,7 @@ CustomizeMode.prototype = { DragPositionManager.stop(); }, - _isUnwantedDragDrop: function(aEvent) { + _isUnwantedDragDrop(aEvent) { // The simulated events generated by synthesizeDragStart/synthesizeDrop in // mochitests are used only for testing whether the right data is being put // into the dataTransfer. Neither cause a real drop to occur, so they don't @@ -1985,7 +1985,7 @@ CustomizeMode.prototype = { mozSourceNode.ownerGlobal != this.window; }, - _setDragActive: function(aItem, aValue, aDraggedItemId, aInToolbar) { + _setDragActive(aItem, aValue, aDraggedItemId, aInToolbar) { if (!aItem) { return; } @@ -2033,7 +2033,7 @@ CustomizeMode.prototype = { } } }, - _cancelDragActive: function(aItem, aNextItem, aNoTransition) { + _cancelDragActive(aItem, aNextItem, aNoTransition) { this._updateToolbarCustomizationOutline(aItem.ownerGlobal); let currentArea = this._getCustomizableParent(aItem); if (!currentArea) { @@ -2069,7 +2069,7 @@ CustomizeMode.prototype = { } }, - _setGridDragActive: function(aDragOverNode, aDraggedItem, aValue) { + _setGridDragActive(aDragOverNode, aDraggedItem, aValue) { let targetArea = this._getCustomizableParent(aDragOverNode); let draggedWrapper = this.document.getElementById("wrapper-" + aDraggedItem.id); let originArea = this._getCustomizableParent(draggedWrapper); @@ -2080,7 +2080,7 @@ CustomizeMode.prototype = { originArea == targetArea); }, - _getDragItemSize: function(aDragOverNode, aDraggedItem) { + _getDragItemSize(aDragOverNode, aDraggedItem) { // Cache it good, cache it real good. if (!this._dragSizeMap) this._dragSizeMap = new WeakMap(); @@ -2140,7 +2140,7 @@ CustomizeMode.prototype = { return size; }, - _getCustomizableParent: function(aElement) { + _getCustomizableParent(aElement) { let areas = CustomizableUI.areas; areas.push(kPaletteId); while (aElement) { @@ -2152,7 +2152,7 @@ CustomizeMode.prototype = { return null; }, - _getDragOverNode: function(aEvent, aAreaElement, aInToolbar, aDraggedItemId) { + _getDragOverNode(aEvent, aAreaElement, aInToolbar, aDraggedItemId) { let expectedParent = aAreaElement.customizationTarget || aAreaElement; // Our tests are stupid. Cope: if (!aEvent.clientX && !aEvent.clientY) { @@ -2200,7 +2200,7 @@ CustomizeMode.prototype = { return targetNode || aEvent.target; }, - _onMouseDown: function(aEvent) { + _onMouseDown(aEvent) { log.debug("_onMouseDown"); if (aEvent.button != 0) { return; @@ -2214,7 +2214,7 @@ CustomizeMode.prototype = { } }, - _onMouseUp: function(aEvent) { + _onMouseUp(aEvent) { log.debug("_onMouseUp"); if (aEvent.button != 0) { return; @@ -2227,7 +2227,7 @@ CustomizeMode.prototype = { } }, - _getWrapper: function(aElement) { + _getWrapper(aElement) { while (aElement && aElement.localName != "toolbarpaletteitem") { if (aElement.localName == "toolbar") return null; @@ -2236,7 +2236,7 @@ CustomizeMode.prototype = { return aElement; }, - _showPanelCustomizationPlaceholders: function() { + _showPanelCustomizationPlaceholders() { let doc = this.document; let contents = this.panelUIContents; let narrowItemsAfterWideItem = 0; @@ -2271,7 +2271,7 @@ CustomizeMode.prototype = { } }, - _removePanelCustomizationPlaceholders: function() { + _removePanelCustomizationPlaceholders() { let contents = this.panelUIContents; let oldPlaceholders = contents.getElementsByClassName(kPlaceholderClass); while (oldPlaceholders.length) { @@ -2288,7 +2288,7 @@ CustomizeMode.prototype = { * outline to. If aToolbarArea is falsy, the outline will be * removed from all toolbar areas. */ - _updateToolbarCustomizationOutline: function(aWindow, aToolbarArea = null) { + _updateToolbarCustomizationOutline(aWindow, aToolbarArea = null) { // Remove the attribute from existing customization targets for (let area of CustomizableUI.areas) { if (CustomizableUI.getAreaType(area) != CustomizableUI.TYPE_TOOLBAR) { @@ -2307,7 +2307,7 @@ CustomizeMode.prototype = { } }, - _findVisiblePreviousSiblingNode: function(aReferenceNode) { + _findVisiblePreviousSiblingNode(aReferenceNode) { while (aReferenceNode && aReferenceNode.localName == "toolbarpaletteitem" && aReferenceNode.firstChild.hidden) { diff --git a/browser/components/customizableui/DragPositionManager.jsm b/browser/components/customizableui/DragPositionManager.jsm index 1b4eb59dc15f..65e2585a5a81 100644 --- a/browser/components/customizableui/DragPositionManager.jsm +++ b/browser/components/customizableui/DragPositionManager.jsm @@ -33,7 +33,7 @@ AreaPositionManager.prototype = { _nodePositionStore: null, _wideCache: null, - update: function(aContainer) { + update(aContainer) { this._nodePositionStore = new WeakMap(); this._wideCache = new Set(); let last = null; @@ -73,7 +73,7 @@ AreaPositionManager.prototype = { * where dy is more heavily weighted by a factor corresponding to the * ratio between the container's width and the height of its elements. */ - find: function(aContainer, aX, aY, aDraggedItemId) { + find(aContainer, aX, aY, aDraggedItemId) { let closest = null; let minCartesian = Number.MAX_VALUE; let containerX = this._containerInfo.left; @@ -130,7 +130,7 @@ AreaPositionManager.prototype = { * they would have if we had inserted something before aBefore. We use CSS * transforms for this, which are CSS transitioned. */ - insertPlaceholder: function(aContainer, aBefore, aWide, aSize, aIsFromThisArea) { + insertPlaceholder(aContainer, aBefore, aWide, aSize, aIsFromThisArea) { let isShifted = false; let shiftDown = aWide; for (let child of aContainer.children) { @@ -185,11 +185,11 @@ AreaPositionManager.prototype = { this._lastPlaceholderInsertion = aBefore; }, - isWide: function(aNode) { + isWide(aNode) { return this._wideCache.has(aNode.id); }, - _checkIfWide: function(aNode) { + _checkIfWide(aNode) { return this._inPanel && aNode && aNode.firstChild && aNode.firstChild.classList.contains(CustomizableUI.WIDE_PANEL_CLASS); }, @@ -201,7 +201,7 @@ AreaPositionManager.prototype = { * @param aNoTransition if truthy, adds a notransition attribute to the node * while resetting the transform. */ - clearPlaceholders: function(aContainer, aNoTransition) { + clearPlaceholders(aContainer, aNoTransition) { for (let child of aContainer.children) { if (aNoTransition) { child.setAttribute("notransition", true); @@ -220,7 +220,7 @@ AreaPositionManager.prototype = { } }, - _getNextPos: function(aNode, aShiftDown, aSize) { + _getNextPos(aNode, aShiftDown, aSize) { // Shifting down is easy: if (this._inPanel && aShiftDown) { return "translate(0, " + aSize.height + "px)"; @@ -228,7 +228,7 @@ AreaPositionManager.prototype = { return this._diffWithNext(aNode, aSize); }, - _diffWithNext: function(aNode, aSize) { + _diffWithNext(aNode, aSize) { let xDiff; let yDiff = null; let nodeBounds = this._lazyStoreGet(aNode); @@ -306,7 +306,7 @@ AreaPositionManager.prototype = { * @param aNodeBounds the bounding rect info of this node * @param aFirstNodeInRow the first node in aNode's row */ - _moveNextBasedOnPrevious: function(aNode, aNodeBounds, aFirstNodeInRow) { + _moveNextBasedOnPrevious(aNode, aNodeBounds, aFirstNodeInRow) { let next = this._getVisibleSiblingForDirection(aNode, "previous"); let otherBounds = this._lazyStoreGet(next); let side = this._dir == "ltr" ? "left" : "right"; @@ -328,7 +328,7 @@ AreaPositionManager.prototype = { * @param aNode the node whose position info we want * @return the position info */ - _lazyStoreGet: function(aNode) { + _lazyStoreGet(aNode) { let rect = this._nodePositionStore.get(aNode); if (!rect) { // getBoundingClientRect() returns a DOMRect that is live, meaning that @@ -352,7 +352,7 @@ AreaPositionManager.prototype = { return rect; }, - _firstInRow: function(aNode) { + _firstInRow(aNode) { // XXXmconley: I'm not entirely sure why we need to take the floor of these // values - it looks like, periodically, we're getting fractional pixels back // from lazyStoreGet. I've filed bug 994247 to investigate. @@ -368,7 +368,7 @@ AreaPositionManager.prototype = { return rv; }, - _getVisibleSiblingForDirection: function(aNode, aDirection) { + _getVisibleSiblingForDirection(aNode, aDirection) { let rv = aNode; do { rv = rv[aDirection + "Sibling"]; @@ -378,7 +378,7 @@ AreaPositionManager.prototype = { } var DragPositionManager = { - start: function(aWindow) { + start(aWindow) { let areas = CustomizableUI.areas.filter((area) => CustomizableUI.getAreaType(area) != "toolbar"); areas = areas.map((area) => CustomizableUI.getCustomizeTargetForArea(area, aWindow)); areas.push(aWindow.document.getElementById(kPaletteId)); @@ -392,7 +392,7 @@ var DragPositionManager = { } }, - add: function(aWindow, aArea, aContainer) { + add(aWindow, aArea, aContainer) { if (CustomizableUI.getAreaType(aArea) != "toolbar") { return; } @@ -400,7 +400,7 @@ var DragPositionManager = { gManagers.set(aContainer, new AreaPositionManager(aContainer)); }, - remove: function(aWindow, aArea, aContainer) { + remove(aWindow, aArea, aContainer) { if (CustomizableUI.getAreaType(aArea) != "toolbar") { return; } @@ -408,11 +408,11 @@ var DragPositionManager = { gManagers.delete(aContainer); }, - stop: function() { + stop() { gManagers = new WeakMap(); }, - getManagerForArea: function(aArea) { + getManagerForArea(aArea) { return gManagers.get(aArea); } }; diff --git a/browser/components/customizableui/PanelWideWidgetTracker.jsm b/browser/components/customizableui/PanelWideWidgetTracker.jsm index 768cebbca73e..a9b38c23eb26 100644 --- a/browser/components/customizableui/PanelWideWidgetTracker.jsm +++ b/browser/components/customizableui/PanelWideWidgetTracker.jsm @@ -22,33 +22,33 @@ var gSeenWidgets = new Set(); var PanelWideWidgetTracker = { // Listeners used to validate panel contents whenever they change: - onWidgetAdded: function(aWidgetId, aArea, aPosition) { + onWidgetAdded(aWidgetId, aArea, aPosition) { if (aArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); let moveForward = this.shouldMoveForward(aWidgetId, aPosition); this.adjustWidgets(aWidgetId, moveForward); } }, - onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) { + onWidgetMoved(aWidgetId, aArea, aOldPosition, aNewPosition) { if (aArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); let moveForward = this.shouldMoveForward(aWidgetId, aNewPosition); this.adjustWidgets(aWidgetId, moveForward); } }, - onWidgetRemoved: function(aWidgetId, aPrevArea) { + onWidgetRemoved(aWidgetId, aPrevArea) { if (aPrevArea == gPanel) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); this.adjustWidgets(aWidgetId, false); } }, - onWidgetReset: function(aWidgetId) { + onWidgetReset(aWidgetId) { gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); }, // Listener to keep abreast of any new nodes. We use the DOM one because // we need access to the actual node's classlist, so we can't use the ones above. // Furthermore, onWidgetCreated only fires for API-based widgets, not for XUL ones. - onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer) { + onWidgetAfterDOMChange(aNode, aNextNode, aContainer) { if (!gSeenWidgets.has(aNode.id)) { if (aNode.classList.contains(CustomizableUI.WIDE_PANEL_CLASS)) { gWideWidgets.add(aNode.id); @@ -57,11 +57,11 @@ var PanelWideWidgetTracker = { } }, // When widgets get destroyed, we remove them from our sets of stuff we care about: - onWidgetDestroyed: function(aWidgetId) { + onWidgetDestroyed(aWidgetId) { gSeenWidgets.delete(aWidgetId); gWideWidgets.delete(aWidgetId); }, - shouldMoveForward: function(aWidgetId, aPosition) { + shouldMoveForward(aWidgetId, aPosition) { let currentWidgetAtPosition = gPanelPlacements[aPosition + 1]; let rv = gWideWidgets.has(currentWidgetAtPosition) && !gWideWidgets.has(aWidgetId); // We might now think we can move forward, but for that we need at least 2 more small @@ -83,7 +83,7 @@ var PanelWideWidgetTracker = { } return rv; }, - adjustWidgets: function(aWidgetId, aMoveForwards) { + adjustWidgets(aWidgetId, aMoveForwards) { if (this.adjusting) { return; } @@ -104,7 +104,7 @@ var PanelWideWidgetTracker = { // This function is called whenever an item gets moved in the menu panel. It // adjusts the position of widgets within the panel to prevent "gaps" between // wide widgets that could be filled up with single column widgets - adjustPosition: function(aWidgetId, aMoveForwards) { + adjustPosition(aWidgetId, aMoveForwards) { // Make sure that there are n % columns = 0 narrow buttons before the widget. let placementIndex = gPanelPlacements.indexOf(aWidgetId); let prevSiblingCount = 0; @@ -144,7 +144,7 @@ var PanelWideWidgetTracker = { * "public-only" if it's not shown in private windows * "real" if it does exist and is shown even in private windows */ - checkWidgetStatus: function(aWidgetId) { + checkWidgetStatus(aWidgetId) { let widgetWrapper = CustomizableUI.getWidget(aWidgetId); // This widget might not actually exist: if (!widgetWrapper) { @@ -164,7 +164,7 @@ var PanelWideWidgetTracker = { return "real"; }, - init: function() { + init() { // Initialize our local placements copy and register the listener gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel); CustomizableUI.addListener(this); diff --git a/browser/components/customizableui/ScrollbarSampler.jsm b/browser/components/customizableui/ScrollbarSampler.jsm index 44736e4c4e08..5a2bfd3e07d7 100644 --- a/browser/components/customizableui/ScrollbarSampler.jsm +++ b/browser/components/customizableui/ScrollbarSampler.jsm @@ -14,7 +14,7 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm"); var gSystemScrollbarWidth = null; this.ScrollbarSampler = { - getSystemScrollbarWidth: function() { + getSystemScrollbarWidth() { if (gSystemScrollbarWidth !== null) { return Promise.resolve(gSystemScrollbarWidth); } @@ -27,11 +27,11 @@ this.ScrollbarSampler = { }); }, - resetSystemScrollbarWidth: function() { + resetSystemScrollbarWidth() { gSystemScrollbarWidth = null; }, - _sampleSystemScrollbarWidth: function() { + _sampleSystemScrollbarWidth() { let hwin = Services.appShell.hiddenDOMWindow; let hdoc = hwin.document.documentElement; let iframe = hwin.document.createElementNS("http://www.w3.org/1999/xhtml", diff --git a/browser/components/customizableui/content/panelUI.js b/browser/components/customizableui/content/panelUI.js index 112e2e72f935..173f788b0011 100644 --- a/browser/components/customizableui/content/panelUI.js +++ b/browser/components/customizableui/content/panelUI.js @@ -37,7 +37,7 @@ const PanelUI = { }, _initialized: false, - init: function() { + init() { for (let [k, v] of Object.entries(this.kElements)) { // Need to do fresh let-bindings per iteration let getKey = k; @@ -57,13 +57,13 @@ const PanelUI = { }, _eventListenersAdded: false, - _ensureEventListenersAdded: function() { + _ensureEventListenersAdded() { if (this._eventListenersAdded) return; this._addEventListeners(); }, - _addEventListeners: function() { + _addEventListeners() { for (let event of this.kEvents) { this.panel.addEventListener(event, this); } @@ -72,7 +72,7 @@ const PanelUI = { this._eventListenersAdded = true; }, - uninit: function() { + uninit() { for (let event of this.kEvents) { this.panel.removeEventListener(event, this); } @@ -92,7 +92,7 @@ const PanelUI = { * @param aMainView * The mainView node to put back into place. */ - setMainView: function(aMainView) { + setMainView(aMainView) { this._ensureEventListenersAdded(); this.multiView.setMainView(aMainView); }, @@ -103,7 +103,7 @@ const PanelUI = { * * @param aEvent the event that triggers the toggle. */ - toggle: function(aEvent) { + toggle(aEvent) { // Don't show the panel if the window is in customization mode, // since this button doubles as an exit path for the user in this case. if (document.documentElement.hasAttribute("customizing")) { @@ -124,7 +124,7 @@ const PanelUI = { * * @param aEvent the event (if any) that triggers showing the menu. */ - show: function(aEvent) { + show(aEvent) { return new Promise(resolve => { this.ensureReady().then(() => { if (this.panel.state == "open" || @@ -170,7 +170,7 @@ const PanelUI = { /** * If the menu panel is being shown, hide it. */ - hide: function() { + hide() { if (document.documentElement.hasAttribute("customizing")) { return; } @@ -178,7 +178,7 @@ const PanelUI = { this.panel.hidePopup(); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { // Ignore context menus and menu button menus showing and hiding: if (aEvent.type.startsWith("popup") && aEvent.target != this.panel) { @@ -221,7 +221,7 @@ const PanelUI = { * * @return a Promise that resolves once the panel is ready to roll. */ - ensureReady: function(aCustomizing = false) { + ensureReady(aCustomizing = false) { if (this._readyPromise) { return this._readyPromise; } @@ -282,7 +282,7 @@ const PanelUI = { * Switch the panel to the main view if it's not already * in that view. */ - showMainView: function() { + showMainView() { this._ensureEventListenersAdded(); this.multiView.showMainView(); }, @@ -291,7 +291,7 @@ const PanelUI = { * Switch the panel to the help view if it's not already * in that view. */ - showHelpView: function(aAnchor) { + showHelpView(aAnchor) { this._ensureEventListenersAdded(); this.multiView.showSubView("PanelUI-helpView", aAnchor); }, @@ -410,15 +410,15 @@ const PanelUI = { * affect the hiding/showing animations of single-subview panels (tempPanel * in the showSubView method). */ - disableSingleSubviewPanelAnimations: function() { + disableSingleSubviewPanelAnimations() { this._disableAnimations = true; }, - enableSingleSubviewPanelAnimations: function() { + enableSingleSubviewPanelAnimations() { this._disableAnimations = false; }, - onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer, aWasRemoval) { + onWidgetAfterDOMChange(aNode, aNextNode, aContainer, aWasRemoval) { if (aContainer != this.contents) { return; } @@ -427,7 +427,7 @@ const PanelUI = { } }, - onWidgetBeforeDOMChange: function(aNode, aNextNode, aContainer, aIsRemoval) { + onWidgetBeforeDOMChange(aNode, aNextNode, aContainer, aIsRemoval) { if (aContainer != this.contents) { return; } @@ -442,7 +442,7 @@ const PanelUI = { * Signal that we're about to make a lot of changes to the contents of the * panels all at once. For performance, we ignore the mutations. */ - beginBatchUpdate: function() { + beginBatchUpdate() { this._ensureEventListenersAdded(); this.multiView.ignoreMutations = true; }, @@ -452,12 +452,12 @@ const PanelUI = { * attention to mutations. This automatically synchronizes the multiview * container with whichever view is displayed if the panel is open. */ - endBatchUpdate: function(aReason) { + endBatchUpdate(aReason) { this._ensureEventListenersAdded(); this.multiView.ignoreMutations = false; }, - _adjustLabelsForAutoHyphens: function(aNode) { + _adjustLabelsForAutoHyphens(aNode) { let toolbarButtons = aNode ? [aNode] : this.contents.querySelectorAll(".toolbarbutton-1"); for (let node of toolbarButtons) { @@ -477,12 +477,12 @@ const PanelUI = { * Sets the anchor node into the open or closed state, depending * on the state of the panel. */ - _updatePanelButton: function() { + _updatePanelButton() { this.menuButton.open = this.panel.state == "open" || this.panel.state == "showing"; }, - _onHelpViewShow: function(aEvent) { + _onHelpViewShow(aEvent) { // Call global menu setup function buildHelpMenu(); @@ -515,7 +515,7 @@ const PanelUI = { items.appendChild(fragment); }, - _updateQuitTooltip: function() { + _updateQuitTooltip() { if (AppConstants.platform == "win") { return; } @@ -535,7 +535,7 @@ const PanelUI = { }, _overlayScrollListenerBoundFn: null, - _overlayScrollListener: function(aMQL) { + _overlayScrollListener(aMQL) { ScrollbarSampler.resetSystemScrollbarWidth(); this._scrollWidth = null; }, diff --git a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js b/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js index 22fbb5c0c227..5545c3fd0e9c 100644 --- a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js +++ b/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js @@ -12,7 +12,7 @@ function simulateItemDragAndEnd(aToDrag, aTarget) { var [result, dataTransfer] = EventUtils.synthesizeDragOver(aToDrag.parentNode, aTarget); EventUtils.synthesizeDropAfterDragOver(result, dataTransfer, aTarget); // Send dragend to move dragging item back to initial place. - EventUtils.sendDragEvent({ type: "dragend", dataTransfer: dataTransfer }, + EventUtils.sendDragEvent({ type: "dragend", dataTransfer }, aToDrag.parentNode); } finally { ds.endDragSession(true); diff --git a/browser/components/customizableui/test/browser_877006_missing_view.js b/browser/components/customizableui/test/browser_877006_missing_view.js index a1495c1feda4..b16775d5bb17 100644 --- a/browser/components/customizableui/test/browser_877006_missing_view.js +++ b/browser/components/customizableui/test/browser_877006_missing_view.js @@ -12,7 +12,7 @@ add_task(function testAddbrokenViewWidget() { type: 'view', viewId: 'idontexist', /* Empty handler so we try to attach it maybe? */ - onViewShowing: function() { + onViewShowing() { } }; diff --git a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js index 61adac9826f3..d19eed775e60 100644 --- a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js +++ b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js @@ -15,7 +15,7 @@ add_task(function*() { for (let i = 0; i < kTestWidgetCount; i++) { let id = kTestWidgetPfx + i; widgetIds.push(id); - let spec = {id: id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i}; + let spec = {id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } for (let i = kTestWidgetCount; i < kTestWidgetCount * 2; i++) { diff --git a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js b/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js index c2006bef048d..45b90d9e7a0a 100644 --- a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js +++ b/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js @@ -14,7 +14,7 @@ add_task(function*() { let privateWindow = null; let observerWindowOpened = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { privateWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow); privateWindow.addEventListener("load", function newWindowHandler() { diff --git a/browser/components/customizableui/test/browser_947914_button_newWindow.js b/browser/components/customizableui/test/browser_947914_button_newWindow.js index 47162ee86147..9c3f08c93abe 100644 --- a/browser/components/customizableui/test/browser_947914_button_newWindow.js +++ b/browser/components/customizableui/test/browser_947914_button_newWindow.js @@ -13,7 +13,7 @@ add_task(function*() { let newWindow = null; let observerWindowOpened = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "domwindowopened") { newWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow); newWindow.addEventListener("load", function newWindowHandler() { diff --git a/browser/components/customizableui/test/browser_973641_button_addon.js b/browser/components/customizableui/test/browser_973641_button_addon.js index 796bf3d0ecad..8d7198dc1646 100755 --- a/browser/components/customizableui/test/browser_973641_button_addon.js +++ b/browser/components/customizableui/test/browser_973641_button_addon.js @@ -14,7 +14,7 @@ add_task(function*() { let widgetSpec = { id: kButton, type: 'button', - onClick: function() { + onClick() { gBrowser.selectedTab = gBrowser.addTab("about:addons"); } }; diff --git a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js b/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js index 3bfa8c25d57f..d6ed3c205278 100644 --- a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js +++ b/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js @@ -20,7 +20,7 @@ add_task(function*() { let id = kTestWidgetPrefix + i; widgetIds.push(id); if (testWidgetExists[i]) { - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } } @@ -57,7 +57,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -106,7 +106,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -156,7 +156,7 @@ add_task(function*() { for (let i = 0; i < 5; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -207,7 +207,7 @@ add_task(function*() { for (let i = 5; i >= 0; i--) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar", 0); } @@ -215,7 +215,7 @@ add_task(function*() { for (let i = 10; i < 15; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); CustomizableUI.addWidgetToArea(id, "nav-bar"); } @@ -269,8 +269,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated(node) { node.style.minWidth = "200px"; if (id == (kTestWidgetPrefix + nonOverflowableId)) { node.setAttribute("overflows", false); @@ -325,8 +325,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { node.style.minWidth = "100px"; }}; + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated(node) { node.style.minWidth = "100px"; }}; info("Creating: " + id); CustomizableUI.createWidget(spec); } @@ -374,8 +374,8 @@ add_task(function*() { if (i != missingId) { // Setting min-width to make the overflow state not depend on styling of the button and/or // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { node.style.minWidth = "200px"; }}; + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i, + onCreated(node) { node.style.minWidth = "200px"; }}; info("Creating: " + id); CustomizableUI.createWidget(spec); } diff --git a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js b/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js index 15197ac86f12..fafbc93592c1 100644 --- a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js +++ b/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js @@ -14,7 +14,7 @@ add_task(function* addOverflowingToolbar() { for (let i = 0; i < 10; i++) { let id = kTestWidgetPrefix + i; widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; + let spec = {id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; CustomizableUI.createWidget(spec); } diff --git a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js index 9a7227a47b6b..1f27e604ae3d 100644 --- a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js +++ b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js @@ -13,7 +13,7 @@ add_task(function* testAddOnBeforeCreatedWidget() { id: kWidgetId, type: 'view', viewId: kWidgetId + 'idontexistyet', - onBeforeCreated: function(doc) { + onBeforeCreated(doc) { let view = doc.createElement("panelview"); view.id = kWidgetId + 'idontexistyet'; let label = doc.createElement("label"); @@ -23,7 +23,7 @@ add_task(function* testAddOnBeforeCreatedWidget() { document.getElementById("PanelUI-multiView").appendChild(view); onBeforeCreatedCalled = true; }, - onViewShowing: function() { + onViewShowing() { viewShownDeferred.resolve(); } }; diff --git a/browser/components/customizableui/test/browser_987492_window_api.js b/browser/components/customizableui/test/browser_987492_window_api.js index 104a14ba6d98..2fccd1b5b82f 100644 --- a/browser/components/customizableui/test/browser_987492_window_api.js +++ b/browser/components/customizableui/test/browser_987492_window_api.js @@ -16,7 +16,7 @@ add_task(function* testOneWindow() { add_task(function* testOpenCloseWindow() { let newWindow = null; let openListener = { - onWindowOpened: function(window) { + onWindowOpened(window) { newWindow = window; } } @@ -39,7 +39,7 @@ add_task(function* testOpenCloseWindow() { let closedWindow = null; let closeListener = { - onWindowClosed: function(window) { + onWindowClosed(window) { closedWindow = window; } } diff --git a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js b/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js index 4d292a929c67..a8790f539869 100644 --- a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js +++ b/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js @@ -65,7 +65,7 @@ add_task(function*() { otherTB.setAttribute("customizable", "true"); let wasInformedCorrectlyOfAreaAppearing = false; let listener = { - onAreaNodeRegistered: function(aArea, aNode) { + onAreaNodeRegistered(aArea, aNode) { if (aNode == otherTB) { wasInformedCorrectlyOfAreaAppearing = true; } @@ -99,14 +99,14 @@ add_task(function*() { // (and therefore onAreaNodeRegistered) one, causing the test to fail. let windowCloseDeferred = Promise.defer(); listener = { - onAreaNodeUnregistered: function(aArea, aNode, aReason) { + onAreaNodeUnregistered(aArea, aNode, aReason) { if (aArea == TOOLBARID) { is(aNode, otherTB, "Should be informed about other toolbar"); is(aReason, CustomizableUI.REASON_WINDOW_CLOSED, "Reason should be correct."); wasInformedCorrectlyOfAreaDisappearing = (aReason === CustomizableUI.REASON_WINDOW_CLOSED); } }, - onWindowClosed: function(aWindow) { + onWindowClosed(aWindow) { if (aWindow == otherWin) { windowCloseDeferred.resolve(aWindow); } else { @@ -133,7 +133,7 @@ add_task(function*() { CustomizableUI.removeListener(listener); wasInformedCorrectlyOfAreaDisappearing = false; listener = { - onAreaNodeUnregistered: function(aArea, aNode, aReason) { + onAreaNodeUnregistered(aArea, aNode, aReason) { if (aArea == TOOLBARID) { is(aNode, toolbar, "Should be informed about this window's toolbar"); is(aReason, CustomizableUI.REASON_AREA_UNREGISTERED, "Reason for final removal should be correct."); diff --git a/browser/components/migration/360seProfileMigrator.js b/browser/components/migration/360seProfileMigrator.js index 42347d542a68..83e2880b132b 100644 --- a/browser/components/migration/360seProfileMigrator.js +++ b/browser/components/migration/360seProfileMigrator.js @@ -209,7 +209,7 @@ function Qihoo360seProfileMigrator() { Qihoo360seProfileMigrator.prototype = Object.create(MigratorPrototype); Object.defineProperty(Qihoo360seProfileMigrator.prototype, "sourceProfiles", { - get: function() { + get() { if ("__sourceProfiles" in this) return this.__sourceProfiles; diff --git a/browser/components/migration/ChromeProfileMigrator.js b/browser/components/migration/ChromeProfileMigrator.js index 2446f713ca20..ee99db3ca626 100644 --- a/browser/components/migration/ChromeProfileMigrator.js +++ b/browser/components/migration/ChromeProfileMigrator.js @@ -246,7 +246,7 @@ function GetBookmarksResource(aProfileFolder) { return { type: MigrationUtils.resourceTypes.BOOKMARKS, - migrate: function(aCallback) { + migrate(aCallback) { return Task.spawn(function* () { let gotErrors = false; let errorGatherer = function() { gotErrors = true }; @@ -341,12 +341,12 @@ function GetHistoryResource(aProfileFolder) { yield new Promise((resolve, reject) => { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult: function() { + handleResult() { // Importing any entry is considered a successful import. this._success = true; }, - handleError: function() {}, - handleCompletion: function() { + handleError() {}, + handleCompletion() { if (this._success) { resolve(); } else { diff --git a/browser/components/migration/ESEDBReader.jsm b/browser/components/migration/ESEDBReader.jsm index a01bee53f73b..ad842356b338 100644 --- a/browser/components/migration/ESEDBReader.jsm +++ b/browser/components/migration/ESEDBReader.jsm @@ -354,7 +354,7 @@ ESEDB.prototype = { return true; }, - tableItems: function*(tableName, columns) { + *tableItems(tableName, columns) { if (!this._opened) { throw new Error("The database was closed!"); } diff --git a/browser/components/migration/EdgeProfileMigrator.js b/browser/components/migration/EdgeProfileMigrator.js index 189932bed8aa..f2d83d433348 100644 --- a/browser/components/migration/EdgeProfileMigrator.js +++ b/browser/components/migration/EdgeProfileMigrator.js @@ -107,7 +107,7 @@ EdgeTypedURLMigrator.prototype = { return this._typedURLs.size > 0; }, - migrate: function(aCallback) { + migrate(aCallback) { let typedURLs = this._typedURLs; let places = []; for (let [urlString, time] of typedURLs) { @@ -140,12 +140,12 @@ EdgeTypedURLMigrator.prototype = { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult: function() { + handleResult() { // Importing any entry is considered a successful import. this._success = true; }, - handleError: function() {}, - handleCompletion: function() { + handleError() {}, + handleCompletion() { aCallback(this._success); } }); diff --git a/browser/components/migration/FirefoxProfileMigrator.js b/browser/components/migration/FirefoxProfileMigrator.js index 526c82938f6d..485719ae90bf 100644 --- a/browser/components/migration/FirefoxProfileMigrator.js +++ b/browser/components/migration/FirefoxProfileMigrator.js @@ -62,7 +62,7 @@ function sorter(a, b) { } Object.defineProperty(FirefoxProfileMigrator.prototype, "sourceProfiles", { - get: function() { + get() { return [...this._getAllProfiles().keys()].map(x => ({id: x, name: x})).sort(sorter); } }); @@ -117,7 +117,7 @@ FirefoxProfileMigrator.prototype._getResourcesInternal = function(sourceProfileD } return { type: aMigrationType, - migrate: function(aCallback) { + migrate(aCallback) { for (let file of files) { file.copyTo(currentProfileDir, ""); } @@ -143,7 +143,7 @@ FirefoxProfileMigrator.prototype._getResourcesInternal = function(sourceProfileD if (sessionFile) { session = { type: types.SESSION, - migrate: function(aCallback) { + migrate(aCallback) { sessionCheckpoints.copyTo(currentProfileDir, "sessionCheckpoints.json"); let newSessionFile = currentProfileDir.clone(); newSessionFile.append("sessionstore.js"); diff --git a/browser/components/migration/IEProfileMigrator.js b/browser/components/migration/IEProfileMigrator.js index b1ff92a69f65..97582208358a 100644 --- a/browser/components/migration/IEProfileMigrator.js +++ b/browser/components/migration/IEProfileMigrator.js @@ -76,9 +76,9 @@ History.prototype = { let lastVisitTime = entry.get("time") || (Date.now() * 1000); places.push( - { uri: uri, - title: title, - visits: [{ transitionType: transitionType, + { uri, + title, + visits: [{ transitionType, visitDate: lastVisitTime }] } ); @@ -92,12 +92,12 @@ History.prototype = { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult: function() { + handleResult() { // Importing any entry is considered a successful import. this._success = true; }, - handleError: function() {}, - handleCompletion: function() { + handleError() {}, + handleCompletion() { aCallback(this._success); } }); @@ -320,8 +320,8 @@ IE7FormPasswords.prototype = { fileTimeToSecondsSinceEpoch(currentLoginItem.hiDateTime, currentLoginItem.loDateTime) * 1000; let currentResult = { - creation: creation, - url: url, + creation, + url, }; // The username is UTF-16 and null-terminated. currentResult.username = diff --git a/browser/components/migration/MSMigrationUtils.jsm b/browser/components/migration/MSMigrationUtils.jsm index c36ef21bffdb..989e6bb541be 100644 --- a/browser/components/migration/MSMigrationUtils.jsm +++ b/browser/components/migration/MSMigrationUtils.jsm @@ -874,7 +874,7 @@ WindowsVaultFormPasswords.prototype = { var MSMigrationUtils = { MIGRATION_TYPE_IE: 1, MIGRATION_TYPE_EDGE: 2, - CtypesKernelHelpers: CtypesKernelHelpers, + CtypesKernelHelpers, getBookmarksMigrator(migrationType = this.MIGRATION_TYPE_IE) { return new Bookmarks(migrationType); }, diff --git a/browser/components/migration/MigrationUtils.jsm b/browser/components/migration/MigrationUtils.jsm index 8a966960634f..01f607f646a4 100644 --- a/browser/components/migration/MigrationUtils.jsm +++ b/browser/components/migration/MigrationUtils.jsm @@ -295,7 +295,6 @@ this.MigratorPrototype = { } notify("Migration:Started"); for (let [migrationType, itemResources] of resourcesGroupedByItems) { - notify("Migration:ItemBeforeMigrate", migrationType); let itemSuccess = false; diff --git a/browser/components/migration/SafariProfileMigrator.js b/browser/components/migration/SafariProfileMigrator.js index 664eb13beca8..2d782d5a448d 100644 --- a/browser/components/migration/SafariProfileMigrator.js +++ b/browser/components/migration/SafariProfileMigrator.js @@ -220,7 +220,7 @@ History.prototype = { places.push({ uri: NetUtil.newURI(entry.get("")), title: entry.get("title"), visits: [{ transitionType: transType, - visitDate: visitDate }] }); + visitDate }] }); } catch (ex) { // Safari's History file may contain malformed URIs which @@ -232,12 +232,12 @@ History.prototype = { if (places.length > 0) { MigrationUtils.insertVisitsWrapper(places, { _success: false, - handleResult: function() { + handleResult() { // Importing any entry is considered a successful import. this._success = true; }, - handleError: function() {}, - handleCompletion: function() { + handleError() {}, + handleCompletion() { aCallback(this._success); } }); diff --git a/browser/components/migration/content/migration.js b/browser/components/migration/content/migration.js index 3691232069da..908c9b965482 100644 --- a/browser/components/migration/content/migration.js +++ b/browser/components/migration/content/migration.js @@ -22,7 +22,7 @@ var MigrationWizard = { /* exported MigrationWizard */ _migrator: null, _autoMigrate: null, - init: function() + init() { let os = Services.obs; os.addObserver(this, "Migration:Started", false); @@ -58,7 +58,7 @@ var MigrationWizard = { /* exported MigrationWizard */ this.onImportSourcePageShow(); }, - uninit: function() + uninit() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); @@ -71,7 +71,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 1 - Import Source - onImportSourcePageShow: function() + onImportSourcePageShow() { // Show warning message to close the selected browser when needed function toggleCloseBrowserWarning() { @@ -137,7 +137,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportSourcePageAdvanced: function() + onImportSourcePageAdvanced() { var newSource = document.getElementById("importSourceGroup").selectedItem.id; @@ -183,7 +183,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 2 - [Profile Selection] - onSelectProfilePageShow: function() + onSelectProfilePageShow() { // Disabling this for now, since we ask about import sources in automigration // too and don't want to disable the back button @@ -210,7 +210,7 @@ var MigrationWizard = { /* exported MigrationWizard */ profiles.selectedItem = this._selectedProfile ? document.getElementById(this._selectedProfile.id) : profiles.firstChild; }, - onSelectProfilePageRewound: function() + onSelectProfilePageRewound() { var profiles = document.getElementById("profiles"); this._selectedProfile = this._migrator.sourceProfiles.find( @@ -218,7 +218,7 @@ var MigrationWizard = { /* exported MigrationWizard */ ) || null; }, - onSelectProfilePageAdvanced: function() + onSelectProfilePageAdvanced() { var profiles = document.getElementById("profiles"); this._selectedProfile = this._migrator.sourceProfiles.find( @@ -231,7 +231,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 3 - ImportItems - onImportItemsPageShow: function() + onImportItemsPageShow() { var dataSources = document.getElementById("dataSources"); while (dataSources.hasChildNodes()) @@ -252,13 +252,13 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportItemsPageRewound: function() + onImportItemsPageRewound() { this._wiz.canAdvance = true; this.onImportItemsPageAdvanced(); }, - onImportItemsPageAdvanced: function() + onImportItemsPageAdvanced() { var dataSources = document.getElementById("dataSources"); this._itemsFlags = 0; @@ -269,7 +269,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onImportItemCommand: function() + onImportItemCommand() { var items = document.getElementById("dataSources"); var checkboxes = items.getElementsByTagName("checkbox"); @@ -286,7 +286,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 4 - Home Page Selection - onHomePageMigrationPageShow: function() + onHomePageMigrationPageShow() { // only want this on the first run if (!this._autoMigrate) { @@ -338,7 +338,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onHomePageMigrationPageAdvanced: function() + onHomePageMigrationPageAdvanced() { // we might not have a selectedItem if we're in fallback mode try { @@ -349,7 +349,7 @@ var MigrationWizard = { /* exported MigrationWizard */ }, // 5 - Migrating - onMigratingPageShow: function() + onMigratingPageShow() { this._wiz.getButton("cancel").disabled = true; this._wiz.canRewind = false; @@ -363,7 +363,7 @@ var MigrationWizard = { /* exported MigrationWizard */ setTimeout(() => this.onMigratingMigrate(), 0); }, - onMigratingMigrate: function() + onMigratingMigrate() { this._migrator.migrate(this._itemsFlags, this._autoMigrate, this._selectedProfile); @@ -383,7 +383,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - _listItems: function(aID) + _listItems(aID) { var items = document.getElementById(aID); while (items.hasChildNodes()) @@ -409,7 +409,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { var label; switch (aTopic) { @@ -514,7 +514,7 @@ var MigrationWizard = { /* exported MigrationWizard */ } }, - onDonePageShow: function() + onDonePageShow() { this._wiz.getButton("cancel").disabled = true; this._wiz.canRewind = false; diff --git a/browser/components/migration/tests/unit/test_automigration.js b/browser/components/migration/tests/unit/test_automigration.js index 34e90d00d900..3a19dcbc3f62 100644 --- a/browser/components/migration/tests/unit/test_automigration.js +++ b/browser/components/migration/tests/unit/test_automigration.js @@ -215,7 +215,7 @@ add_task(function* checkUndoRemoval() { let frecencyUpdatePromise = new Promise(resolve => { let expectedChanges = 2; let observer = { - onFrecencyChanged: function() { + onFrecencyChanged() { if (!--expectedChanges) { PlacesUtils.history.removeObserver(observer); resolve(); @@ -561,31 +561,31 @@ add_task(function* checkUndoVisitsState() { ]); let wrongMethodDeferred = PromiseUtils.defer(); let observer = { - onBeginUpdateBatch: function() {}, - onEndUpdateBatch: function() {}, - onVisit: function(uri) { + onBeginUpdateBatch() {}, + onEndUpdateBatch() {}, + onVisit(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onVisit " + uri.spec)); }, - onTitleChanged: function(uri) { + onTitleChanged(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onTitleChanged " + uri.spec)); }, - onClearHistory: function() { + onClearHistory() { wrongMethodDeferred.reject("Unexpected call to onClearHistory"); }, - onPageChanged: function(uri) { + onPageChanged(uri) { wrongMethodDeferred.reject(new Error("Unexpected call to onPageChanged " + uri.spec)); }, - onFrecencyChanged: function(aURI) { + onFrecencyChanged(aURI) { do_print("frecency change"); Assert.ok(frecencyChangesExpected.has(aURI.spec), "Should be expecting frecency change for " + aURI.spec); frecencyChangesExpected.get(aURI.spec).resolve(); }, - onManyFrecenciesChanged: function() { + onManyFrecenciesChanged() { do_print("Many frecencies changed"); wrongMethodDeferred.reject(new Error("This test can't deal with onManyFrecenciesChanged to be called")); }, - onDeleteURI: function(aURI) { + onDeleteURI(aURI) { do_print("delete uri"); Assert.ok(uriDeletedExpected.has(aURI.spec), "Should be expecting uri deletion for " + aURI.spec); diff --git a/browser/components/newtab/NewTabURL.jsm b/browser/components/newtab/NewTabURL.jsm index 5000eae2e9ae..9c8b78dd571a 100644 --- a/browser/components/newtab/NewTabURL.jsm +++ b/browser/components/newtab/NewTabURL.jsm @@ -18,7 +18,7 @@ XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", this.NewTabURL = { - get: function() { + get() { return aboutNewTabService.newTabURL; }, @@ -26,11 +26,11 @@ this.NewTabURL = { return aboutNewTabService.overridden; }, - override: function(newURL) { + override(newURL) { aboutNewTabService.newTabURL = newURL; }, - reset: function() { + reset() { aboutNewTabService.resetNewTabURL(); } }; diff --git a/browser/components/newtab/NewTabWebChannel.jsm b/browser/components/newtab/NewTabWebChannel.jsm index 28614ebb7883..8a6973f9e603 100644 --- a/browser/components/newtab/NewTabWebChannel.jsm +++ b/browser/components/newtab/NewTabWebChannel.jsm @@ -188,7 +188,7 @@ NewTabWebChannelImpl.prototype = { try { let msg = JSON.parse(message); - this.emit(msg.type, {data: msg.data, target: target}); + this.emit(msg.type, {data: msg.data, target}); } catch (err) { Cu.reportError(err); } diff --git a/browser/components/newtab/PlacesProvider.jsm b/browser/components/newtab/PlacesProvider.jsm index 2e26729c6435..63e17b88deee 100644 --- a/browser/components/newtab/PlacesProvider.jsm +++ b/browser/components/newtab/PlacesProvider.jsm @@ -248,6 +248,6 @@ Links.prototype = { const gLinks = new Links(); // jshint ignore:line let PlacesProvider = { - LinkChecker: LinkChecker, + LinkChecker, links: gLinks, }; diff --git a/browser/components/nsBrowserGlue.js b/browser/components/nsBrowserGlue.js index f06528712477..255b39c279e1 100644 --- a/browser/components/nsBrowserGlue.js +++ b/browser/components/nsBrowserGlue.js @@ -543,7 +543,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getFormattedString("addonwatch.disable.label", [addon.name]), accessKey: "", // workaround for bug 1192901 - callback: function() { + callback() { done(STATE_USER_PICKED_DISABLE); addon.userDisabled = true; if (addon.pendingOperations == addon.PENDING_NONE) { @@ -554,7 +554,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getFormattedString("addonwatch.restart.label", [brandShortName]), accessKey: win.gNavigatorBundle.getString("addonwatch.restart.accesskey"), - callback: function() { + callback() { let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"] .getService(Ci.nsIAppStartup); appStartup.quit(appStartup.eForceQuit | appStartup.eRestart); @@ -569,7 +569,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("addonwatch.ignoreSession.label"), accessKey: win.gNavigatorBundle.getString("addonwatch.ignoreSession.accesskey"), - callback: function() { + callback() { done(STATE_USER_PICKED_IGNORE_FOR_NOW); AddonWatcher.ignoreAddonForSession(addonId); } @@ -577,7 +577,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("addonwatch.ignorePerm.label"), accessKey: win.gNavigatorBundle.getString("addonwatch.ignorePerm.accesskey"), - callback: function() { + callback() { done(STATE_USER_PICKED_IGNORE_FOREVER); AddonWatcher.ignoreAddonPermanently(addonId); } @@ -672,7 +672,7 @@ BrowserGlue.prototype = { Services.obs.notifyObservers(null, "browser-ui-startup-complete", ""); }, - _checkForOldBuildUpdates: function() { + _checkForOldBuildUpdates() { // check for update if our build is old if (AppConstants.MOZ_UPDATER && Services.prefs.getBoolPref("app.update.enabled") && @@ -724,7 +724,7 @@ BrowserGlue.prototype = { } }, - _trackSlowStartup: function() { + _trackSlowStartup() { if (Services.startup.interrupted || Services.prefs.getBoolPref("browser.slowStartup.notificationDisabled")) return; @@ -767,7 +767,7 @@ BrowserGlue.prototype = { return (Date.now() - profileDate) / ONE_DAY; }), - _showSlowStartupNotification: function(profileAge) { + _showSlowStartupNotification(profileAge) { if (profileAge < 90) // 3 months return; @@ -782,14 +782,14 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("slowStartup.helpButton.label"), accessKey: win.gNavigatorBundle.getString("slowStartup.helpButton.accesskey"), - callback: function() { + callback() { win.openUILinkIn("https://support.mozilla.org/kb/reset-firefox-easily-fix-most-problems", "tab"); } }, { label: win.gNavigatorBundle.getString("slowStartup.disableNotificationButton.label"), accessKey: win.gNavigatorBundle.getString("slowStartup.disableNotificationButton.accesskey"), - callback: function() { + callback() { Services.prefs.setBoolPref("browser.slowStartup.notificationDisabled", true); } } @@ -808,7 +808,7 @@ BrowserGlue.prototype = { * String of either "unused" or "uninstall", specifying the reason * why a profile reset is offered. */ - _resetProfileNotification: function(reason) { + _resetProfileNotification(reason) { let win = RecentWindow.getMostRecentBrowserWindow(); if (!win) return; @@ -833,7 +833,7 @@ BrowserGlue.prototype = { { label: resetBundle.formatStringFromName("refreshProfile.resetButton.label", [productName], 1), accessKey: resetBundle.GetStringFromName("refreshProfile.resetButton.accesskey"), - callback: function() { + callback() { ResetProfile.openConfirmationDialog(win); } }, @@ -845,7 +845,7 @@ BrowserGlue.prototype = { nb.PRIORITY_INFO_LOW, buttons); }, - _notifyUnsignedAddonsDisabled: function() { + _notifyUnsignedAddonsDisabled() { let win = RecentWindow.getMostRecentBrowserWindow(); if (!win) return; @@ -855,7 +855,7 @@ BrowserGlue.prototype = { { label: win.gNavigatorBundle.getString("unsignedAddonsDisabled.learnMore.label"), accessKey: win.gNavigatorBundle.getString("unsignedAddonsDisabled.learnMore.accesskey"), - callback: function() { + callback() { win.BrowserOpenAddonsMgr("addons://list/extension?unsigned=true"); } }, @@ -866,7 +866,7 @@ BrowserGlue.prototype = { nb.PRIORITY_WARNING_MEDIUM, buttons); }, - _firstWindowTelemetry: function(aWindow) { + _firstWindowTelemetry(aWindow) { let SCALING_PROBE_NAME = ""; switch (AppConstants.platform) { case "win": @@ -979,7 +979,7 @@ BrowserGlue.prototype = { /** * Application shutdown handler. */ - _onQuitApplicationGranted: function() { + _onQuitApplicationGranted() { // This pref must be set here because SessionStore will use its value // on quit-application. this._setPrefToSaveSession(); @@ -1008,14 +1008,14 @@ BrowserGlue.prototype = { } }, - _initServiceDiscovery: function() { + _initServiceDiscovery() { if (!Services.prefs.getBoolPref("browser.casting.enabled")) { return; } var rokuDevice = { id: "roku:ecp", target: "roku:ecp", - factory: function(aService) { + factory(aService) { Cu.import("resource://gre/modules/RokuApp.jsm"); return new RokuApp(aService); }, @@ -1171,7 +1171,7 @@ BrowserGlue.prototype = { E10SAccessibilityCheck.onWindowsRestored(); }, - _createExtraDefaultProfile: function() { + _createExtraDefaultProfile() { if (!AppConstants.MOZ_DEV_EDITION) { return; } @@ -1391,10 +1391,10 @@ BrowserGlue.prototype = { let buttons = [ { - label: label, + label, accessKey: key, popup: null, - callback: function(aNotificationBar, aButton) { + callback(aNotificationBar, aButton) { win.openUILinkIn(url, "tab"); } } @@ -1694,9 +1694,9 @@ BrowserGlue.prototype = { var buttons = [ { label: buttonText, - accessKey: accessKey, + accessKey, popup: null, - callback: function(aNotificationBar, aButton) { + callback(aNotificationBar, aButton) { win.openUILinkIn(url, "tab"); } } @@ -1709,7 +1709,7 @@ BrowserGlue.prototype = { notification.persistence = -1; // Until user closes it }, - _showSyncStartedDoorhanger: function() { + _showSyncStartedDoorhanger() { let bundle = Services.strings.createBundle("chrome://browser/locale/accounts.properties"); let productName = gBrandBundle.GetStringFromName("brandShortName"); let title = bundle.GetStringFromName("syncStartNotification.title"); @@ -2098,7 +2098,7 @@ BrowserGlue.prototype = { true, url, clickCallback); }), - _hasSystemAlertsService: function() { + _hasSystemAlertsService() { try { return !!Cc["@mozilla.org/system-alerts-service;1"].getService( Ci.nsIAlertsService); @@ -2356,7 +2356,7 @@ BrowserGlue.prototype = { AlertsService.showAlertNotification(null, title, body, true, null, clickCallback); }, - _handleFlashHang: function() { + _handleFlashHang() { ++this._flashHangCount; if (this._flashHangCount < 2) { return; @@ -2388,7 +2388,7 @@ BrowserGlue.prototype = { let buttons = [{ label: win.gNavigatorBundle.getString("flashHang.helpButton.label"), accessKey: win.gNavigatorBundle.getString("flashHang.helpButton.accesskey"), - callback: function() { + callback() { win.openUILinkIn("https://support.mozilla.org/kb/flash-protected-mode-autodisabled", "tab"); } }]; @@ -2509,13 +2509,13 @@ var DefaultBrowserCheck = { _setAsDefaultTimer: null, _setAsDefaultButtonClickStartTime: 0, - closePrompt: function(aNode) { + closePrompt(aNode) { if (this._notification) { this._notification.close(); } }, - setAsDefault: function() { + setAsDefault() { let claimAllTypes = true; let setAsDefaultError = false; if (AppConstants.platform == "win") { @@ -2571,7 +2571,7 @@ var DefaultBrowserCheck = { .add(setAsDefaultError); }, - _createPopup: function(win, notNowStrings, neverStrings) { + _createPopup(win, notNowStrings, neverStrings) { let doc = win.document; let popup = doc.createElement("menupopup"); popup.id = this.OPTIONPOPUP; @@ -2594,7 +2594,7 @@ var DefaultBrowserCheck = { popupset.appendChild(popup); }, - handleEvent: function(event) { + handleEvent(event) { if (event.type == "command") { if (event.target.id == "defaultBrowserNever") { ShellService.shouldCheckDefaultBrowser = false; @@ -2603,7 +2603,7 @@ var DefaultBrowserCheck = { } }, - prompt: function(win) { + prompt(win) { let useNotificationBar = Services.prefs.getBoolPref("browser.defaultbrowser.notificationbar"); let brandBundle = win.document.getElementById("bundle_brand"); @@ -2689,7 +2689,7 @@ var DefaultBrowserCheck = { } }, - _onNotificationEvent: function(eventType) { + _onNotificationEvent(eventType) { if (eventType == "removed") { let doc = this._notification.ownerDocument; let popup = doc.getElementById(this.OPTIONPOPUP); @@ -2705,7 +2705,7 @@ var E10SAccessibilityCheck = { // first window being opening. _wantsPrompt: false, - init: function() { + init() { Services.obs.addObserver(this, "a11y-init-or-shutdown", true); Services.obs.addObserver(this, "quit-application-granted", true); }, @@ -2719,7 +2719,7 @@ var E10SAccessibilityCheck = { return false; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "quit-application-granted": // Tag the profile with a11y load state. We use this in nsAppRunner @@ -2737,7 +2737,7 @@ var E10SAccessibilityCheck = { } }, - onWindowsRestored: function() { + onWindowsRestored() { if (this._wantsPrompt) { this._wantsPrompt = false; this._showE10sAccessibilityWarning(); @@ -2746,7 +2746,7 @@ var E10SAccessibilityCheck = { _warnedAboutAccessibility: false, - _showE10sAccessibilityWarning: function() { + _showE10sAccessibilityWarning() { // We don't prompt about a11y incompat if e10s is off. if (!Services.appinfo.browserTabsRemoteAutostart) { return; @@ -2794,7 +2794,7 @@ var E10SAccessibilityCheck = { let mainAction = { label: win.gNavigatorBundle.getString("e10s.accessibilityNotice.acceptButton.label"), accessKey: win.gNavigatorBundle.getString("e10s.accessibilityNotice.acceptButton.accesskey"), - callback: function() { + callback() { // If the user invoked the button option remove the notification, // otherwise keep the alert icon around in the address bar. notification.remove(); diff --git a/browser/components/originattributes/test/browser/browser_cache.js b/browser/components/originattributes/test/browser/browser_cache.js index 87a0aadd1b42..f1f80d5ccf6a 100644 --- a/browser/components/originattributes/test/browser/browser_cache.js +++ b/browser/components/originattributes/test/browser/browser_cache.js @@ -42,8 +42,8 @@ function cacheDataForContext(loadContextInfo) { let cacheVisitor = { onCacheStorageInfo(num, consumption) {}, onCacheEntryInfo(uri, idEnhance) { - cacheEntries.push({ uri: uri, - idEnhance: idEnhance }); + cacheEntries.push({ uri, + idEnhance }); }, onCacheEntryVisitCompleted() { resolve(cacheEntries); @@ -73,7 +73,7 @@ function observeChannels(onChannel) { // We use a dummy proxy filter to catch all channels, even those that do not // generate an "http-on-modify-request" notification, such as link preconnects. let proxyFilter = { - applyFilter : function(aProxyService, aChannel, aProxy) { + applyFilter(aProxyService, aChannel, aProxy) { // We have the channel; provide it to the callback. onChannel(aChannel); // Pass on aProxy unmodified. @@ -141,7 +141,7 @@ function* doInit(aMode) { function* doTest(aBrowser) { let argObj = { - randomSuffix: randomSuffix, + randomSuffix, urlPrefix: TEST_DOMAIN + TEST_PATH, }; diff --git a/browser/components/places/PlacesUIUtils.jsm b/browser/components/places/PlacesUIUtils.jsm index 45f3226e6ca4..7ab2f9f0391e 100644 --- a/browser/components/places/PlacesUIUtils.jsm +++ b/browser/components/places/PlacesUIUtils.jsm @@ -584,7 +584,7 @@ this.PlacesUIUtils = { * @return a Places Transaction that can be transacted for performing the * move/insert command. */ - getTransactionForData: function(aData, aType, aNewParentGuid, aIndex, aCopy) { + getTransactionForData(aData, aType, aNewParentGuid, aIndex, aCopy) { if (!this.SUPPORTED_FLAVORS.includes(aData.type)) throw new Error(`Unsupported '${aData.type}' data type`); @@ -617,7 +617,7 @@ this.PlacesUIUtils = { let title = aData.type != PlacesUtils.TYPE_UNICODE ? aData.title : aData.uri; return PlacesTransactions.NewBookmark({ uri: NetUtil.newURI(aData.uri) - , title: title + , title , parentGuid: aNewParentGuid , index: aIndex }); }, @@ -797,7 +797,7 @@ this.PlacesUIUtils = { * a node, except the root node of a query. * @return true if the aNode represents a removable entry, false otherwise. */ - canUserRemove: function(aNode) { + canUserRemove(aNode) { let parentNode = aNode.parent; if (!parentNode) { // canUserRemove doesn't accept root nodes. @@ -845,7 +845,7 @@ this.PlacesUIUtils = { * @note livemark "folders" are considered read-only (but see bug 1072833). * @return true if aItemId points to a read-only folder, false otherwise. */ - isContentsReadOnly: function(aNodeOrItemId) { + isContentsReadOnly(aNodeOrItemId) { let itemId; if (typeof(aNodeOrItemId) == "number") { itemId = aNodeOrItemId; @@ -1408,7 +1408,7 @@ this.PlacesUIUtils = { return queryName; }, - shouldShowTabsFromOtherComputersMenuitem: function() { + shouldShowTabsFromOtherComputersMenuitem() { let weaveOK = Weave.Status.checkSetup() != Weave.CLIENT_NOT_CONFIGURED && Weave.Svc.Prefs.get("firstSync", "") != "notReady"; return weaveOK; @@ -1691,7 +1691,7 @@ XPCOMUtils.defineLazyGetter(PlacesUIUtils, "ptm", function() { * boolean value. * @return nsITransaction object. */ - setLoadInSidebar: function(aItemId, aLoadInSidebar) + setLoadInSidebar(aItemId, aLoadInSidebar) { let annoObj = { name: PlacesUIUtils.LOAD_IN_SIDEBAR_ANNO, type: Ci.nsIAnnotationService.TYPE_INT32, @@ -1710,7 +1710,7 @@ XPCOMUtils.defineLazyGetter(PlacesUIUtils, "ptm", function() { * new description. * @return nsITransaction object. */ - editItemDescription: function(aItemId, aDescription) + editItemDescription(aItemId, aDescription) { let annoObj = { name: PlacesUIUtils.DESCRIPTION_ANNO, type: Ci.nsIAnnotationService.TYPE_STRING, diff --git a/browser/components/places/content/bookmarkProperties.js b/browser/components/places/content/bookmarkProperties.js index f1695ffd5af7..42d825ea460d 100644 --- a/browser/components/places/content/bookmarkProperties.js +++ b/browser/components/places/content/bookmarkProperties.js @@ -614,7 +614,7 @@ var BookmarkPropertiesPanel = { let folderGuid = yield PlacesUtils.promiseItemGuid(container); let bm = yield PlacesUtils.bookmarks.fetch({ parentGuid: folderGuid, - index: index + index }); this._itemId = yield PlacesUtils.promiseItemId(bm.guid); diff --git a/browser/components/places/content/browserPlacesViews.js b/browser/components/places/content/browserPlacesViews.js index 3cdb7135ae30..d5170fa7e1c3 100644 --- a/browser/components/places/content/browserPlacesViews.js +++ b/browser/components/places/content/browserPlacesViews.js @@ -135,8 +135,8 @@ PlacesViewBase.prototype = { get selType() { return "single"; }, - selectItems: function() { }, - selectAll: function() { }, + selectItems() { }, + selectAll() { }, get selectedNode() { if (this._contextMenuShown) { @@ -619,12 +619,12 @@ PlacesViewBase.prototype = { } }, - nodeTagsChanged: function() { }, - nodeDateAddedChanged: function() { }, - nodeLastModifiedChanged: function() { }, - nodeKeywordChanged: function() { }, - sortingChanged: function() { }, - batching: function() { }, + nodeTagsChanged() { }, + nodeDateAddedChanged() { }, + nodeLastModifiedChanged() { }, + nodeKeywordChanged() { }, + sortingChanged() { }, + batching() { }, nodeInserted: function PVB_nodeInserted(aParentPlacesNode, aPlacesNode, aIndex) { @@ -1180,7 +1180,7 @@ PlacesToolbar.prototype = { } }, - updateOverflowStatus: function() { + updateOverflowStatus() { if (this._rootElt.scrollLeftMin != this._rootElt.scrollLeftMax) { this._onOverflow(); } else { diff --git a/browser/components/places/content/controller.js b/browser/components/places/content/controller.js index d0e1fab83c32..061ba02e82ee 100644 --- a/browser/components/places/content/controller.js +++ b/browser/components/places/content/controller.js @@ -59,7 +59,7 @@ InsertionPoint.prototype = { return this._index = val; }, - promiseGuid: function() { + promiseGuid() { return PlacesUtils.promiseItemGuid(this.itemId); }, @@ -867,7 +867,7 @@ PlacesController.prototype = { let tag = node.parent.title; if (!tag) tag = PlacesUtils.bookmarks.getItemTitle(tagItemId); - transactions.push(PlacesTransactions.Untag({ uri: uri, tag: tag })); + transactions.push(PlacesTransactions.Untag({ uri, tag })); } else { let txn = new PlacesUntagURITransaction(uri, [tagItemId]); @@ -885,7 +885,7 @@ PlacesController.prototype = { let tag = node.title; let URIs = PlacesUtils.tagging.getURIsForTag(tag); if (PlacesUIUtils.useAsyncTransactions) { - transactions.push(PlacesTransactions.Untag({ tag: tag, uris: URIs })); + transactions.push(PlacesTransactions.Untag({ tag, uris: URIs })); } else { for (var j = 0; j < URIs.length; j++) { @@ -1308,7 +1308,7 @@ PlacesController.prototype = { if (PlacesUIUtils.useAsyncTransactions) { if (ip.isTag) { let uris = items.filter(item => "uri" in item).map(item => NetUtil.newURI(item.uri)); - yield PlacesTransactions.Tag({ uris: uris, tag: ip.tagName }).transact(); + yield PlacesTransactions.Tag({ uris, tag: ip.tagName }).transact(); } else { yield PlacesTransactions.batch(function* () { @@ -1548,7 +1548,7 @@ var PlacesControllerDragHelper = { * A node unwrapped by PlacesUtils.unwrapNodes(). * @return True if the node can be moved, false otherwise. */ - canMoveUnwrappedNode: function(aUnwrappedNode) { + canMoveUnwrappedNode(aUnwrappedNode) { return aUnwrappedNode.id > 0 && !PlacesUtils.isRootItem(aUnwrappedNode.id) && (!aUnwrappedNode.parent || !PlacesUIUtils.isContentsReadOnly(aUnwrappedNode.parent)) && @@ -1637,7 +1637,7 @@ var PlacesControllerDragHelper = { let uri = NetUtil.newURI(unwrapped.uri); let tagItemId = insertionPoint.itemId; if (PlacesUIUtils.useAsyncTransactions) - transactions.push(PlacesTransactions.Tag({ uri: uri, tag: tagName })); + transactions.push(PlacesTransactions.Tag({ uri, tag: tagName })); else transactions.push(new PlacesTagURITransaction(uri, [tagItemId])); } @@ -1679,7 +1679,7 @@ var PlacesControllerDragHelper = { * @param aContainer * The container were we are want to drop */ - disallowInsertion: function(aContainer) { + disallowInsertion(aContainer) { NS_ASSERT(aContainer, "empty container"); // Allow dropping into Tag containers and editable folders. return !PlacesUtils.nodeIsTagQuery(aContainer) && diff --git a/browser/components/places/content/editBookmarkOverlay.js b/browser/components/places/content/editBookmarkOverlay.js index f08b6b36c91d..8df6511d9a73 100644 --- a/browser/components/places/content/editBookmarkOverlay.js +++ b/browser/components/places/content/editBookmarkOverlay.js @@ -393,7 +393,7 @@ var gEditItemOverlay = { this._recentFolders = []; for (let i = 0; i < folderIds.length; i++) { var lastUsed = annos.getItemAnnotation(folderIds[i], LAST_USED_ANNO); - this._recentFolders.push({ folderId: folderIds[i], lastUsed: lastUsed }); + this._recentFolders.push({ folderId: folderIds[i], lastUsed }); } this._recentFolders.sort(function(a, b) { if (b.lastUsed < a.lastUsed) diff --git a/browser/components/places/content/moveBookmarks.js b/browser/components/places/content/moveBookmarks.js index 626b2b904e40..5f4bf0cfc050 100644 --- a/browser/components/places/content/moveBookmarks.js +++ b/browser/components/places/content/moveBookmarks.js @@ -14,7 +14,7 @@ var gMoveBookmarksDialog = { return this._foldersTree; }, - init: function() { + init() { this._nodes = window.arguments[0]; this.foldersTree.place = diff --git a/browser/components/places/content/places.js b/browser/components/places/content/places.js index 7a141354d172..50ebfaf839fa 100644 --- a/browser/components/places/content/places.js +++ b/browser/components/places/content/places.js @@ -32,7 +32,7 @@ var PlacesOrganizer = { "editBMPanel_keywordRow", ], - _initFolderTree: function() { + _initFolderTree() { var leftPaneRoot = PlacesUIUtils.leftPaneFolderId; this._places.place = "place:excludeItems=1&expandQueries=0&folder=" + leftPaneRoot; }, @@ -1250,7 +1250,7 @@ var ContentArea = { let { view, options } = this._specialViews.get(aQueryString); if (typeof view == "function") { view = view(); - this._specialViews.set(aQueryString, { view: view, options: options }); + this._specialViews.set(aQueryString, { view, options }); } return view; } @@ -1356,7 +1356,7 @@ var ContentArea = { return viewOptions; }, - focus: function() { + focus() { this._deck.selectedPanel.focus(); } }; diff --git a/browser/components/places/content/treeView.js b/browser/components/places/content/treeView.js index ece93fd4ff99..81180a7d0b01 100644 --- a/browser/components/places/content/treeView.js +++ b/browser/components/places/content/treeView.js @@ -1135,7 +1135,7 @@ PlacesTreeView.prototype = { this._selection = val; }, - getRowProperties: function() { return ""; }, + getRowProperties() { return ""; }, getCellProperties: function PTV_getCellProperties(aRow, aColumn) { @@ -1217,7 +1217,7 @@ PlacesTreeView.prototype = { return props + " " + properties; }, - getColumnProperties: function(aColumn) { return ""; }, + getColumnProperties(aColumn) { return ""; }, isContainer: function PTV_isContainer(aRow) { // Only leaf nodes aren't listed in the rows array. @@ -1414,7 +1414,7 @@ PlacesTreeView.prototype = { return false; }, - getLevel: function(aRow) { + getLevel(aRow) { return this._getNodeForRow(aRow).indentLevel; }, @@ -1427,8 +1427,8 @@ PlacesTreeView.prototype = { return node.icon; }, - getProgressMode: function(aRow, aColumn) { }, - getCellValue: function(aRow, aColumn) { }, + getProgressMode(aRow, aColumn) { }, + getCellValue(aRow, aColumn) { }, getCellText: function PTV_getCellText(aRow, aColumn) { let node = this._getNodeForRow(aRow); @@ -1717,10 +1717,10 @@ PlacesTreeView.prototype = { } }, - selectionChanged: function() { }, - cycleCell: function(aRow, aColumn) { }, - isSelectable: function(aRow, aColumn) { return false; }, - performAction: function(aAction) { }, - performActionOnRow: function(aAction, aRow) { }, - performActionOnCell: function(aAction, aRow, aColumn) { } + selectionChanged() { }, + cycleCell(aRow, aColumn) { }, + isSelectable(aRow, aColumn) { return false; }, + performAction(aAction) { }, + performActionOnRow(aAction, aRow) { }, + performActionOnCell(aAction, aRow, aColumn) { } }; diff --git a/browser/components/places/tests/browser/browser_423515.js b/browser/components/places/tests/browser/browser_423515.js index 8a67f050cdd5..2eb129cb7783 100644 --- a/browser/components/places/tests/browser/browser_423515.js +++ b/browser/components/places/tests/browser/browser_423515.js @@ -20,11 +20,11 @@ function test() { // add a regular folder, should be moveable tests.push({ - populate: function() { + populate() { this.id = PlacesUtils.bookmarks.createFolder(rootId, "", IDX); }, - validate: function() { + validate() { is(rootNode.childCount, 1, "populate added data to the test root"); is(PlacesControllerDragHelper.canMoveNode(rootNode.getChild(0)), @@ -34,13 +34,13 @@ function test() { // add a regular folder shortcut, should be moveable tests.push({ - populate: function() { + populate() { this.folderId = PlacesUtils.bookmarks.createFolder(rootId, "foo", IDX); this.shortcutId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder=" + this.folderId), IDX, "bar"); }, - validate: function() { + validate() { is(rootNode.childCount, 2, "populated data to the test root"); @@ -62,13 +62,13 @@ function test() { // add a regular query, should be moveable tests.push({ - populate: function() { + populate() { this.bookmarkId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("http://foo.com"), IDX, "foo"); this.queryId = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:terms=foo"), IDX, "bar"); }, - validate: function() { + validate() { is(rootNode.childCount, 2, "populated data to the test root"); @@ -90,14 +90,14 @@ function test() { PlacesUtils.tagsFolderId, PlacesUtils.unfiledBookmarksFolderId, PlacesUtils.toolbarFolderId], shortcuts: {}, - populate: function() { + populate() { for (var i = 0; i < this.folders.length; i++) { var id = this.folders[i]; this.shortcuts[id] = PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder=" + id), IDX, ""); } }, - validate: function() { + validate() { // test toolbar shortcut node is(rootNode.childCount, this.folders.length, "populated data to the test root"); @@ -138,13 +138,13 @@ function test() { // test that a tag container cannot be moved tests.push({ - populate: function() { + populate() { // tag a uri this.uri = makeURI("http://foo.com"); PlacesUtils.tagging.tagURI(this.uri, ["bar"]); registerCleanupFunction(() => PlacesUtils.tagging.untagURI(this.uri, ["bar"])); }, - validate: function() { + validate() { // get tag root var query = PlacesUtils.history.getNewQuery(); var options = PlacesUtils.history.getNewQueryOptions(); diff --git a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js index 78d667e5f169..aaece0b9f5ed 100644 --- a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js +++ b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js @@ -6,9 +6,9 @@ function makeBookmarkFor(url, keyword) { return Promise.all([ PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid, title: "bookmarklet", - url: url }), - PlacesUtils.keywords.insert({url: url, - keyword: keyword}) + url }), + PlacesUtils.keywords.insert({url, + keyword}) ]); } diff --git a/browser/components/places/tests/browser/browser_bookmarksProperties.js b/browser/components/places/tests/browser/browser_bookmarksProperties.js index 7f7d635afe01..63d1c4f874e0 100644 --- a/browser/components/places/tests/browser/browser_bookmarksProperties.js +++ b/browser/components/places/tests/browser/browser_bookmarksProperties.js @@ -63,7 +63,7 @@ gTests.push({ _itemId: null, _cleanShutdown: false, - setup: function(aCallback) { + setup(aCallback) { // Add a bookmark in unsorted bookmarks folder. this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL)); ok(this._itemId > 0, "Correctly added a bookmark"); @@ -75,14 +75,14 @@ gTests.push({ aCallback(); }, - selectNode: function(tree) { + selectNode(tree) { tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]); PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; tree.selectItems([this._itemId]); is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected"); }, - run: function() { + run() { // open tags autocomplete and press enter var tagsField = this.window.document.getElementById("editBMPanel_tagsField"); var self = this; @@ -97,7 +97,7 @@ gTests.push({ }, true); var popupListener = { - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "popuphidden": // Everything worked fine, we can stop observing the window. @@ -137,12 +137,12 @@ gTests.push({ }); }, - finish: function() { + finish() { SidebarUI.hide(); runNextTest(); }, - cleanup: function() { + cleanup() { // Check tags have not changed. var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); is(tags[0], "testTag", "Tag on node has not changed"); @@ -165,7 +165,7 @@ gTests.push({ _itemId: null, _cleanShutdown: false, - setup: function(aCallback) { + setup(aCallback) { // Add a bookmark in unsorted bookmarks folder. this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL)); ok(this._itemId > 0, "Correctly added a bookmark"); @@ -177,14 +177,14 @@ gTests.push({ aCallback(); }, - selectNode: function(tree) { + selectNode(tree) { tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]); PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; tree.selectItems([this._itemId]); is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected"); }, - run: function() { + run() { // open tags autocomplete and press enter var tagsField = this.window.document.getElementById("editBMPanel_tagsField"); var self = this; @@ -199,7 +199,7 @@ gTests.push({ }, true); var popupListener = { - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "popuphidden": // Everything worked fine. @@ -237,12 +237,12 @@ gTests.push({ EventUtils.synthesizeKey("t", {}, this.window); }, - finish: function() { + finish() { SidebarUI.hide(); runNextTest(); }, - cleanup: function() { + cleanup() { // Check tags have not changed. var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); is(tags[0], "testTag", "Tag on node has not changed"); @@ -264,7 +264,7 @@ gTests.push({ historyView: SIDEBAR_HISTORY_BYLASTVISITED_VIEW, window: null, - setup: function(aCallback) { + setup(aCallback) { // Add a visit. PlacesTestUtils.addVisits( {uri: PlacesUtils._uri(TEST_URL), @@ -272,14 +272,14 @@ gTests.push({ ).then(aCallback); }, - selectNode: function(tree) { + selectNode(tree) { var visitNode = tree.view.nodeForTreeIndex(0); tree.selectNode(visitNode); is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected"); is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked"); }, - run: function() { + run() { // Open folder selector. var foldersExpander = this.window.document.getElementById("editBMPanel_foldersExpander"); var folderTree = this.window.document.getElementById("editBMPanel_folderTree"); @@ -315,12 +315,12 @@ gTests.push({ foldersExpander.doCommand(); }, - finish: function() { + finish() { SidebarUI.hide(); runNextTest(); }, - cleanup: function() { + cleanup() { return PlacesTestUtils.clearHistory(); } }); diff --git a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js b/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js index fbc0b02b6387..95aa6f620946 100644 --- a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js +++ b/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js @@ -144,7 +144,7 @@ var gTests = [ { desc: "Drag a folder on toolbar", - run: function() { + run() { // Create a test folder to be dragged. var folderId = PlacesUtils.bookmarks .createFolder(PlacesUtils.toolbarFolderId, @@ -185,7 +185,7 @@ var gTests = [ { desc: "Drag a bookmark on toolbar", - run: function() { + run() { // Create a test bookmark to be dragged. var itemId = PlacesUtils.bookmarks .insertBookmark(PlacesUtils.toolbarFolderId, diff --git a/browser/components/places/tests/browser/browser_library_batch_delete.js b/browser/components/places/tests/browser/browser_library_batch_delete.js index 531ad9139b48..37f843b6a21b 100644 --- a/browser/components/places/tests/browser/browser_library_batch_delete.js +++ b/browser/components/places/tests/browser/browser_library_batch_delete.js @@ -14,10 +14,10 @@ var gLibrary; gTests.push({ desc: "Create and batch remove bookmarks", - run: function() { + run() { let testURI = makeURI(TEST_URL); PlacesUtils.history.runInBatchMode({ - runBatched: function(aUserData) { + runBatched(aUserData) { // Create a folder in unserted and populate it with bookmarks. let folder = PlacesUtils.bookmarks.createFolder( PlacesUtils.unfiledBookmarksFolderId, "deleteme", @@ -67,7 +67,7 @@ gTests.push({ gTests.push({ desc: "Ensure correct selection and functionality in Library", - run: function() { + run() { let PO = gLibrary.PlacesOrganizer; let ContentTree = gLibrary.ContentTree; // Move selection forth and back. diff --git a/browser/components/places/tests/browser/browser_library_downloads.js b/browser/components/places/tests/browser/browser_library_downloads.js index 77005b6fc6b2..3578b8f2b7cf 100644 --- a/browser/components/places/tests/browser/browser_library_downloads.js +++ b/browser/components/places/tests/browser/browser_library_downloads.js @@ -32,11 +32,11 @@ function test() { }, ] PlacesUtils.asyncHistory.updatePlaces(places, { - handleResult: function() {}, - handleError: function() { + handleResult() {}, + handleError() { ok(false, "gHistory.updatePlaces() failed"); }, - handleCompletion: function() { + handleCompletion() { // Make sure Downloads is present. isnot(win.PlacesOrganizer._places.selectedNode, null, "Downloads is present and selected"); diff --git a/browser/components/places/tests/browser/browser_library_infoBox.js b/browser/components/places/tests/browser/browser_library_infoBox.js index 8189438f3c2e..644e216cdc7c 100644 --- a/browser/components/places/tests/browser/browser_library_infoBox.js +++ b/browser/components/places/tests/browser/browser_library_infoBox.js @@ -16,7 +16,7 @@ var gLibrary; gTests.push({ desc: "Bug 430148 - Remove or hide the more/less button in details pane...", - run: function() { + run() { var PO = gLibrary.PlacesOrganizer; let ContentTree = gLibrary.ContentTree; var infoBoxExpanderWrapper = getAndCheckElmtById("infoBoxExpanderWrapper"); diff --git a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js b/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js index 7cea38f20ce8..2c739c04fc34 100644 --- a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js +++ b/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js @@ -64,7 +64,7 @@ function test() { .getItemAnnotation(items[i], PlacesUIUtils.ORGANIZER_QUERY_ANNO); var query = { name: queryName, - itemId: itemId, + itemId, correctTitle: PlacesUtils.bookmarks.getItemTitle(itemId) } switch (queryName) { case "BookmarksToolbar": diff --git a/browser/components/places/tests/browser/browser_library_middleclick.js b/browser/components/places/tests/browser/browser_library_middleclick.js index 0bde80bc0165..bc1605ce5d84 100644 --- a/browser/components/places/tests/browser/browser_library_middleclick.js +++ b/browser/components/places/tests/browser/browser_library_middleclick.js @@ -18,7 +18,7 @@ var gTabsListener = { _loadedURIs: [], _openTabsCount: 0, - handleEvent: function(aEvent) { + handleEvent(aEvent) { if (aEvent.type != "TabOpen") return; @@ -32,7 +32,7 @@ var gTabsListener = { "Tab has been opened in current browser window"); }, - onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, + onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) { var spec = aLocationURI.spec; ok(true, spec); @@ -76,7 +76,7 @@ gTests.push({ URIs: ["about:buildconfig"], _itemId: -1, - setup: function() { + setup() { var bs = PlacesUtils.bookmarks; // Add a new unsorted bookmark. this._itemId = bs.insertBookmark(bs.unfiledBookmarksFolder, @@ -92,11 +92,11 @@ gTests.push({ is(bookmarkNode.uri, this.URIs[0], "Found bookmark in the right pane"); }, - finish: function() { + finish() { setTimeout(runNextTest, 0); }, - cleanup: function() { + cleanup() { PlacesUtils.bookmarks.removeItem(this._itemId); } }); @@ -109,7 +109,7 @@ gTests.push({ URIs: ["about:buildconfig", "about:"], _folderId: -1, - setup: function() { + setup() { var bs = PlacesUtils.bookmarks; // Create a new folder. var folderId = bs.createFolder(bs.unfiledBookmarksFolder, @@ -134,11 +134,11 @@ gTests.push({ is(folderNode.title, "Folder", "Found folder in the right pane"); }, - finish: function() { + finish() { setTimeout(runNextTest, 0); }, - cleanup: function() { + cleanup() { PlacesUtils.bookmarks.removeItem(this._folderId); } }); @@ -152,7 +152,7 @@ gTests.push({ _folderId: -1, _queryId: -1, - setup: function() { + setup() { var bs = PlacesUtils.bookmarks; // Create a new folder. var folderId = bs.createFolder(bs.unfiledBookmarksFolder, @@ -191,11 +191,11 @@ gTests.push({ is(folderNode.title, "Query", "Found query in the right pane"); }, - finish: function() { + finish() { setTimeout(runNextTest, 0); }, - cleanup: function() { + cleanup() { PlacesUtils.bookmarks.removeItem(this._folderId); PlacesUtils.bookmarks.removeItem(this._queryId); } diff --git a/browser/components/places/tests/browser/browser_library_views_liveupdate.js b/browser/components/places/tests/browser/browser_library_views_liveupdate.js index a70e4ef45806..d84c587bb83d 100644 --- a/browser/components/places/tests/browser/browser_library_views_liveupdate.js +++ b/browser/components/places/tests/browser/browser_library_views_liveupdate.js @@ -154,10 +154,10 @@ var bookmarksObserver = { ]), // nsIAnnotationObserver - onItemAnnotationSet: function() {}, - onItemAnnotationRemoved: function() {}, - onPageAnnotationSet: function() {}, - onPageAnnotationRemoved: function() {}, + onItemAnnotationSet() {}, + onItemAnnotationRemoved() {}, + onPageAnnotationSet() {}, + onPageAnnotationRemoved() {}, // nsINavBookmarkObserver onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, aItemType, @@ -191,7 +191,7 @@ var bookmarksObserver = { is(node, null, "Places node not found in left pane"); }, - onItemMoved: function(aItemId, + onItemMoved(aItemId, aOldFolderId, aOldIndex, aNewFolderId, aNewIndex, aItemType) { var node = null; @@ -219,7 +219,7 @@ var bookmarksObserver = { onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {}, onEndUpdateBatch: function PSB_onEndUpdateBatch() {}, - onItemVisited: function() {}, + onItemVisited() {}, onItemChanged: function PSB_onItemChanged(aItemId, aProperty, aIsAnnotationProperty, aNewValue) { if (aProperty == "title") { diff --git a/browser/components/places/tests/browser/browser_sidebarpanels_click.js b/browser/components/places/tests/browser/browser_sidebarpanels_click.js index b1db4e78a02f..48c7fd4e5ef9 100644 --- a/browser/components/places/tests/browser/browser_sidebarpanels_click.js +++ b/browser/components/places/tests/browser/browser_sidebarpanels_click.js @@ -27,7 +27,7 @@ function test() { tests.push({ _itemID: null, - init: function(aCallback) { + init(aCallback) { // Add a bookmark to the Unfiled Bookmarks folder. this._itemID = PlacesUtils.bookmarks.insertBookmark( PlacesUtils.unfiledBookmarksFolderId, PlacesUtils._uri(TEST_URL), @@ -35,12 +35,12 @@ function test() { ); aCallback(); }, - prepare: function() { + prepare() { }, - selectNode: function(tree) { + selectNode(tree) { tree.selectItems([this._itemID]); }, - cleanup: function(aCallback) { + cleanup(aCallback) { PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId); executeSoon(aCallback); }, @@ -50,23 +50,23 @@ function test() { }); tests.push({ - init: function(aCallback) { + init(aCallback) { // Add a history entry. let uri = PlacesUtils._uri(TEST_URL); PlacesTestUtils.addVisits({ - uri: uri, visitDate: Date.now() * 1000, + uri, visitDate: Date.now() * 1000, transition: PlacesUtils.history.TRANSITION_TYPED }).then(aCallback); }, - prepare: function() { + prepare() { sidebar.contentDocument.getElementById("byvisited").doCommand(); }, - selectNode: function(tree) { + selectNode(tree) { tree.selectNode(tree.view.nodeForTreeIndex(0)); is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected"); is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked"); }, - cleanup: function(aCallback) { + cleanup(aCallback) { PlacesTestUtils.clearHistory().then(aCallback); }, sidebarName: HISTORY_SIDEBAR_ID, diff --git a/browser/components/places/tests/browser/browser_views_liveupdate.js b/browser/components/places/tests/browser/browser_views_liveupdate.js index add7984a82d8..a3d8d2ecaba2 100644 --- a/browser/components/places/tests/browser/browser_views_liveupdate.js +++ b/browser/components/places/tests/browser/browser_views_liveupdate.js @@ -192,10 +192,10 @@ var bookmarksObserver = { ]), // nsIAnnotationObserver - onItemAnnotationSet: function() {}, - onItemAnnotationRemoved: function() {}, - onPageAnnotationSet: function() {}, - onPageAnnotationRemoved: function() {}, + onItemAnnotationSet() {}, + onItemAnnotationRemoved() {}, + onPageAnnotationSet() {}, + onPageAnnotationRemoved() {}, // nsINavBookmarkObserver onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, @@ -223,7 +223,7 @@ var bookmarksObserver = { } }, - onItemMoved: function(aItemId, + onItemMoved(aItemId, aOldFolderId, aOldIndex, aNewFolderId, aNewIndex, aItemType) { @@ -242,7 +242,7 @@ var bookmarksObserver = { onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {}, onEndUpdateBatch: function PSB_onEndUpdateBatch() {}, - onItemVisited: function() {}, + onItemVisited() {}, onItemChanged: function PSB_onItemChanged(aItemId, aProperty, aIsAnnotationProperty, aNewValue, diff --git a/browser/components/places/tests/browser/head.js b/browser/components/places/tests/browser/head.js index c6190db4c17c..1bfd71cb59c9 100644 --- a/browser/components/places/tests/browser/head.js +++ b/browser/components/places/tests/browser/head.js @@ -116,9 +116,9 @@ function waitForAsyncUpdates(aCallback, aScope, aArguments) let commit = db.createAsyncStatement("COMMIT"); commit.executeAsync({ - handleResult: function() {}, - handleError: function() {}, - handleCompletion: function(aReason) + handleResult() {}, + handleError() {}, + handleCompletion(aReason) { aCallback.apply(scope, args); } diff --git a/browser/components/places/tests/unit/test_421483.js b/browser/components/places/tests/unit/test_421483.js index a0d1383728e2..ac086a2e3362 100644 --- a/browser/components/places/tests/unit/test_421483.js +++ b/browser/components/places/tests/unit/test_421483.js @@ -79,7 +79,7 @@ add_task(function* move_smart_bookmark_rename_and_restore() { // change title and move into new subfolder yield PlacesUtils.bookmarks.update({ - guid: guid, + guid, parentGuid: subfolder.guid, index: PlacesUtils.bookmarks.DEFAULT_INDEX, title: "new title" diff --git a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js b/browser/components/places/tests/unit/test_PUIU_makeTransaction.js index da8191b0fc23..dcc3645b9119 100644 --- a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js +++ b/browser/components/places/tests/unit/test_PUIU_makeTransaction.js @@ -4,7 +4,7 @@ function waitForBookmarkNotification(aNotification, aCallback, aProperty) { PlacesUtils.bookmarks.addObserver({ - validate: function(aMethodName, aData) + validate(aMethodName, aData) { if (aMethodName == aNotification && (!aProperty || aProperty == aData.property)) { diff --git a/browser/components/places/tests/unit/test_clearHistory_shutdown.js b/browser/components/places/tests/unit/test_clearHistory_shutdown.js index 4bf88b04aa8a..c020bdbd99fb 100644 --- a/browser/components/places/tests/unit/test_clearHistory_shutdown.js +++ b/browser/components/places/tests/unit/test_clearHistory_shutdown.js @@ -133,11 +133,11 @@ function storeCache(aURL, aContent) { return new Promise(resolve => { let storeCacheListener = { - onCacheEntryCheck: function(entry, appcache) { + onCacheEntryCheck(entry, appcache) { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; }, - onCacheEntryAvailable: function(entry, isnew, appcache, status) { + onCacheEntryAvailable(entry, isnew, appcache, status) { do_check_eq(status, Cr.NS_OK); entry.setMetaDataElement("servertype", "0"); @@ -168,7 +168,7 @@ function checkCache(aURL) { return new Promise(resolve => { let checkCacheListener = { - onCacheEntryAvailable: function(entry, isnew, appcache, status) { + onCacheEntryAvailable(entry, isnew, appcache, status) { do_check_eq(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND); resolve(); } diff --git a/browser/components/preferences/SiteDataManager.jsm b/browser/components/preferences/SiteDataManager.jsm index 8d2be6cb1ed9..6107f2361096 100644 --- a/browser/components/preferences/SiteDataManager.jsm +++ b/browser/components/preferences/SiteDataManager.jsm @@ -54,8 +54,8 @@ this.SiteDataManager = { if (status === Ci.nsIPermissionManager.ALLOW_ACTION || status === Ci.nsIPermissionManager.DENY_ACTION) { this._sites.set(perm.principal.origin, { - perm: perm, - status: status, + perm, + status, quotaUsage: 0, appCacheList: [], diskCacheList: [] @@ -79,7 +79,7 @@ this.SiteDataManager = { for (let site of this._sites.values()) { promises.push(new Promise(resolve => { let callback = { - onUsageResult: function(request) { + onUsageResult(request) { site.quotaUsage = request.usage; resolve(); } @@ -121,7 +121,7 @@ this.SiteDataManager = { if (this._sites.size) { let sites = this._sites; let visitor = { - onCacheEntryInfo: function(uri, idEnhance, dataSize) { + onCacheEntryInfo(uri, idEnhance, dataSize) { for (let site of sites.values()) { if (site.perm.matchesURI(uri, true)) { site.diskCacheList.push({ @@ -132,7 +132,7 @@ this.SiteDataManager = { } } }, - onCacheEntryVisitCompleted: function() { + onCacheEntryVisitCompleted() { resolve(); } }; diff --git a/browser/components/preferences/blocklists.js b/browser/components/preferences/blocklists.js index 208a329d5f82..70ea7f1c43ba 100644 --- a/browser/components/preferences/blocklists.js +++ b/browser/components/preferences/blocklists.js @@ -22,7 +22,7 @@ var gBlocklistManager = { get rowCount() { return this._rowCount; }, - getCellText: function(row, column) { + getCellText(row, column) { if (column.id == "listCol") { let list = gBlocklistManager._blockLists[row]; let desc = list.description ? list.description : ""; @@ -33,21 +33,21 @@ var gBlocklistManager = { return ""; }, - isSeparator: function(index) { return false; }, - isSorted: function() { return false; }, - isContainer: function(index) { return false; }, - setTree: function(tree) {}, - getImageSrc: function(row, column) {}, - getProgressMode: function(row, column) {}, - getCellValue: function(row, column) { + isSeparator(index) { return false; }, + isSorted() { return false; }, + isContainer(index) { return false; }, + setTree(tree) {}, + getImageSrc(row, column) {}, + getProgressMode(row, column) {}, + getCellValue(row, column) { if (column.id == "selectionCol") return gBlocklistManager._blockLists[row].selected; return undefined; }, - cycleHeader: function(column) {}, - getRowProperties: function(row) { return ""; }, - getColumnProperties: function(column) { return ""; }, - getCellProperties: function(row, column) { + cycleHeader(column) {}, + getRowProperties(row) { return ""; }, + getColumnProperties(column) { return ""; }, + getCellProperties(row, column) { if (column.id == "selectionCol") { return "checkmark"; } @@ -56,7 +56,7 @@ var gBlocklistManager = { } }, - onWindowKeyPress: function(event) { + onWindowKeyPress(event) { if (event.keyCode == KeyEvent.DOM_VK_ESCAPE) { window.close(); } else if (event.keyCode == KeyEvent.DOM_VK_RETURN) { @@ -64,13 +64,13 @@ var gBlocklistManager = { } }, - onLoad: function() { + onLoad() { this._bundle = document.getElementById("bundlePreferences"); let params = window.arguments[0]; this.init(params); }, - init: function(params) { + init(params) { if (this._type) { // reusing an open dialog, clear the old observer this.uninit(); @@ -97,9 +97,9 @@ var gBlocklistManager = { this._loadBlockLists(); }, - uninit: function() {}, + uninit() {}, - onListSelected: function() { + onListSelected() { for (let list of this._blockLists) { list.selected = false; } @@ -108,7 +108,7 @@ var gBlocklistManager = { this._updateTree(); }, - onApplyChanges: function() { + onApplyChanges() { let activeList = this._getActiveList(); let selected = null; for (let list of this._blockLists) { @@ -153,7 +153,7 @@ var gBlocklistManager = { window.close(); }, - _loadBlockLists: function() { + _loadBlockLists() { this._blockLists = []; // Load blocklists into a table. @@ -171,7 +171,7 @@ var gBlocklistManager = { this._updateTree(); }, - _createOrUpdateBlockList: function(itemName) { + _createOrUpdateBlockList(itemName) { let branch = Services.prefs.getBranch(LISTS_PREF_BRANCH); let key = branch.getCharPref(itemName); let value = this._bundle.getString(key); @@ -192,13 +192,13 @@ var gBlocklistManager = { return list; }, - _updateTree: function() { + _updateTree() { this._tree = document.getElementById("blocklistsTree"); this._view._rowCount = this._blockLists.length; this._tree.view = this._view; }, - _getActiveList: function() { + _getActiveList() { let trackingTable = Services.prefs.getCharPref(TRACKING_TABLE_PREF); return trackingTable.includes(CONTENT_LIST_ID) ? CONTENT_LIST_ID : BASE_LIST_ID; } diff --git a/browser/components/preferences/connection.js b/browser/components/preferences/connection.js index 9997a1a7490c..128c9caa8549 100644 --- a/browser/components/preferences/connection.js +++ b/browser/components/preferences/connection.js @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gConnectionsDialog = { - beforeAccept: function() + beforeAccept() { var proxyTypePref = document.getElementById("network.proxy.type"); if (proxyTypePref.value == 2) { @@ -52,13 +52,13 @@ var gConnectionsDialog = { return true; }, - checkForSystemProxy: function() + checkForSystemProxy() { if ("@mozilla.org/system-proxy-settings;1" in Components.classes) document.getElementById("systemPref").removeAttribute("hidden"); }, - proxyTypeChanged: function() + proxyTypeChanged() { var proxyTypePref = document.getElementById("network.proxy.type"); @@ -84,7 +84,7 @@ var gConnectionsDialog = { this.updateReloadButton(); }, - updateDNSPref: function() + updateDNSPref() { var socksVersionPref = document.getElementById("network.proxy.socks_version"); var socksDNSPref = document.getElementById("network.proxy.socks_remote_dns"); @@ -94,7 +94,7 @@ var gConnectionsDialog = { return undefined; }, - updateReloadButton: function() + updateReloadButton() { // Disable the "Reload PAC" button if the selected proxy type is not PAC or // if the current value of the PAC textbox does not match the value stored @@ -116,13 +116,13 @@ var gConnectionsDialog = { (proxyTypeCur != 2 || proxyType != 2 || typedURL != pacURL); }, - readProxyType: function() + readProxyType() { this.proxyTypeChanged(); return undefined; }, - updateProtocolPrefs: function() + updateProtocolPrefs() { var proxyTypePref = document.getElementById("network.proxy.type"); var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); @@ -156,7 +156,7 @@ var gConnectionsDialog = { return undefined; }, - readProxyProtocolPref: function(aProtocol, aIsPort) + readProxyProtocolPref(aProtocol, aIsPort) { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) { @@ -168,13 +168,13 @@ var gConnectionsDialog = { return backupPref.hasUserValue ? backupPref.value : undefined; }, - reloadPAC: function() + reloadPAC() { Components.classes["@mozilla.org/network/protocol-proxy-service;1"]. getService().reloadPAC(); }, - doAutoconfigURLFixup: function() + doAutoconfigURLFixup() { var autoURL = document.getElementById("networkProxyAutoconfigURL"); var autoURLPref = document.getElementById("network.proxy.autoconfig_url"); @@ -185,7 +185,7 @@ var gConnectionsDialog = { } catch (ex) {} }, - sanitizeNoProxiesPref: function() + sanitizeNoProxiesPref() { var noProxiesPref = document.getElementById("network.proxy.no_proxies_on"); // replace substrings of ; and \n with commas if they're neither immediately @@ -195,7 +195,7 @@ var gConnectionsDialog = { noProxiesPref.value = noProxiesPref.value.replace(/[;\n]/g, ''); }, - readHTTPProxyServer: function() + readHTTPProxyServer() { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) @@ -203,7 +203,7 @@ var gConnectionsDialog = { return undefined; }, - readHTTPProxyPort: function() + readHTTPProxyPort() { var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); if (shareProxiesPref.value) diff --git a/browser/components/preferences/cookies.js b/browser/components/preferences/cookies.js index 82abbebb00ef..55b8e6cbb26b 100644 --- a/browser/components/preferences/cookies.js +++ b/browser/components/preferences/cookies.js @@ -21,7 +21,7 @@ var gCookiesWindow = { _tree : null, _bundle : null, - init: function() { + init() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); os.addObserver(this, "cookie-changed", false); @@ -39,14 +39,14 @@ var gCookiesWindow = { } }, - uninit: function() { + uninit() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); os.removeObserver(this, "cookie-changed"); os.removeObserver(this, "perm-changed"); }, - _populateList: function(aInitialLoad) { + _populateList(aInitialLoad) { this._loadCookies(); this._tree.view = this._view; if (aInitialLoad) @@ -69,7 +69,7 @@ var gCookiesWindow = { this._saveState(); }, - _cookieEquals: function(aCookieA, aCookieB, aStrippedHost) { + _cookieEquals(aCookieA, aCookieB, aStrippedHost) { return aCookieA.rawHost == aStrippedHost && aCookieA.name == aCookieB.name && aCookieA.path == aCookieB.path && @@ -77,7 +77,7 @@ var gCookiesWindow = { aCookieB.originAttributes); }, - _isPrivateCookie: function(aCookie) { + _isPrivateCookie(aCookie) { let { userContextId } = aCookie.originAttributes; if (!userContextId) { // Default identity is public. @@ -86,7 +86,7 @@ var gCookiesWindow = { return !ContextualIdentityService.getIdentityFromId(userContextId).public; }, - observe: function(aCookie, aTopic, aData) { + observe(aCookie, aTopic, aData) { if (aTopic != "cookie-changed") return; @@ -123,7 +123,7 @@ var gCookiesWindow = { // and is rather complicated as selection tracking is difficult }, - _handleCookieChanged: function(changedCookie, strippedHost) { + _handleCookieChanged(changedCookie, strippedHost) { var rowIndex = 0; var cookieItem = null; if (!this._view._filtered) { @@ -172,7 +172,7 @@ var gCookiesWindow = { this._updateCookieData(cookieItem); }, - _handleCookieAdded: function(changedCookie, strippedHost) { + _handleCookieAdded(changedCookie, strippedHost) { var rowCountImpact = 0; var addedHost = { value: 0 }; this._addCookie(strippedHost, changedCookie, addedHost); @@ -212,7 +212,7 @@ var gCookiesWindow = { return this._rowCount; }, - _getItemAtIndex: function(aIndex) { + _getItemAtIndex(aIndex) { if (this._filtered) return this._filterSet[aIndex]; @@ -267,7 +267,7 @@ var gCookiesWindow = { return null; }, - _removeItemAtIndex: function(aIndex, aCount) { + _removeItemAtIndex(aIndex, aCount) { let removeCount = aCount === undefined ? 1 : aCount; if (this._filtered) { // remove the cookies from the unfiltered set so that they @@ -306,11 +306,11 @@ var gCookiesWindow = { } }, - _invalidateCache: function(aIndex) { + _invalidateCache(aIndex) { this._cacheValid = Math.min(this._cacheValid, aIndex); }, - getCellText: function(aIndex, aColumn) { + getCellText(aIndex, aColumn) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) @@ -331,10 +331,10 @@ var gCookiesWindow = { _selection: null, get selection() { return this._selection; }, set selection(val) { this._selection = val; return val; }, - getRowProperties: function(aIndex) { return ""; }, - getCellProperties: function(aIndex, aColumn) { return ""; }, - getColumnProperties: function(aColumn) { return ""; }, - isContainer: function(aIndex) { + getRowProperties(aIndex) { return ""; }, + getCellProperties(aIndex, aColumn) { return ""; }, + getColumnProperties(aColumn) { return ""; }, + isContainer(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -342,7 +342,7 @@ var gCookiesWindow = { } return false; }, - isContainerOpen: function(aIndex) { + isContainerOpen(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -350,7 +350,7 @@ var gCookiesWindow = { } return false; }, - isContainerEmpty: function(aIndex) { + isContainerEmpty(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -358,11 +358,11 @@ var gCookiesWindow = { } return false; }, - isSeparator: function(aIndex) { return false; }, - isSorted: function(aIndex) { return false; }, - canDrop: function(aIndex, aOrientation) { return false; }, - drop: function(aIndex, aOrientation) {}, - getParentIndex: function(aIndex) { + isSeparator(aIndex) { return false; }, + isSorted(aIndex) { return false; }, + canDrop(aIndex, aOrientation) { return false; }, + drop(aIndex, aOrientation) {}, + getParentIndex(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); // If an item has no parent index (i.e. it is at the top level) this @@ -374,7 +374,7 @@ var gCookiesWindow = { } return -1; }, - hasNextSibling: function(aParentIndex, aIndex) { + hasNextSibling(aParentIndex, aIndex) { if (!this._filtered) { // |aParentIndex| appears to be bogus, but we can get the real // parent index by getting the entry for |aIndex| and reading the @@ -399,7 +399,7 @@ var gCookiesWindow = { } return aIndex < this.rowCount - 1; }, - hasPreviousSibling: function(aIndex) { + hasPreviousSibling(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return false; @@ -409,7 +409,7 @@ var gCookiesWindow = { } return aIndex > 0; }, - getLevel: function(aIndex) { + getLevel(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return 0; @@ -417,11 +417,11 @@ var gCookiesWindow = { } return 0; }, - getImageSrc: function(aIndex, aColumn) {}, - getProgressMode: function(aIndex, aColumn) {}, - getCellValue: function(aIndex, aColumn) {}, - setTree: function(aTree) {}, - toggleOpenState: function(aIndex) { + getImageSrc(aIndex, aColumn) {}, + getProgressMode(aIndex, aColumn) {}, + getCellValue(aIndex, aColumn) {}, + setTree(aTree) {}, + toggleOpenState(aIndex) { if (!this._filtered) { var item = this._getItemAtIndex(aIndex); if (!item) return; @@ -434,28 +434,28 @@ var gCookiesWindow = { gCookiesWindow._tree.treeBoxObject.invalidateRow(aIndex); } }, - cycleHeader: function(aColumn) {}, - selectionChanged: function() {}, - cycleCell: function(aIndex, aColumn) {}, - isEditable: function(aIndex, aColumn) { + cycleHeader(aColumn) {}, + selectionChanged() {}, + cycleCell(aIndex, aColumn) {}, + isEditable(aIndex, aColumn) { return false; }, - isSelectable: function(aIndex, aColumn) { + isSelectable(aIndex, aColumn) { return false; }, - setCellValue: function(aIndex, aColumn, aValue) {}, - setCellText: function(aIndex, aColumn, aValue) {}, - performAction: function(aAction) {}, - performActionOnRow: function(aAction, aIndex) {}, - performActionOnCell: function(aAction, aindex, aColumn) {} + setCellValue(aIndex, aColumn, aValue) {}, + setCellText(aIndex, aColumn, aValue) {}, + performAction(aAction) {}, + performActionOnRow(aAction, aIndex) {}, + performActionOnCell(aAction, aindex, aColumn) {} }, - _makeStrippedHost: function(aHost) { + _makeStrippedHost(aHost) { var formattedHost = aHost.charAt(0) == "." ? aHost.substring(1, aHost.length) : aHost; return formattedHost.substring(0, 4) == "www." ? formattedHost.substring(4, formattedHost.length) : formattedHost; }, - _addCookie: function(aStrippedHost, aCookie, aHostCount) { + _addCookie(aStrippedHost, aCookie, aHostCount) { if (!(aStrippedHost in this._hosts) || !this._hosts[aStrippedHost]) { this._hosts[aStrippedHost] = { cookies : [], rawHost : aStrippedHost, @@ -470,7 +470,7 @@ var gCookiesWindow = { this._hosts[aStrippedHost].cookies.push(c); }, - _makeCookieObject: function(aStrippedHost, aCookie) { + _makeCookieObject(aStrippedHost, aCookie) { var c = { name : aCookie.name, value : aCookie.value, isDomain : aCookie.isDomain, @@ -485,7 +485,7 @@ var gCookiesWindow = { return c; }, - _loadCookies: function() { + _loadCookies() { var e = this._cm.enumerator; var hostCount = { value: 0 }; this._hosts = {}; @@ -506,7 +506,7 @@ var gCookiesWindow = { this._view._rowCount = hostCount.value; }, - formatExpiresString: function(aExpires) { + formatExpiresString(aExpires) { if (aExpires) { var date = new Date(1000 * aExpires); const locale = Components.classes["@mozilla.org/chrome/chrome-registry;1"] @@ -519,7 +519,7 @@ var gCookiesWindow = { return this._bundle.getString("expireAtEndOfSession"); }, - _getUserContextString: function(aUserContextId) { + _getUserContextString(aUserContextId) { if (parseInt(aUserContextId) == 0) { return this._bundle.getString("defaultUserContextLabel"); } @@ -527,7 +527,7 @@ var gCookiesWindow = { return ContextualIdentityService.getUserContextLabel(aUserContextId); }, - _updateCookieData: function(aItem) { + _updateCookieData(aItem) { var seln = this._view.selection; var ids = ["name", "value", "host", "path", "isSecure", "expires", "userContext"]; var properties; @@ -557,7 +557,7 @@ var gCookiesWindow = { document.getElementById(property).value = properties[property]; }, - onCookieSelected: function() { + onCookieSelected() { var item; var seln = this._tree.view.selection; if (!this._view._filtered) @@ -602,7 +602,7 @@ var gCookiesWindow = { } }, - deleteCookie: function() { + deleteCookie() { // Selection Notes // - Selection always moves to *NEXT* adjacent item unless item // is last child at a given level in which case it moves to *PREVIOUS* @@ -728,7 +728,7 @@ var gCookiesWindow = { } }, - deleteAllCookies: function() { + deleteAllCookies() { if (this._view._filtered) { var rowCount = this._view.rowCount; var deleteItems = []; @@ -747,7 +747,7 @@ var gCookiesWindow = { this.focusFilterBox(); }, - onCookieKeyPress: function(aEvent) { + onCookieKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) { this.deleteCookie(); } else if (AppConstants.platform == "macosx" && @@ -758,7 +758,7 @@ var gCookiesWindow = { _lastSortProperty : "", _lastSortAscending: false, - sort: function(aProperty) { + sort(aProperty) { var ascending = (aProperty == this._lastSortProperty) ? !this._lastSortAscending : true; // Sort the Non-Filtered Host Collections if (aProperty == "rawHost") { @@ -809,7 +809,7 @@ var gCookiesWindow = { this._lastSortProperty = aProperty; }, - clearFilter: function() { + clearFilter() { // Revert to single-select in the tree this._tree.setAttribute("seltype", "single"); @@ -851,13 +851,13 @@ var gCookiesWindow = { this._updateRemoveAllButton(); }, - _cookieMatchesFilter: function(aCookie) { + _cookieMatchesFilter(aCookie) { return aCookie.rawHost.indexOf(this._view._filterValue) != -1 || aCookie.name.indexOf(this._view._filterValue) != -1 || aCookie.value.indexOf(this._view._filterValue) != -1; }, - _filterCookies: function(aFilterValue) { + _filterCookies(aFilterValue) { this._view._filterValue = aFilterValue; var cookies = []; for (let i = 0; i < gCookiesWindow._hostOrder.length; ++i) { // var host in gCookiesWindow._hosts) { @@ -873,7 +873,7 @@ var gCookiesWindow = { _lastSelectedRanges: [], _openIndices: [], - _saveState: function() { + _saveState() { // Save selection var seln = this._view.selection; this._lastSelectedRanges = []; @@ -897,7 +897,7 @@ var gCookiesWindow = { document.getElementById("removeAllCookies").disabled = this._view._rowCount == 0; }, - filter: function() { + filter() { var filter = document.getElementById("filter").value; if (filter == "") { gCookiesWindow.clearFilter(); @@ -930,18 +930,18 @@ var gCookiesWindow = { this._updateRemoveAllButton(); }, - setFilter: function(aFilterString) { + setFilter(aFilterString) { document.getElementById("filter").value = aFilterString; this.filter(); }, - focusFilterBox: function() { + focusFilterBox() { var filter = document.getElementById("filter"); filter.focus(); filter.select(); }, - onWindowKeyPress: function(aEvent) { + onWindowKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); } diff --git a/browser/components/preferences/fonts.js b/browser/components/preferences/fonts.js index e6b2a0acd73d..ac66044a2b80 100644 --- a/browser/components/preferences/fonts.js +++ b/browser/components/preferences/fonts.js @@ -19,7 +19,7 @@ const kFontSizeFmtFixed = "font.size.fixed.%LANG%"; const kFontMinSizeFmt = "font.minimum-size.%LANG%"; var gFontsDialog = { - _selectLanguageGroup: function(aLanguageGroup) + _selectLanguageGroup(aLanguageGroup) { var prefs = [{ format: kDefaultFontType, type: "string", element: "defaultFontType", fonttype: null}, { format: kFontNameFmtSerif, type: "fontname", element: "serif", fonttype: "serif" }, @@ -58,26 +58,26 @@ var gFontsDialog = { } }, - readFontLanguageGroup: function() + readFontLanguageGroup() { var languagePref = document.getElementById("font.language.group"); this._selectLanguageGroup(languagePref.value); return undefined; }, - readUseDocumentFonts: function() + readUseDocumentFonts() { var preference = document.getElementById("browser.display.use_document_fonts"); return preference.value == 1; }, - writeUseDocumentFonts: function() + writeUseDocumentFonts() { var useDocumentFonts = document.getElementById("useDocumentFonts"); return useDocumentFonts.checked ? 1 : 0; }, - onBeforeAccept: function() + onBeforeAccept() { let preferences = document.querySelectorAll("preference[id*='font.minimum-size']"); // It would be good if we could avoid touching languages the pref pages won't use, but diff --git a/browser/components/preferences/in-content/tests/browser_advanced_siteData.js b/browser/components/preferences/in-content/tests/browser_advanced_siteData.js index 043c8aea072d..4b635a2138de 100644 --- a/browser/components/preferences/in-content/tests/browser_advanced_siteData.js +++ b/browser/components/preferences/in-content/tests/browser_advanced_siteData.js @@ -21,13 +21,13 @@ const mockOfflineAppCacheHelper = { originalClear: null, - register: function() { + register() { this.originalClear = OfflineAppCacheHelper.clear; this.clear = sinon.spy(); OfflineAppCacheHelper.clear = this.clear; }, - unregister: function() { + unregister() { OfflineAppCacheHelper.clear = this.originalClear; } }; @@ -55,7 +55,7 @@ function getQuotaUsage(origin) { function getCacheUsage() { return new Promise(resolve => { let obs = { - onNetworkCacheDiskConsumption: function(usage) { + onNetworkCacheDiskConsumption(usage) { resolve(usage); }, QueryInterface: XPCOMUtils.generateQI([ diff --git a/browser/components/preferences/in-content/tests/browser_advanced_update.js b/browser/components/preferences/in-content/tests/browser_advanced_update.js index d9d7aa33ae7a..9a18fcecae6b 100644 --- a/browser/components/preferences/in-content/tests/browser_advanced_update.js +++ b/browser/components/preferences/in-content/tests/browser_advanced_update.js @@ -20,14 +20,14 @@ const mockUpdateManager = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateManager]), - createInstance: function(outer, iiD) { + createInstance(outer, iiD) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } return this.QueryInterface(iiD); }, - register: function() { + register() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); if (!registrar.isCIDRegistered(this._mockClassId)) { this._originalClassId = registrar.contractIDToCID(this.contractId); @@ -37,7 +37,7 @@ const mockUpdateManager = { } }, - unregister: function() { + unregister() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(this._mockClassId, this); registrar.registerFactory(this._originalClassId, "", this.contractId, this._originalFactory); @@ -47,7 +47,7 @@ const mockUpdateManager = { return this._updates.length; }, - getUpdateAt: function(index) { + getUpdateAt(index) { return this._updates[index]; }, diff --git a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js b/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js index 32c1bd726374..40741cccab77 100644 --- a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js +++ b/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js @@ -27,14 +27,14 @@ add_task(function*() { // Simulate a dumb font backend. win.FontBuilder._enumerator = { _list: ["MockedFont1", "MockedFont2", "MockedFont3"], - EnumerateFonts: function(lang, type, list) { + EnumerateFonts(lang, type, list) { return this._list; }, - EnumerateAllFonts: function() { + EnumerateAllFonts() { return this._list; }, - getDefaultFont: function() { return null; }, - getStandardFamilyName: function(name) { return name; }, + getDefaultFont() { return null; }, + getStandardFamilyName(name) { return name; }, }; win.FontBuilder._allFonts = null; win.FontBuilder._langGroupSupported = false; diff --git a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js b/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js index bc2c6d800296..8d0a910f0c14 100644 --- a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js +++ b/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js @@ -35,7 +35,7 @@ function openPreferencesViaHash(aPane) { let win = gBrowser.contentWindow; let selectedPane = win.history.state; gBrowser.removeCurrentTab(); - deferred.resolve({selectedPane: selectedPane}); + deferred.resolve({selectedPane}); }); }, true); diff --git a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js b/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js index 15342f127529..d604332096b5 100644 --- a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js +++ b/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js @@ -14,7 +14,7 @@ var testRunner = { tests: [ { - test: function(params) { + test(params) { params.url.value = "test.com"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -28,7 +28,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "test.com"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", @@ -41,7 +41,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "test.com"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", @@ -54,7 +54,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "test.com"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -64,7 +64,7 @@ var testRunner = { }, { expectPermObservancesDuringTestFunction: true, - test: function(params) { + test(params) { let uri = params.ioService.newURI("http://test.com", null, null); params.pm.add(uri, "popup", Ci.nsIPermissionManager.DENY_ACTION); is(params.tree.view.rowCount, 0, "adding unrelated permission should not change display"); @@ -72,13 +72,13 @@ var testRunner = { }, observances: [{ type: "popup", origin: "http://test.com", data: "added", capability: Ci.nsIPermissionManager.DENY_ACTION }], - cleanUp: function(params) { + cleanUp(params) { let uri = params.ioService.newURI("http://test.com", null, null); params.pm.remove(uri, "popup"); }, }, { - test: function(params) { + test(params) { params.url.value = "https://test.com:12345"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -92,7 +92,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "https://test.com:12345"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", @@ -105,7 +105,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "https://test.com:12345"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", @@ -118,7 +118,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "https://test.com:12345"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -127,7 +127,7 @@ var testRunner = { observances: [{ type: "cookie", origin: "https://test.com:12345", data: "deleted" }], }, { - test: function(params) { + test(params) { params.url.value = "localhost:12345"; params.btnAllow.doCommand(); is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); @@ -141,7 +141,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "localhost:12345"; params.btnBlock.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", @@ -154,7 +154,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.DENY_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "localhost:12345"; params.btnAllow.doCommand(); is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", @@ -167,7 +167,7 @@ var testRunner = { capability: Ci.nsIPermissionManager.ALLOW_ACTION }], }, { - test: function(params) { + test(params) { params.url.value = "localhost:12345"; params.btnRemove.doCommand(); is(params.tree.view.rowCount, 0, "exception should be removed"); @@ -220,7 +220,7 @@ var testRunner = { _currentTest: -1, - runTests: function() { + runTests() { this._currentTest++; info("Running test #" + (this._currentTest + 1) + "\n"); @@ -236,11 +236,11 @@ var testRunner = { }); }, - runCurrentTest: function(testNumber) { + runCurrentTest(testNumber) { return new Promise(function(resolve, reject) { let helperFunctions = { - windowLoad: function(win) { + windowLoad(win) { let doc = win.document; let params = { doc, @@ -265,7 +265,7 @@ var testRunner = { }; let permObserver = { - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic != "perm-changed") return; diff --git a/browser/components/preferences/in-content/tests/head.js b/browser/components/preferences/in-content/tests/head.js index 203fd686782b..d9eb3a1aabfa 100644 --- a/browser/components/preferences/in-content/tests/head.js +++ b/browser/components/preferences/in-content/tests/head.js @@ -136,7 +136,7 @@ function openPreferencesViaOpenPreferencesAPI(aPane, aAdvancedTab, aOptions) { let selectedAdvancedTab = aAdvancedTab && doc.getElementById("advancedPrefs").selectedTab.id; if (!aOptions || !aOptions.leaveOpen) gBrowser.removeCurrentTab(); - deferred.resolve({selectedPane: selectedPane, selectedAdvancedTab: selectedAdvancedTab}); + deferred.resolve({selectedPane, selectedAdvancedTab}); }); }, true); diff --git a/browser/components/preferences/languages.js b/browser/components/preferences/languages.js index 677892b942ff..2be9ddfbced2 100644 --- a/browser/components/preferences/languages.js +++ b/browser/components/preferences/languages.js @@ -10,7 +10,7 @@ var gLanguagesDialog = { _selectedItemID : null, - init: function() + init() { if (!this._availableLanguagesList.length) this._loadAvailableLanguages(); @@ -18,7 +18,7 @@ var gLanguagesDialog = { // Ugly hack used to trigger extra reflow in order to work around XUL bug 1194844; // see bug 1194346. - forceReflow: function() + forceReflow() { this._activeLanguages.style.fontKerning = "none"; setTimeout("gLanguagesDialog._activeLanguages.style.removeProperty('font-kerning')", 0); @@ -34,7 +34,7 @@ var gLanguagesDialog = { return document.getElementById("availableLanguages"); }, - _loadAvailableLanguages: function() + _loadAvailableLanguages() { // This is a parser for: resource://gre/res/language.properties // The file is formatted like so: @@ -102,7 +102,7 @@ var gLanguagesDialog = { this._buildAvailableLanguageList(); }, - _buildAvailableLanguageList: function() + _buildAvailableLanguageList() { var availableLanguagesPopup = document.getElementById("availableLanguagesPopup"); while (availableLanguagesPopup.hasChildNodes()) @@ -126,7 +126,7 @@ var gLanguagesDialog = { } }, - readAcceptLanguages: function() + readAcceptLanguages() { while (this._activeLanguages.hasChildNodes()) this._activeLanguages.removeChild(this._activeLanguages.firstChild); @@ -160,12 +160,12 @@ var gLanguagesDialog = { return undefined; }, - writeAcceptLanguages: function() + writeAcceptLanguages() { return undefined; }, - onAvailableLanguageSelect: function() + onAvailableLanguageSelect() { var addButton = document.getElementById("addButton"); addButton.disabled = false; @@ -173,7 +173,7 @@ var gLanguagesDialog = { this._availableLanguages.removeAttribute("accesskey"); }, - addLanguage: function() + addLanguage() { var selectedID = this._availableLanguages.selectedItem.id; var preference = document.getElementById("intl.accept_languages"); @@ -201,7 +201,7 @@ var gLanguagesDialog = { this._availableLanguages.setAttribute("label", this._availableLanguages.getAttribute("label2")); }, - removeLanguage: function() + removeLanguage() { // Build the new preference value string. var languagesArray = []; @@ -229,7 +229,7 @@ var gLanguagesDialog = { this._buildAvailableLanguageList(); }, - _getLanguageName: function(aABCD) + _getLanguageName(aABCD) { if (!this._availableLanguagesList.length) this._loadAvailableLanguages(); @@ -240,7 +240,7 @@ var gLanguagesDialog = { return ""; }, - moveUp: function() + moveUp() { var selectedItem = this._activeLanguages.selectedItems[0]; var previousItem = selectedItem.previousSibling; @@ -264,7 +264,7 @@ var gLanguagesDialog = { preference.value = string; }, - moveDown: function() + moveDown() { var selectedItem = this._activeLanguages.selectedItems[0]; var nextItem = selectedItem.nextSibling; @@ -288,7 +288,7 @@ var gLanguagesDialog = { preference.value = string; }, - onLanguageSelect: function() + onLanguageSelect() { var upButton = document.getElementById("up"); var downButton = document.getElementById("down"); diff --git a/browser/components/preferences/permissions.js b/browser/components/preferences/permissions.js index 43a7c02dee71..40469cdacf2a 100644 --- a/browser/components/preferences/permissions.js +++ b/browser/components/preferences/permissions.js @@ -32,7 +32,7 @@ var gPermissionManager = { { return this._rowCount; }, - getCellText: function(aRow, aColumn) + getCellText(aRow, aColumn) { if (aColumn.id == "siteCol") return gPermissionManager._permissions[aRow].origin; @@ -41,17 +41,17 @@ var gPermissionManager = { return ""; }, - isSeparator: function(aIndex) { return false; }, - isSorted: function() { return false; }, - isContainer: function(aIndex) { return false; }, - setTree: function(aTree) {}, - getImageSrc: function(aRow, aColumn) {}, - getProgressMode: function(aRow, aColumn) {}, - getCellValue: function(aRow, aColumn) {}, - cycleHeader: function(column) {}, - getRowProperties: function(row) { return ""; }, - getColumnProperties: function(column) { return ""; }, - getCellProperties: function(row, column) { + isSeparator(aIndex) { return false; }, + isSorted() { return false; }, + isContainer(aIndex) { return false; }, + setTree(aTree) {}, + getImageSrc(aRow, aColumn) {}, + getProgressMode(aRow, aColumn) {}, + getCellValue(aRow, aColumn) {}, + cycleHeader(column) {}, + getRowProperties(row) { return ""; }, + getColumnProperties(column) { return ""; }, + getCellProperties(row, column) { if (column.element.getAttribute("id") == "siteCol") return "ltr"; @@ -59,7 +59,7 @@ var gPermissionManager = { } }, - _getCapabilityString: function(aCapability) + _getCapabilityString(aCapability) { var stringKey = null; switch (aCapability) { @@ -79,7 +79,7 @@ var gPermissionManager = { return this._bundle.getString(stringKey); }, - addPermission: function(aCapability) + addPermission(aCapability) { var textbox = document.getElementById("url"); var input_url = textbox.value.replace(/^\s*/, ""); // trim any leading space @@ -127,7 +127,7 @@ var gPermissionManager = { } } - let permissionParams = {principal: principal, type: this._type, capability: aCapability}; + let permissionParams = {principal, type: this._type, capability: aCapability}; if (!permissionExists) { this._permissionsToAdd.set(principal.origin, permissionParams); this._addPermission(permissionParams); @@ -147,7 +147,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = this._permissions.length == 0; }, - _removePermission: function(aPermission) + _removePermission(aPermission) { this._removePermissionFromList(aPermission.principal); @@ -162,7 +162,7 @@ var gPermissionManager = { }, - _handleCapabilityChange: function() + _handleCapabilityChange() { // Re-do the sort, if the status changed from Block to Allow // or vice versa, since if we're sorted on status, we may no @@ -173,7 +173,7 @@ var gPermissionManager = { this._tree.treeBoxObject.invalidate(); }, - _addPermission: function(aPermission) + _addPermission(aPermission) { this._addPermissionToList(aPermission); ++this._view._rowCount; @@ -182,7 +182,7 @@ var gPermissionManager = { this._resortPermissions(); }, - _resortPermissions: function() + _resortPermissions() { gTreeUtils.sort(this._tree, this._view, this._permissions, this._lastPermissionSortColumn, @@ -191,33 +191,33 @@ var gPermissionManager = { !this._lastPermissionSortAscending); // keep sort direction }, - onHostInput: function(aSiteField) + onHostInput(aSiteField) { document.getElementById("btnSession").disabled = !aSiteField.value; document.getElementById("btnBlock").disabled = !aSiteField.value; document.getElementById("btnAllow").disabled = !aSiteField.value; }, - onWindowKeyPress: function(aEvent) + onWindowKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); }, - onHostKeyPress: function(aEvent) + onHostKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN) document.getElementById("btnAllow").click(); }, - onLoad: function() + onLoad() { this._bundle = document.getElementById("bundlePreferences"); var params = window.arguments[0]; this.init(params); }, - init: function(aParams) + init(aParams) { if (this._type) { // reusing an open dialog, clear the old observer @@ -275,7 +275,7 @@ var gPermissionManager = { urlField.focus(); }, - uninit: function() + uninit() { if (!this._observerRemoved) { Services.obs.removeObserver(this, "perm-changed"); @@ -284,7 +284,7 @@ var gPermissionManager = { } }, - observe: function(aSubject, aTopic, aData) + observe(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { var permission = aSubject.QueryInterface(Components.interfaces.nsIPermission); @@ -311,7 +311,7 @@ var gPermissionManager = { } }, - onPermissionSelected: function() + onPermissionSelected() { var hasSelection = this._tree.view.selection.count > 0; var hasRows = this._tree.view.rowCount > 0; @@ -319,7 +319,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = !hasRows; }, - onPermissionDeleted: function() + onPermissionDeleted() { if (!this._view.rowCount) return; @@ -333,7 +333,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = !this._permissions.length; }, - onAllPermissionsDeleted: function() + onAllPermissionsDeleted() { if (!this._view.rowCount) return; @@ -347,7 +347,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = true; }, - onPermissionKeyPress: function(aEvent) + onPermissionKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) { this.onPermissionDeleted(); @@ -359,13 +359,13 @@ var gPermissionManager = { _lastPermissionSortColumn: "", _lastPermissionSortAscending: false, - _permissionsComparator : function(a, b) + _permissionsComparator(a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }, - onPermissionSort: function(aColumn) + onPermissionSort(aColumn) { this._lastPermissionSortAscending = gTreeUtils.sort(this._tree, this._view, @@ -377,7 +377,7 @@ var gPermissionManager = { this._lastPermissionSortColumn = aColumn; }, - onApplyChanges: function() + onApplyChanges() { // Stop observing permission changes since we are about // to write out the pending adds/deletes and don't need @@ -395,7 +395,7 @@ var gPermissionManager = { window.close(); }, - _loadPermissions: function() + _loadPermissions() { this._tree = document.getElementById("permissionsTree"); this._permissions = []; @@ -417,7 +417,7 @@ var gPermissionManager = { document.getElementById("removeAllPermissions").disabled = this._permissions.length == 0; }, - _addPermissionToList: function(aPermission) + _addPermissionToList(aPermission) { if (aPermission.type == this._type && (!this._manageCapability || @@ -432,7 +432,7 @@ var gPermissionManager = { } }, - _removePermissionFromList: function(aPrincipal) + _removePermissionFromList(aPrincipal) { for (let i = 0; i < this._permissions.length; ++i) { if (this._permissions[i].principal.equals(aPrincipal)) { @@ -445,7 +445,7 @@ var gPermissionManager = { } }, - setOrigin: function(aOrigin) + setOrigin(aOrigin) { document.getElementById("url").value = aOrigin; } diff --git a/browser/components/preferences/sanitize.js b/browser/components/preferences/sanitize.js index a9beea163d92..cf764086db98 100644 --- a/browser/components/preferences/sanitize.js +++ b/browser/components/preferences/sanitize.js @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gSanitizeDialog = Object.freeze({ - init: function() { + init() { let customWidthElements = document.getElementsByAttribute("dialogWidth", "*"); let isInSubdialog = document.documentElement.hasAttribute("subdialog"); for (let element of customWidthElements) { @@ -13,7 +13,7 @@ var gSanitizeDialog = Object.freeze({ this.onClearHistoryChanged(); }, - onClearHistoryChanged: function() { + onClearHistoryChanged() { let downloadsPref = document.getElementById("privacy.clearOnShutdown.downloads"); let historyPref = document.getElementById("privacy.clearOnShutdown.history"); downloadsPref.value = historyPref.value; diff --git a/browser/components/preferences/translation.js b/browser/components/preferences/translation.js index 0c7d86ff3165..82dd0e7bfedf 100644 --- a/browser/components/preferences/translation.js +++ b/browser/components/preferences/translation.js @@ -33,7 +33,7 @@ Tree.prototype = { get hasSelection() { return this.selection.count > 0; }, - getSelectedItems: function() { + getSelectedItems() { let result = []; let rc = this.selection.getRangeCount(); @@ -51,30 +51,30 @@ Tree.prototype = { get rowCount() { return this._data.length; }, - getCellText: function(aRow, aColumn) { + getCellText(aRow, aColumn) { return this._data[aRow]; }, - isSeparator: function(aIndex) { + isSeparator(aIndex) { return false; }, - isSorted: function() { + isSorted() { return false; }, - isContainer: function(aIndex) { + isContainer(aIndex) { return false; }, - setTree: function(aTree) {}, - getImageSrc: function(aRow, aColumn) {}, - getProgressMode: function(aRow, aColumn) {}, - getCellValue: function(aRow, aColumn) {}, - cycleHeader: function(column) {}, - getRowProperties: function(row) { + setTree(aTree) {}, + getImageSrc(aRow, aColumn) {}, + getProgressMode(aRow, aColumn) {}, + getCellValue(aRow, aColumn) {}, + cycleHeader(column) {}, + getRowProperties(row) { return ""; }, - getColumnProperties: function(column) { + getColumnProperties(column) { return ""; }, - getCellProperties: function(row, column) { + getCellProperties(row, column) { return ""; }, QueryInterface: XPCOMUtils.generateQI([Ci.nsITreeView]) @@ -87,13 +87,13 @@ function Lang(aCode) } Lang.prototype = { - toString: function() { + toString() { return this._label; } } var gTranslationExceptions = { - onLoad: function() { + onLoad() { if (this._siteTree) { // Re-using an open dialog, clear the old observers. this.uninit(); @@ -123,7 +123,7 @@ var gTranslationExceptions = { }, // Get the list of languages we don't translate as an array. - getLanguageExceptions: function() { + getLanguageExceptions() { let langs = Services.prefs.getCharPref(kLanguagesPref); if (!langs) return []; @@ -134,7 +134,7 @@ var gTranslationExceptions = { return result; }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "perm-changed") { if (aData == "cleared") { if (!this._sites.length) @@ -180,22 +180,22 @@ var gTranslationExceptions = { } }, - _handleButtonDisabling: function(aTree, aIdPart) { + _handleButtonDisabling(aTree, aIdPart) { let empty = aTree.isEmpty; document.getElementById("removeAll" + aIdPart + "s").disabled = empty; document.getElementById("remove" + aIdPart).disabled = empty || !aTree.hasSelection; }, - onLanguageSelected: function() { + onLanguageSelected() { this._handleButtonDisabling(this._langTree, "Language"); }, - onSiteSelected: function() { + onSiteSelected() { this._handleButtonDisabling(this._siteTree, "Site"); }, - onLanguageDeleted: function() { + onLanguageDeleted() { let langs = Services.prefs.getCharPref(kLanguagesPref); if (!langs) return; @@ -206,11 +206,11 @@ var gTranslationExceptions = { Services.prefs.setCharPref(kLanguagesPref, langs.join(",")); }, - onAllLanguagesDeleted: function() { + onAllLanguagesDeleted() { Services.prefs.setCharPref(kLanguagesPref, ""); }, - onSiteDeleted: function() { + onSiteDeleted() { let removedSites = this._siteTree.getSelectedItems(); for (let origin of removedSites) { let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(origin); @@ -218,7 +218,7 @@ var gTranslationExceptions = { } }, - onAllSitesDeleted: function() { + onAllSitesDeleted() { if (this._siteTree.isEmpty) return; @@ -233,22 +233,22 @@ var gTranslationExceptions = { this.onSiteSelected(); }, - onSiteKeyPress: function(aEvent) { + onSiteKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) this.onSiteDeleted(); }, - onLanguageKeyPress: function(aEvent) { + onLanguageKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE) this.onLanguageDeleted(); }, - onWindowKeyPress: function(aEvent) { + onWindowKeyPress(aEvent) { if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) window.close(); }, - uninit: function() { + uninit() { Services.obs.removeObserver(this, "perm-changed"); Services.prefs.removeObserver(kLanguagesPref, this); } diff --git a/browser/components/search/test/browser_426329.js b/browser/components/search/test/browser_426329.js index d9cbd3f7a9b9..259705b4c26a 100644 --- a/browser/components/search/test/browser_426329.js +++ b/browser/components/search/test/browser_426329.js @@ -47,11 +47,11 @@ function getMenuEntries() { function countEntries(name, value) { return new Promise(resolve => { let count = 0; - let obj = name && value ? {fieldname: name, value: value} : {}; + let obj = name && value ? {fieldname: name, value} : {}; FormHistory.count(obj, - { handleResult: function(result) { count = result; }, - handleError: function(error) { throw error; }, - handleCompletion: function(reason) { + { handleResult(result) { count = result; }, + handleError(error) { throw error; }, + handleCompletion(reason) { if (!reason) { resolve(count); } diff --git a/browser/components/search/test/browser_aboutSearchReset.js b/browser/components/search/test/browser_aboutSearchReset.js index 75b591077695..6001c274af37 100644 --- a/browser/components/search/test/browser_aboutSearchReset.js +++ b/browser/components/search/test/browser_aboutSearchReset.js @@ -49,7 +49,7 @@ var gTests = [ { desc: "Test the 'Keep Current Settings' button.", - run: function* () { + *run() { let engine = yield promiseNewEngine(kTestEngine, {setAsCurrent: true}); let expectedURL = engine. @@ -75,7 +75,7 @@ var gTests = [ { desc: "Test the 'Restore Search Defaults' button.", - run: function* () { + *run() { let currentEngine = Services.search.currentEngine; let originalEngine = Services.search.originalDefaultEngine; let doc = gBrowser.contentDocument; @@ -103,7 +103,7 @@ var gTests = [ { desc: "Click the settings link.", - run: function* () { + *run() { let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, "about:preferences#search") @@ -116,7 +116,7 @@ var gTests = [ { desc: "Load another page without clicking any of the buttons.", - run: function* () { + *run() { yield promiseTabLoadEvent(gBrowser.selectedTab, "about:mozilla"); checkTelemetryRecords(TELEMETRY_RESULT_ENUM.CLOSED_PAGE); diff --git a/browser/components/search/test/browser_abouthome_behavior.js b/browser/components/search/test/browser_abouthome_behavior.js index e7d062e65e46..5a19ffc6c1eb 100644 --- a/browser/components/search/test/browser_abouthome_behavior.js +++ b/browser/components/search/test/browser_abouthome_behavior.js @@ -64,28 +64,28 @@ function test() { { name: "Search with Bing from about:home", searchURL: replaceUrl("http://www.bing.com/search?q=foo&pc=MOZI&form=MOZSPG"), - run: function() { + run() { verify_about_home_search("Bing"); } }, { name: "Search with Yahoo from about:home", searchURL: replaceUrl("https://search.yahoo.com/search?p=foo&ei=UTF-8&fr=moz35"), - run: function() { + run() { verify_about_home_search("Yahoo"); } }, { name: "Search with Google from about:home", searchURL: replaceUrl("https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8"), - run: function() { + run() { verify_about_home_search("Google"); } }, { name: "Search with Amazon.com from about:home", searchURL: replaceUrl("https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&mode=blended&tag=mozilla-20&sourceid=Mozilla-search"), - run: function() { + run() { verify_about_home_search("Amazon.com"); } } diff --git a/browser/components/search/test/browser_addEngine.js b/browser/components/search/test/browser_addEngine.js index 512b2dd558ab..798c4e9f7294 100644 --- a/browser/components/search/test/browser_addEngine.js +++ b/browser/components/search/test/browser_addEngine.js @@ -46,14 +46,14 @@ var gTests = [ description: "Foo Search", searchForm: "http://mochi.test:8888/browser/browser/components/search/test/" }, - run: function() { + run() { Services.obs.addObserver(observer, "browser-search-engine-modified", false); gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml", null, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC", false); }, - added: function(engine) { + added(engine) { ok(engine, "engine was added."); checkEngine(this.engine, engine); @@ -66,14 +66,14 @@ var gTests = [ gSS.currentEngine = engine; }, - current: function(engine) { + current(engine) { let currentEngine = gSS.currentEngine; is(engine, currentEngine, "engine is current"); is(engine.name, this.engine.name, "current engine was changed successfully"); gSS.removeEngine(engine); }, - removed: function(engine) { + removed(engine) { // Remove the observer before calling the currentEngine getter, // as that getter will set the currentEngine to the original default // which will trigger a notification causing the test to loop over all diff --git a/browser/components/search/test/browser_amazon_behavior.js b/browser/components/search/test/browser_amazon_behavior.js index 55695e11e862..d695939c6375 100644 --- a/browser/components/search/test/browser_amazon_behavior.js +++ b/browser/components/search/test/browser_amazon_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base, - run: function() { + run() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base, - run: function() { + run() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search", searchURL: base, - run: function() { + run() { gURLBar.value = "a foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base, - run: function() { + run() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base, - run: function() { + run() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_bing_behavior.js b/browser/components/search/test/browser_bing_behavior.js index 5087bd182004..7011fe41dc59 100644 --- a/browser/components/search/test/browser_bing_behavior.js +++ b/browser/components/search/test/browser_bing_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base + "&form=MOZCON", - run: function() { + run() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base + "&form=MOZLBR", - run: function() { + run() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search with alias", searchURL: base + "&form=MOZLBR", - run: function() { + run() { gURLBar.value = "b foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base + "&form=MOZSBR", - run: function() { + run() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base + "&form=MOZTSB", - run: function() { + run() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_google_behavior.js b/browser/components/search/test/browser_google_behavior.js index 1f31b35d9d93..f75c86a830de 100644 --- a/browser/components/search/test/browser_google_behavior.js +++ b/browser/components/search/test/browser_google_behavior.js @@ -30,7 +30,7 @@ function test() { { name: "context menu search", searchURL: base, - run: function() { + run() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -39,7 +39,7 @@ function test() { { name: "keyword search", searchURL: base, - run: function() { + run() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -48,7 +48,7 @@ function test() { { name: "keyword search", searchURL: base, - run: function() { + run() { gURLBar.value = "g foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -57,7 +57,7 @@ function test() { { name: "search bar search", searchURL: base, - run: function() { + run() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -70,7 +70,7 @@ function test() { { name: "new tab search", searchURL: base, - run: function() { + run() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js b/browser/components/search/test/browser_hiddenOneOffs_cleanup.js index 7bbcd523dbb3..34c7eca17656 100644 --- a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js +++ b/browser/components/search/test/browser_hiddenOneOffs_cleanup.js @@ -7,14 +7,14 @@ function promiseNewEngine(basename) { return new Promise((resolve, reject) => { info("Waiting for engine to be added: " + basename); Services.search.init({ - onInitComplete: function() { + onInitComplete() { let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); } diff --git a/browser/components/search/test/browser_searchbar_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_keyboard_navigation.js index 26b8939c7d07..7e0602cf034f 100644 --- a/browser/components/search/test/browser_searchbar_keyboard_navigation.js +++ b/browser/components/search/test/browser_searchbar_keyboard_navigation.js @@ -37,16 +37,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(addOps, { - handleCompletion: function() { + handleCompletion() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_searchbar_openpopup.js b/browser/components/search/test/browser_searchbar_openpopup.js index df2a45e539c4..939ac9941894 100644 --- a/browser/components/search/test/browser_searchbar_openpopup.js +++ b/browser/components/search/test/browser_searchbar_openpopup.js @@ -58,16 +58,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(addOps, { - handleCompletion: function() { + handleCompletion() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js index e5e613971617..9ad747f76812 100644 --- a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js +++ b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js @@ -38,16 +38,16 @@ add_task(function* init() { info("adding search history values: " + kValues); let addOps = kValues.map(value => { return {op: "add", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(addOps, { - handleCompletion: function() { + handleCompletion() { registerCleanupFunction(() => { info("removing search history values: " + kValues); let removeOps = kValues.map(value => { return {op: "remove", fieldname: "searchbar-history", - value: value} + value} }); searchbar.FormHistory.update(removeOps); }); diff --git a/browser/components/search/test/browser_webapi.js b/browser/components/search/test/browser_webapi.js index d8161ffbe528..4016484c31f9 100644 --- a/browser/components/search/test/browser_webapi.js +++ b/browser/components/search/test/browser_webapi.js @@ -14,7 +14,7 @@ function AddSearchProvider(...args) { function promiseDialogOpened() { return new Promise((resolve, reject) => { Services.wm.addListener({ - onOpenWindow: function(xulWin) { + onOpenWindow(xulWin) { Services.wm.removeListener(this); let win = xulWin.QueryInterface(Ci.nsIInterfaceRequestor) diff --git a/browser/components/search/test/browser_yahoo_behavior.js b/browser/components/search/test/browser_yahoo_behavior.js index 5f182971f7f3..ec4d85d3adc4 100644 --- a/browser/components/search/test/browser_yahoo_behavior.js +++ b/browser/components/search/test/browser_yahoo_behavior.js @@ -32,7 +32,7 @@ function test() { { name: "context menu search", searchURL: base + "&hsimp=yhs-005", - run: function() { + run() { // Simulate a contextmenu search // FIXME: This is a bit "low-level"... BrowserSearch.loadSearch("foo", false, "contextmenu"); @@ -41,7 +41,7 @@ function test() { { name: "keyword search", searchURL: base + "&hsimp=yhs-002", - run: function() { + run() { gURLBar.value = "? foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -50,7 +50,7 @@ function test() { { name: "keyword search with alias", searchURL: base + "&hsimp=yhs-002", - run: function() { + run() { gURLBar.value = "y foo"; gURLBar.focus(); EventUtils.synthesizeKey("VK_RETURN", {}); @@ -59,7 +59,7 @@ function test() { { name: "search bar search", searchURL: base + "&hsimp=yhs-001", - run: function() { + run() { let sb = BrowserSearch.searchBar; sb.focus(); sb.value = "foo"; @@ -72,7 +72,7 @@ function test() { { name: "new tab search", searchURL: base + "&hsimp=yhs-004", - run: function() { + run() { function doSearch(doc) { // Re-add the listener, and perform a search gBrowser.addProgressListener(listener); diff --git a/browser/components/search/test/head.js b/browser/components/search/test/head.js index 5fb4fe02cf02..318dd54c7897 100644 --- a/browser/components/search/test/head.js +++ b/browser/components/search/test/head.js @@ -58,11 +58,11 @@ function promiseNewEngine(basename, options = {}) { options.setAsCurrent == undefined ? true : options.setAsCurrent; info("Waiting for engine to be added: " + basename); Services.search.init({ - onInitComplete: function() { + onInitComplete() { let url = getRootDirectory(gTestPath) + basename; let current = Services.search.currentEngine; Services.search.addEngine(url, null, options.iconURL || "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); if (setAsCurrent) { Services.search.currentEngine = engine; @@ -76,7 +76,7 @@ function promiseNewEngine(basename, options = {}) { }); resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); reject(); } diff --git a/browser/components/selfsupport/SelfSupportService.js b/browser/components/selfsupport/SelfSupportService.js index bdde07a2f43f..38904cdfd395 100644 --- a/browser/components/selfsupport/SelfSupportService.js +++ b/browser/components/selfsupport/SelfSupportService.js @@ -30,7 +30,7 @@ MozSelfSupportInterface.prototype = { _window: null, - init: function(window) { + init(window) { this._window = window; }, @@ -42,34 +42,34 @@ MozSelfSupportInterface.prototype = { Preferences.set(PREF_FHR_UPLOAD_ENABLED, enabled); }, - resetPref: function(name) { + resetPref(name) { Services.prefs.clearUserPref(name); }, - resetSearchEngines: function() { + resetSearchEngines() { Services.search.restoreDefaultEngines(); Services.search.resetToOriginalDefaultEngine(); }, - getTelemetryPingList: function() { + getTelemetryPingList() { return this._wrapPromise(TelemetryArchive.promiseArchivedPingList()); }, - getTelemetryPing: function(pingId) { + getTelemetryPing(pingId) { return this._wrapPromise(TelemetryArchive.promiseArchivedPingById(pingId)); }, - getCurrentTelemetryEnvironment: function() { + getCurrentTelemetryEnvironment() { const current = TelemetryEnvironment.currentEnvironment; return new this._window.Promise(resolve => resolve(current)); }, - getCurrentTelemetrySubsessionPing: function() { + getCurrentTelemetrySubsessionPing() { const current = TelemetryController.getCurrentPingData(true); return new this._window.Promise(resolve => resolve(current)); }, - _wrapPromise: function(promise) { + _wrapPromise(promise) { return new this._window.Promise( (resolve, reject) => promise.then(resolve, reject)); }, diff --git a/browser/components/shell/content/setDesktopBackground.js b/browser/components/shell/content/setDesktopBackground.js index 094c34aa56da..e23cd912e68b 100644 --- a/browser/components/shell/content/setDesktopBackground.js +++ b/browser/components/shell/content/setDesktopBackground.js @@ -20,7 +20,7 @@ var gSetBackground = { .getService(Ci.nsIShellService); }, - load: function() + load() { this._canvas = document.getElementById("screen"); this._screenWidth = screen.width; @@ -49,7 +49,7 @@ var gSetBackground = { }, 0, this); }, - init: function(aImage) + init(aImage) { this._image = aImage; @@ -76,7 +76,7 @@ var gSetBackground = { this.updatePosition(); }, - setDesktopBackground: function() + setDesktopBackground() { if (AppConstants.platform != "macosx") { document.persist("menuPosition", "value"); @@ -95,7 +95,7 @@ var gSetBackground = { Ci.nsIShellService["BACKGROUND_" + this._position]); }, - updatePosition: function() + updatePosition() { var ctx = this._canvas.getContext("2d"); ctx.clearRect(0, 0, this._screenWidth, this._screenHeight); diff --git a/browser/components/syncedtabs/SyncedTabsDeckComponent.js b/browser/components/syncedtabs/SyncedTabsDeckComponent.js index dfbec056ca0b..bdad78e43e32 100644 --- a/browser/components/syncedtabs/SyncedTabsDeckComponent.js +++ b/browser/components/syncedtabs/SyncedTabsDeckComponent.js @@ -49,7 +49,7 @@ function SyncedTabsDeckComponent({ window: this._window, store: this._syncedTabsListStore, View: TabListView, - SyncedTabs: SyncedTabs, + SyncedTabs, clipboardHelper: Cc["@mozilla.org/widget/clipboardhelper;1"] .getService(Ci.nsIClipboardHelper), getChromeWindow: this._getChromeWindow, diff --git a/browser/components/syncedtabs/SyncedTabsDeckStore.js b/browser/components/syncedtabs/SyncedTabsDeckStore.js index ede6914c8302..eef594a51956 100644 --- a/browser/components/syncedtabs/SyncedTabsDeckStore.js +++ b/browser/components/syncedtabs/SyncedTabsDeckStore.js @@ -31,7 +31,7 @@ Object.assign(SyncedTabsDeckStore.prototype, EventEmitter.prototype, { let panels = this._panels.map(panel => { return {id: panel, selected: panel === this._selectedPanel}; }); - this.emit("change", {panels, isUpdatable: isUpdatable}); + this.emit("change", {panels, isUpdatable}); }, /** diff --git a/browser/components/syncedtabs/test/xpcshell/head.js b/browser/components/syncedtabs/test/xpcshell/head.js index af0458ea6e8b..17590109b6b4 100644 --- a/browser/components/syncedtabs/test/xpcshell/head.js +++ b/browser/components/syncedtabs/test/xpcshell/head.js @@ -15,9 +15,9 @@ do_get_profile(); // fxa needs a profile directory for storage. let window = { document: {}, location: {}, - setTimeout: setTimeout, - setInterval: setInterval, - clearTimeout: clearTimeout, + setTimeout, + setInterval, + clearTimeout, clearinterval: clearInterval }; let self = window; diff --git a/browser/components/tests/browser/browser_bug538331.js b/browser/components/tests/browser/browser_bug538331.js index fc1003413b50..1665163633fc 100644 --- a/browser/components/tests/browser/browser_bug538331.js +++ b/browser/components/tests/browser/browser_bug538331.js @@ -135,11 +135,11 @@ function test() var gWindowCatcher = { windowsOpen: 0, finishCalled: false, - start: function() { + start() { Services.ww.registerNotification(this); }, - finish: function(aFunc) { + finish(aFunc) { Services.ww.unregisterNotification(this); this.finishFunc = aFunc; if (this.windowsOpen > 0) @@ -148,7 +148,7 @@ var gWindowCatcher = { this.finishFunc(); }, - closeWindow: function(win) { + closeWindow(win) { info("window catcher closing window: " + win.document.documentURI); win.close(); this.windowsOpen--; @@ -157,11 +157,11 @@ var gWindowCatcher = { } }, - windowLoad: function(win) { + windowLoad(win) { executeSoon(this.closeWindow.bind(this, win)); }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic != "domwindowopened") return; diff --git a/browser/components/tests/unit/test_distribution.js b/browser/components/tests/unit/test_distribution.js index 86f4c40665cd..83255a083356 100644 --- a/browser/components/tests/unit/test_distribution.js +++ b/browser/components/tests/unit/test_distribution.js @@ -46,7 +46,7 @@ function installDistributionEngine() { do_get_file("data/engine-de-DE.xml").copyTo(localeDir, "engine-de-DE.xml"); Services.dirsvc.registerProvider({ - getFile: function(aProp, aPersistent) { + getFile(aProp, aPersistent) { aPersistent.value = true; if (aProp == XRE_APP_DISTRIBUTION_DIR) return distDir.clone(); diff --git a/browser/components/translation/BingTranslator.jsm b/browser/components/translation/BingTranslator.jsm index fc1cc942a14a..cdaec46ff9ef 100644 --- a/browser/components/translation/BingTranslator.jsm +++ b/browser/components/translation/BingTranslator.jsm @@ -58,7 +58,7 @@ this.BingTranslator.prototype = { * @returns {Promise} A promise that will resolve when the translation * task is finished. */ - translate: function() { + translate() { return Task.spawn(function *() { let currentIndex = 0; this._onFinishedDeferred = Promise.defer(); @@ -98,7 +98,7 @@ this.BingTranslator.prototype = { * Resets the expiration time of the current token, in order to * force the token manager to ask for a new token during the next request. */ - _resetToken : function() { + _resetToken() { // Force the token manager to get update token BingTokenManager._currentExpiryTime = 0; }, @@ -111,7 +111,7 @@ this.BingTranslator.prototype = { * * @param request The BingRequest sent to the server. */ - _chunkCompleted: function(bingRequest) { + _chunkCompleted(bingRequest) { if (this._parseChunkResult(bingRequest)) { this._partialSuccess = true; // Count the number of characters successfully translated. @@ -131,7 +131,7 @@ this.BingTranslator.prototype = { * * @param aError [optional] The XHR object of the request that failed. */ - _chunkFailed: function(aError) { + _chunkFailed(aError) { if (aError instanceof Ci.nsIXMLHttpRequest && [400, 401].indexOf(aError.status) != -1) { let body = aError.responseText; @@ -148,7 +148,7 @@ this.BingTranslator.prototype = { * This function handles resolving the promise * returned by the public `translate()` method when all chunks are completed. */ - _checkIfFinished: function() { + _checkIfFinished() { // Check if all pending requests have been // completed and then resolves the promise. // If at least one chunk was successful, the @@ -177,7 +177,7 @@ this.BingTranslator.prototype = { * @param request The request sent to the server. * @returns boolean True if parsing of this chunk was successful. */ - _parseChunkResult: function(bingRequest) { + _parseChunkResult(bingRequest) { let results; try { let doc = bingRequest.networkRequest.responseXML; @@ -220,7 +220,7 @@ this.BingTranslator.prototype = { * @param startIndex What is the index, in the roots list, that the * chunk should start. */ - _generateNextTranslationRequest: function(startIndex) { + _generateNextTranslationRequest(startIndex) { let currentDataSize = 0; let currentChunks = 0; let output = []; @@ -285,7 +285,7 @@ BingRequest.prototype = { /** * Initiates the request */ - fireRequest: function() { + fireRequest() { return Task.spawn(function *() { // Prepare authentication. let token = yield BingTokenManager.getToken(); @@ -324,11 +324,11 @@ BingRequest.prototype = { onLoad: (function(responseText, xhr) { deferred.resolve(this); }).bind(this), - onError: function(e, responseText, xhr) { + onError(e, responseText, xhr) { deferred.reject(xhr); }, postData: requestString, - headers: headers + headers }; // Fire the request. @@ -358,7 +358,7 @@ var BingTokenManager = { * can be the same one used in the past if it is still * valid. */ - getToken: function() { + getToken() { if (this._pendingRequest) { return this._pendingRequest; } @@ -378,7 +378,7 @@ var BingTokenManager = { * @returns {Promise} A promise that resolves with the token * string once it is obtained. */ - _getNewToken: function() { + _getNewToken() { let url = getUrlParam("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13", "browser.translation.bing.authURL"); let params = [ @@ -392,7 +392,7 @@ var BingTokenManager = { let deferred = Promise.defer(); let options = { - onLoad: function(responseText, xhr) { + onLoad(responseText, xhr) { BingTokenManager._pendingRequest = null; try { let json = JSON.parse(responseText); @@ -411,7 +411,7 @@ var BingTokenManager = { deferred.reject(e); } }, - onError: function(e, responseText, xhr) { + onError(e, responseText, xhr) { BingTokenManager._pendingRequest = null; deferred.reject(e); }, diff --git a/browser/components/translation/LanguageDetector.jsm b/browser/components/translation/LanguageDetector.jsm index a65d6eda124a..e75f777a1f26 100644 --- a/browser/components/translation/LanguageDetector.jsm +++ b/browser/components/translation/LanguageDetector.jsm @@ -134,7 +134,7 @@ this.LanguageDetector = { * entry with the languge code 'un', indicating the percent of * the text which is unknown. */ - detectLanguage: function(aParams) { + detectLanguage(aParams) { if (typeof aParams == "string") aParams = { text: aParams }; diff --git a/browser/components/translation/Translation.jsm b/browser/components/translation/Translation.jsm index c2591b65ed67..9dc29930f58c 100644 --- a/browser/components/translation/Translation.jsm +++ b/browser/components/translation/Translation.jsm @@ -41,7 +41,7 @@ this.Translation = { return this._defaultTargetLanguage; }, - documentStateReceived: function(aBrowser, aData) { + documentStateReceived(aBrowser, aData) { if (aData.state == this.STATE_OFFER) { if (aData.detectedLanguage == this.defaultTargetLanguage) { // Detected language is the same as the user's locale. @@ -78,7 +78,7 @@ this.Translation = { trUI.showTranslationInfoBar(); }, - openProviderAttribution: function() { + openProviderAttribution() { let attribution = this.supportedEngines[this.translationEngine]; Cu.import("resource:///modules/RecentWindow.jsm"); RecentWindow.getMostRecentBrowserWindow().openUILinkIn(attribution, "tab"); @@ -138,7 +138,7 @@ TranslationUI.prototype = { aBrowser.messageManager.addMessageListener("Translation:Finished", this); this._browser = aBrowser; }, - translate: function(aFrom, aTo) { + translate(aFrom, aTo) { if (aFrom == aTo || (this.state == Translation.STATE_TRANSLATED && this.translatedFrom == aFrom && this.translatedTo == aTo)) { @@ -166,7 +166,7 @@ TranslationUI.prototype = { ); }, - showURLBarIcon: function() { + showURLBarIcon() { let chromeWin = this.browser.ownerGlobal; let PopupNotifications = chromeWin.PopupNotifications; let removeId = this.originalShown ? "translated" : "translate"; @@ -214,14 +214,14 @@ TranslationUI.prototype = { }, originalShown: true, - showOriginalContent: function() { + showOriginalContent() { this.originalShown = true; this.showURLBarIcon(); this.browser.messageManager.sendAsyncMessage("Translation:ShowOriginal"); TranslationTelemetry.recordShowOriginalContent(); }, - showTranslatedContent: function() { + showTranslatedContent() { this.originalShown = false; this.showURLBarIcon(); this.browser.messageManager.sendAsyncMessage("Translation:ShowTranslation"); @@ -231,7 +231,7 @@ TranslationUI.prototype = { return this.browser.ownerGlobal.gBrowser.getNotificationBox(this.browser); }, - showTranslationInfoBar: function() { + showTranslationInfoBar() { let notificationBox = this.notificationBox; let notif = notificationBox.appendNotification("", "translation", null, notificationBox.PRIORITY_INFO_HIGH); @@ -239,7 +239,7 @@ TranslationUI.prototype = { return notif; }, - shouldShowInfoBar: function(aURI) { + shouldShowInfoBar(aURI) { // Never show the infobar automatically while the translation // service is temporarily unavailable. if (Translation.serviceUnavailable) @@ -263,7 +263,7 @@ TranslationUI.prototype = { return true; }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Translation:Finished": if (msg.data.success) { @@ -284,7 +284,7 @@ TranslationUI.prototype = { } }, - infobarClosed: function() { + infobarClosed() { if (this.state == Translation.STATE_OFFER) TranslationTelemetry.recordDeniedTranslationOffer(); } @@ -298,7 +298,7 @@ TranslationUI.prototype = { */ this.TranslationTelemetry = { - init: function() { + init() { // Constructing histograms. const plain = (id) => Services.telemetry.getHistogramById(id); const keyed = (id) => Services.telemetry.getKeyedHistogramById(id); @@ -326,7 +326,7 @@ this.TranslationTelemetry = { * @param language * The language of the page. */ - recordTranslationOpportunity: function(language) { + recordTranslationOpportunity(language) { return this._recordOpportunity(language, true); }, @@ -337,7 +337,7 @@ this.TranslationTelemetry = { * @param language * The language of the page. */ - recordMissedTranslationOpportunity: function(language) { + recordMissedTranslationOpportunity(language) { return this._recordOpportunity(language, false); }, @@ -351,7 +351,7 @@ this.TranslationTelemetry = { * These translation opportunities should still be recorded in addition to * recording the automatic rejection of the offer. */ - recordAutoRejectedTranslationOffer: function() { + recordAutoRejectedTranslationOffer() { if (!this._canRecord) return; this.HISTOGRAMS.AUTO_REJECTED().add(); }, @@ -365,7 +365,7 @@ this.TranslationTelemetry = { * @param numCharacters * The number of characters that were translated */ - recordTranslation: function(langFrom, langTo, numCharacters) { + recordTranslation(langFrom, langTo, numCharacters) { if (!this._canRecord) return; this.HISTOGRAMS.PAGES().add(); this.HISTOGRAMS.PAGES_BY_LANG().add(langFrom + " -> " + langTo); @@ -384,7 +384,7 @@ this.TranslationTelemetry = { * the user has manually adjusted the detected language false should * be passed. */ - recordDetectedLanguageChange: function(beforeFirstTranslation) { + recordDetectedLanguageChange(beforeFirstTranslation) { if (!this._canRecord) return; this.HISTOGRAMS.DETECTION_CHANGES().add(beforeFirstTranslation); }, @@ -394,7 +394,7 @@ this.TranslationTelemetry = { * only be called when actually executing a translation, not every time the * user changes in the language in the UI. */ - recordTargetLanguageChange: function() { + recordTargetLanguageChange() { if (!this._canRecord) return; this.HISTOGRAMS.TARGET_CHANGES().add(); }, @@ -402,7 +402,7 @@ this.TranslationTelemetry = { /** * Record a denied translation offer. */ - recordDeniedTranslationOffer: function() { + recordDeniedTranslationOffer() { if (!this._canRecord) return; this.HISTOGRAMS.DENIED().add(); }, @@ -410,7 +410,7 @@ this.TranslationTelemetry = { /** * Record a "Show Original" command use. */ - recordShowOriginalContent: function() { + recordShowOriginalContent() { if (!this._canRecord) return; this.HISTOGRAMS.SHOW_ORIGINAL().add(); }, @@ -418,7 +418,7 @@ this.TranslationTelemetry = { /** * Record the state of translation preferences. */ - recordPreferences: function() { + recordPreferences() { if (!this._canRecord) return; if (Services.prefs.getBoolPref(TRANSLATION_PREF_SHOWUI)) { this.HISTOGRAMS.SHOW_UI().add(1); @@ -428,7 +428,7 @@ this.TranslationTelemetry = { } }, - _recordOpportunity: function(language, success) { + _recordOpportunity(language, success) { if (!this._canRecord) return; this.HISTOGRAMS.OPPORTUNITIES().add(success); this.HISTOGRAMS.OPPORTUNITIES_BY_LANG().add(language, success); @@ -438,7 +438,7 @@ this.TranslationTelemetry = { * A shortcut for reading the telemetry preference. * */ - _canRecord: function() { + _canRecord() { return Services.prefs.getBoolPref("toolkit.telemetry.enabled"); } }; diff --git a/browser/components/translation/TranslationContentHandler.jsm b/browser/components/translation/TranslationContentHandler.jsm index 3b0d59dddd40..62376d4aa5ed 100644 --- a/browser/components/translation/TranslationContentHandler.jsm +++ b/browser/components/translation/TranslationContentHandler.jsm @@ -31,7 +31,7 @@ this.TranslationContentHandler = function(global, docShell) { } TranslationContentHandler.prototype = { - handleEvent: function(aEvent) { + handleEvent(aEvent) { // We are only listening to pageshow events. let target = aEvent.target; @@ -61,7 +61,7 @@ TranslationContentHandler.prototype = { }, /* nsIWebProgressListener implementation */ - onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { if (!aWebProgress.isTopLevel || !(aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) || !this.global.content) @@ -108,15 +108,15 @@ TranslationContentHandler.prototype = { }, // Unused methods. - onProgressChange: function() {}, - onLocationChange: function() {}, - onStatusChange: function() {}, - onSecurityChange: function() {}, + onProgressChange() {}, + onLocationChange() {}, + onStatusChange() {}, + onSecurityChange() {}, QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference]), - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Translation:TranslateDocument": { diff --git a/browser/components/translation/TranslationDocument.jsm b/browser/components/translation/TranslationDocument.jsm index 058d07a498cf..c754251046bd 100644 --- a/browser/components/translation/TranslationDocument.jsm +++ b/browser/components/translation/TranslationDocument.jsm @@ -42,7 +42,7 @@ this.TranslationDocument.prototype = { * * @param document The document to be translated */ - _init: function(document) { + _init(document) { let window = document.defaultView; let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -94,7 +94,7 @@ this.TranslationDocument.prototype = { * * @returns A TranslationItem object. */ - _createItemForNode: function(node, id, isRoot) { + _createItemForNode(node, id, isRoot) { if (this.itemsMap.has(node)) { return this.itemsMap.get(node); } @@ -129,7 +129,7 @@ this.TranslationDocument.prototype = { * * @returns A string representation of the TranslationItem. */ - generateTextForItem: function(item) { + generateTextForItem(item) { if (item.original) { return regenerateTextFromOriginalHelper(item); } @@ -187,7 +187,7 @@ this.TranslationDocument.prototype = { * Changes the document to display its translated * content. */ - showTranslation: function() { + showTranslation() { this.originalShown = false; this._swapDocumentContent("translation"); }, @@ -196,7 +196,7 @@ this.TranslationDocument.prototype = { * Changes the document to display its original * content. */ - showOriginal: function() { + showOriginal() { this.originalShown = true; this._swapDocumentContent("original"); }, @@ -208,7 +208,7 @@ this.TranslationDocument.prototype = { * @param target A string that is either "translation" * or "original". */ - _swapDocumentContent: function(target) { + _swapDocumentContent(target) { Task.spawn(function *() { // Let the event loop breath on every 100 nodes // that are replaced. @@ -274,7 +274,7 @@ TranslationItem.prototype = { isRoot: false, isSimpleRoot: false, - toString: function() { + toString() { let rootType = ""; if (this.isRoot) { if (this.isSimpleRoot) { @@ -305,7 +305,7 @@ TranslationItem.prototype = { * @param result A string with the textual result received from the server, * which can be plain-text or a serialized HTML doc. */ - parseResult: function(result) { + parseResult(result) { if (this.isSimpleRoot) { this.translation = [result]; return; @@ -325,7 +325,7 @@ TranslationItem.prototype = { * @returns A TranslationItem with the given id, or null if * it was not found. */ - getChildById: function(id) { + getChildById(id) { for (let child of this.children) { if (("n" + child.id) == id) { return child; @@ -341,7 +341,7 @@ TranslationItem.prototype = { * @param target A string that is either "translation" * or "original". */ - swapText: function(target) { + swapText(target) { swapTextForItem(this, target); } }; @@ -354,7 +354,7 @@ TranslationItem.prototype = { * for correct positioning and spliting of text nodes. */ const TranslationItem_NodePlaceholder = { - toString: function() { + toString() { return "[object TranslationItem_NodePlaceholder]"; } }; diff --git a/browser/components/translation/YandexTranslator.jsm b/browser/components/translation/YandexTranslator.jsm index ab92e09625c9..11206d91d48a 100644 --- a/browser/components/translation/YandexTranslator.jsm +++ b/browser/components/translation/YandexTranslator.jsm @@ -76,7 +76,7 @@ this.YandexTranslator.prototype = { * @returns {Promise} A promise that will resolve when the translation * task is finished. */ - translate: function() { + translate() { return Task.spawn(function *() { let currentIndex = 0; this._onFinishedDeferred = Promise.defer(); @@ -120,7 +120,7 @@ this.YandexTranslator.prototype = { * * @param request The YandexRequest sent to the server */ - _chunkCompleted: function(yandexRequest) { + _chunkCompleted(yandexRequest) { if (this._parseChunkResult(yandexRequest)) { this._partialSuccess = true; // Count the number of characters successfully translated. @@ -140,7 +140,7 @@ this.YandexTranslator.prototype = { * * @param aError [optional] The XHR object of the request that failed. */ - _chunkFailed: function(aError) { + _chunkFailed(aError) { if (aError instanceof Ci.nsIXMLHttpRequest) { let body = aError.responseText; let json = { code: 0 }; @@ -160,7 +160,7 @@ this.YandexTranslator.prototype = { * This function handles resolving the promise * returned by the public `translate()` method when all chunks are completed. */ - _checkIfFinished: function() { + _checkIfFinished() { // Check if all pending requests have been // completed and then resolves the promise. // If at least one chunk was successful, the @@ -188,7 +188,7 @@ this.YandexTranslator.prototype = { * @param request The request sent to the server. * @returns boolean True if parsing of this chunk was successful. */ - _parseChunkResult: function(yandexRequest) { + _parseChunkResult(yandexRequest) { let results; try { let result = JSON.parse(yandexRequest.networkRequest.responseText); @@ -228,7 +228,7 @@ this.YandexTranslator.prototype = { * @param startIndex What is the index, in the roots list, that the * chunk should start. */ - _generateNextTranslationRequest: function(startIndex) { + _generateNextTranslationRequest(startIndex) { let currentDataSize = 0; let currentChunks = 0; let output = []; @@ -292,7 +292,7 @@ YandexRequest.prototype = { /** * Initiates the request */ - fireRequest: function() { + fireRequest() { return Task.spawn(function *() { // Prepare URL. let url = getUrlParam("https://translate.yandex.net/api/v1.5/tr.json/translate", @@ -317,7 +317,7 @@ YandexRequest.prototype = { onLoad: (function(responseText, xhr) { deferred.resolve(this); }).bind(this), - onError: function(e, responseText, xhr) { + onError(e, responseText, xhr) { deferred.reject(xhr); }, postData: params diff --git a/browser/components/translation/test/browser_translation_infobar.js b/browser/components/translation/test/browser_translation_infobar.js index 4dbdcbee4c3c..9b6917b3fe31 100644 --- a/browser/components/translation/test/browser_translation_infobar.js +++ b/browser/components/translation/test/browser_translation_infobar.js @@ -33,23 +33,23 @@ function waitForCondition(condition, nextTest, errorMsg) { } var TranslationStub = { - translate: function(aFrom, aTo) { + translate(aFrom, aTo) { this.state = Translation.STATE_TRANSLATING; this.translatedFrom = aFrom; this.translatedTo = aTo; }, - _reset: function() { + _reset() { this.translatedFrom = ""; this.translatedTo = ""; }, - failTranslation: function() { + failTranslation() { this.state = Translation.STATE_ERROR; this._reset(); }, - finishTranslation: function() { + finishTranslation() { this.showTranslatedContent(); this.state = Translation.STATE_TRANSLATED; this._reset(); diff --git a/browser/components/translation/test/browser_translation_telemetry.js b/browser/components/translation/test/browser_translation_telemetry.js index 2c89c283f0b7..4e3e08925e9c 100644 --- a/browser/components/translation/test/browser_translation_telemetry.js +++ b/browser/components/translation/test/browser_translation_telemetry.js @@ -24,14 +24,14 @@ var MetricsChecker = { DETECT_LANG : Services.telemetry.getHistogramById("SHOULD_AUTO_DETECT_LANGUAGE"), }, - reset: function() { + reset() { for (let i of Object.keys(this.HISTOGRAMS)) { this.HISTOGRAMS[i].clear(); } this.updateMetrics(); }, - updateMetrics: function() { + updateMetrics() { this._metrics = { opportunitiesCount: this.HISTOGRAMS.OPPORTUNITIES.snapshot().sum || 0, pageCount: this.HISTOGRAMS.PAGES.snapshot().sum || 0, @@ -65,7 +65,7 @@ var MetricsChecker = { /** * A recurrent loop for making assertions about collected metrics. */ - _assertionLoop: function(prevMetrics, metrics, additions) { + _assertionLoop(prevMetrics, metrics, additions) { for (let metric of Object.keys(additions)) { let addition = additions[metric]; // Allows nesting metrics. Useful for keyed histograms. @@ -77,7 +77,7 @@ var MetricsChecker = { } }, - checkAdditions: function(additions) { + checkAdditions(additions) { let prevMetrics = this._metrics; this.updateMetrics(); this._assertionLoop(prevMetrics, this._metrics, additions); diff --git a/browser/components/uitour/UITour-lib.js b/browser/components/uitour/UITour-lib.js index 40c1a82b4d99..9b7775864988 100644 --- a/browser/components/uitour/UITour-lib.js +++ b/browser/components/uitour/UITour-lib.js @@ -27,7 +27,7 @@ if (typeof Mozilla == 'undefined') { var event = new CustomEvent('mozUITour', { bubbles: true, detail: { - action: action, + action, data: data || {} } }); @@ -94,19 +94,19 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.registerPageID = function(pageID) { _sendEvent('registerPageID', { - pageID: pageID + pageID }); }; Mozilla.UITour.showHeartbeat = function(message, thankyouMessage, flowId, engagementURL, learnMoreLabel, learnMoreURL, options) { var args = { - message: message, - thankyouMessage: thankyouMessage, - flowId: flowId, - engagementURL: engagementURL, - learnMoreLabel: learnMoreLabel, - learnMoreURL: learnMoreURL, + message, + thankyouMessage, + flowId, + engagementURL, + learnMoreLabel, + learnMoreURL, }; if (options) { @@ -123,8 +123,8 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.showHighlight = function(target, effect) { _sendEvent('showHighlight', { - target: target, - effect: effect + target, + effect }); }; @@ -152,13 +152,13 @@ if (typeof Mozilla == 'undefined') { targetCallbackID = _waitForCallback(options.targetCallback); _sendEvent('showInfo', { - target: target, - title: title, - text: text, - icon: icon, + target, + title, + text, + icon, buttons: buttonData, - closeButtonCallbackID: closeButtonCallbackID, - targetCallbackID: targetCallbackID + closeButtonCallbackID, + targetCallbackID }); }; @@ -209,14 +209,14 @@ if (typeof Mozilla == 'undefined') { showCallbackID = _waitForCallback(callback); _sendEvent('showMenu', { - name: name, - showCallbackID: showCallbackID, + name, + showCallbackID, }); }; Mozilla.UITour.hideMenu = function(name) { _sendEvent('hideMenu', { - name: name + name }); }; @@ -260,34 +260,34 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.addNavBarWidget = function(name, callback) { _sendEvent('addNavBarWidget', { - name: name, + name, callbackID: _waitForCallback(callback), }); }; Mozilla.UITour.setDefaultSearchEngine = function(identifier) { _sendEvent('setDefaultSearchEngine', { - identifier: identifier, + identifier, }); }; Mozilla.UITour.setTreatmentTag = function(name, value) { _sendEvent('setTreatmentTag', { - name: name, - value: value + name, + value }); }; Mozilla.UITour.getTreatmentTag = function(name, callback) { _sendEvent('getTreatmentTag', { - name: name, + name, callbackID: _waitForCallback(callback) }); }; Mozilla.UITour.setSearchTerm = function(term) { _sendEvent('setSearchTerm', { - term: term + term }); }; @@ -307,7 +307,7 @@ if (typeof Mozilla == 'undefined') { Mozilla.UITour.openPreferences = function(pane) { _sendEvent('openPreferences', { - pane: pane + pane }); }; diff --git a/browser/components/uitour/UITour.jsm b/browser/components/uitour/UITour.jsm index 2e25fdd458f4..eeb73ade9eab 100644 --- a/browser/components/uitour/UITour.jsm +++ b/browser/components/uitour/UITour.jsm @@ -214,7 +214,7 @@ this.UITour = { ["webide", {query: "#webide-button"}], ]), - init: function() { + init() { log.debug("Initializing UITour"); // Lazy getter is initialized here so it can be replicated any time // in a test. @@ -243,7 +243,7 @@ this.UITour = { }, {})); }, - restoreSeenPageIDs: function() { + restoreSeenPageIDs() { delete this.seenPageIDs; if (UITelemetry.enabled) { @@ -276,7 +276,7 @@ this.UITour = { return this.seenPageIDs; }, - addSeenPageID: function(aPageID) { + addSeenPageID(aPageID) { if (!UITelemetry.enabled) return; @@ -287,7 +287,7 @@ this.UITour = { this.persistSeenIDs(); }, - persistSeenIDs: function() { + persistSeenIDs() { if (this.seenPageIDs.size === 0) { Services.prefs.clearUserPref(PREF_SEENPAGEIDS); return; @@ -303,7 +303,7 @@ this.UITour = { return this._readerViewTriggerRegEx = new RegExp(readerViewUITourTrigger, "i"); }, - onLocationChange: function(aLocation) { + onLocationChange(aLocation) { // The ReaderView tour page is expected to run in Reader View, // which disables JavaScript on the page. To get around that, we // automatically start a pre-defined tour on page load (for hysterical @@ -314,7 +314,7 @@ this.UITour = { } }, - onPageEvent: function(aMessage, aEvent) { + onPageEvent(aMessage, aEvent) { let browser = aMessage.target; let window = browser.ownerGlobal; @@ -620,7 +620,7 @@ this.UITour = { value = Services.prefs.getComplexValue("browser.uitour.treatment." + name, Ci.nsISupportsString).data; } catch (ex) {} - this.sendPageCallback(messageManager, data.callbackID, { value: value }); + this.sendPageCallback(messageManager, data.callbackID, { value }); break; } @@ -708,7 +708,7 @@ this.UITour = { window.addEventListener("SSWindowClosing", this); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { log.debug("handleEvent: type =", aEvent.type, "event =", aEvent); switch (aEvent.type) { case "TabSelect": { @@ -734,7 +734,7 @@ this.UITour = { } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { log.debug("observe: aTopic =", aTopic); switch (aTopic) { // The browser message manager is disconnected when the is @@ -769,7 +769,7 @@ this.UITour = { // additional utm_* URL params that should be appended, validate and append // them to the passed URLSearchParams object. Returns true if the params // were validated and appended, and false if the request should be ignored. - _populateCampaignParams: function(urlSearchParams, extraURLCampaignParams) { + _populateCampaignParams(urlSearchParams, extraURLCampaignParams) { // We are extra paranoid about what params we allow to be appended. if (typeof extraURLCampaignParams == "undefined") { // no params, so it's all good. @@ -811,12 +811,12 @@ this.UITour = { return true; }, - setTelemetryBucket: function(aPageID) { + setTelemetryBucket(aPageID) { let bucket = BUCKET_NAME + BrowserUITelemetry.BUCKET_SEPARATOR + aPageID; BrowserUITelemetry.setBucket(bucket); }, - setExpiringTelemetryBucket: function(aPageID, aType) { + setExpiringTelemetryBucket(aPageID, aType) { let bucket = BUCKET_NAME + BrowserUITelemetry.BUCKET_SEPARATOR + aPageID + BrowserUITelemetry.BUCKET_SEPARATOR + aType; @@ -826,7 +826,7 @@ this.UITour = { // This is registered with UITelemetry by BrowserUITelemetry, so that UITour // can remain lazy-loaded on-demand. - getTelemetry: function() { + getTelemetry() { return { seenPageIDs: [...this.seenPageIDs.keys()], }; @@ -835,7 +835,7 @@ this.UITour = { /** * Tear down a tour from a tab e.g. upon switching/closing tabs. */ - teardownTourForBrowser: function(aWindow, aBrowser, aTourPageClosing = false) { + teardownTourForBrowser(aWindow, aBrowser, aTourPageClosing = false) { log.debug("teardownTourForBrowser: aBrowser = ", aBrowser, aTourPageClosing); if (this.pageIDSourceBrowsers.has(aBrowser)) { @@ -873,7 +873,7 @@ this.UITour = { /** * Tear down all tours for a ChromeWindow. */ - teardownTourForWindow: function(aWindow) { + teardownTourForWindow(aWindow) { log.debug("teardownTourForWindow"); aWindow.gBrowser.tabContainer.removeEventListener("TabSelect", this); aWindow.removeEventListener("SSWindowClosing", this); @@ -892,7 +892,7 @@ this.UITour = { }, // This function is copied to UITourListener. - isSafeScheme: function(aURI) { + isSafeScheme(aURI) { let allowedSchemes = new Set(["https", "about"]); if (!Services.prefs.getBoolPref("browser.uitour.requireSecure")) allowedSchemes.add("http"); @@ -905,7 +905,7 @@ this.UITour = { return true; }, - resolveURL: function(aBrowser, aURL) { + resolveURL(aBrowser, aURL) { try { let uri = Services.io.newURI(aURL, null, aBrowser.currentURI); @@ -918,20 +918,20 @@ this.UITour = { return null; }, - sendPageCallback: function(aMessageManager, aCallbackID, aData = {}) { + sendPageCallback(aMessageManager, aCallbackID, aData = {}) { let detail = {data: aData, callbackID: aCallbackID}; log.debug("sendPageCallback", detail); aMessageManager.sendAsyncMessage("UITour:SendPageCallback", detail); }, - isElementVisible: function(aElement) { + isElementVisible(aElement) { let targetStyle = aElement.ownerGlobal.getComputedStyle(aElement); return !aElement.ownerDocument.hidden && targetStyle.display != "none" && targetStyle.visibility == "visible"; }, - getTarget: function(aWindow, aTargetName, aSticky = false) { + getTarget(aWindow, aTargetName, aSticky = false) { log.debug("getTarget:", aTargetName); let deferred = Promise.defer(); if (typeof aTargetName != "string" || !aTargetName) { @@ -966,7 +966,7 @@ this.UITour = { infoPanelOffsetX: targetObject.infoPanelOffsetX, infoPanelOffsetY: targetObject.infoPanelOffsetY, infoPanelPosition: targetObject.infoPanelPosition, - node: node, + node, removeTargetListener: targetObject.removeTargetListener, targetName: aTargetName, widgetName: targetObject.widgetName, @@ -976,7 +976,7 @@ this.UITour = { return deferred.promise; }, - targetIsInAppMenu: function(aTarget) { + targetIsInAppMenu(aTarget) { let placement = CustomizableUI.getPlacementOfWidget(aTarget.widgetName || aTarget.node.id); if (placement && placement.area == CustomizableUI.AREA_PANEL) { return true; @@ -997,7 +997,7 @@ this.UITour = { * Called before opening or after closing a highlight or info panel to see if * we need to open or close the appMenu to see the annotation's anchor. */ - _setAppMenuStateForAnnotation: function(aWindow, aAnnotationType, aShouldOpenForHighlight, aCallback = null) { + _setAppMenuStateForAnnotation(aWindow, aAnnotationType, aShouldOpenForHighlight, aCallback = null) { log.debug("_setAppMenuStateForAnnotation:", aAnnotationType); log.debug("_setAppMenuStateForAnnotation: Menu is expected to be:", aShouldOpenForHighlight ? "open" : "closed"); @@ -1037,14 +1037,14 @@ this.UITour = { }, - previewTheme: function(aTheme) { + previewTheme(aTheme) { let origin = Services.prefs.getCharPref("browser.uitour.themeOrigin"); let data = LightweightThemeManager.parseTheme(aTheme, origin); if (data) LightweightThemeManager.previewTheme(data); }, - resetTheme: function() { + resetTheme() { LightweightThemeManager.resetPreview(); }, @@ -1387,7 +1387,7 @@ this.UITour = { * @param {Node} aAnchor The element that's supposed to be the anchor * @type {Node} */ - _correctAnchor: function(aAnchor) { + _correctAnchor(aAnchor) { // If the target is in the overflow panel, just return the overflow button. if (aAnchor.getAttribute("overflowedItem")) { let doc = aAnchor.ownerDocument; @@ -1407,7 +1407,7 @@ this.UITour = { * @param aEffect (optional) The effect to use from UITour.highlightEffects or "none". * @see UITour.highlightEffects */ - showHighlight: function(aChromeWindow, aTarget, aEffect = "none") { + showHighlight(aChromeWindow, aTarget, aEffect = "none") { function showHighlightPanel() { let highlighter = aChromeWindow.document.getElementById("UITourHighlight"); @@ -1478,7 +1478,7 @@ this.UITour = { showHighlightPanel.bind(this)); }, - hideHighlight: function(aWindow) { + hideHighlight(aWindow) { let highlighter = aWindow.document.getElementById("UITourHighlight"); this._removeAnnotationPanelMutationObserver(highlighter.parentElement); highlighter.parentElement.hidePopup(); @@ -1617,7 +1617,7 @@ this.UITour = { return tooltip.getAttribute("targetName") == aTargetName && tooltip.state != "closed"; }, - hideInfo: function(aWindow) { + hideInfo(aWindow) { let document = aWindow.document; let tooltip = document.getElementById("UITourTooltip"); @@ -1630,7 +1630,7 @@ this.UITour = { tooltipButtons.firstChild.remove(); }, - showMenu: function(aWindow, aMenuName, aOpenCallback = null) { + showMenu(aWindow, aMenuName, aOpenCallback = null) { log.debug("showMenu:", aMenuName); function openMenuButton(aMenuBtn) { if (!aMenuBtn || !aMenuBtn.boxObject || aMenuBtn.open) { @@ -1731,7 +1731,7 @@ this.UITour = { } }, - hideMenu: function(aWindow, aMenuName) { + hideMenu(aWindow, aMenuName) { log.debug("hideMenu:", aMenuName); function closeMenuButton(aMenuBtn) { if (aMenuBtn && aMenuBtn.boxObject) @@ -1749,11 +1749,11 @@ this.UITour = { } }, - showNewTab: function(aWindow, aBrowser) { + showNewTab(aWindow, aBrowser) { aWindow.openLinkIn("about:newtab", "current", {targetBrowser: aBrowser}); }, - hideAnnotationsForPanel: function(aEvent, aTargetPositionCallback) { + hideAnnotationsForPanel(aEvent, aTargetPositionCallback) { let win = aEvent.target.ownerGlobal; let annotationElements = new Map([ // [annotationElement (panel), method to hide the annotation] @@ -1778,7 +1778,7 @@ this.UITour = { UITour.appMenuOpenForAnnotation.clear(); }, - hideAppMenuAnnotations: function(aEvent) { + hideAppMenuAnnotations(aEvent) { UITour.hideAnnotationsForPanel(aEvent, UITour.targetIsInAppMenu); }, @@ -1788,13 +1788,13 @@ this.UITour = { }); }, - onPanelHidden: function(aEvent) { + onPanelHidden(aEvent) { aEvent.target.removeAttribute("noautohide"); UITour.recreatePopup(aEvent.target); UITour.clearAvailableTargetsCache(); }, - recreatePopup: function(aPanel) { + recreatePopup(aPanel) { // After changing popup attributes that relate to how the native widget is created // (e.g. @noautohide) we need to re-create the frame/widget for it to take effect. if (aPanel.hidden) { @@ -1808,7 +1808,7 @@ this.UITour = { aPanel.hidden = false; }, - getConfiguration: function(aMessageManager, aWindow, aConfiguration, aCallbackID) { + getConfiguration(aMessageManager, aWindow, aConfiguration, aCallbackID) { switch (aConfiguration) { case "appinfo": let props = ["defaultUpdateChannel", "version"]; @@ -1888,7 +1888,7 @@ this.UITour = { } }, - setConfiguration: function(aWindow, aConfiguration, aValue) { + setConfiguration(aWindow, aConfiguration, aValue) { switch (aConfiguration) { case "defaultBrowser": // Ignore aValue in this case because the default browser can only @@ -1906,7 +1906,7 @@ this.UITour = { } }, - getAvailableTargets: function(aMessageManager, aChromeWindow, aCallbackID) { + getAvailableTargets(aMessageManager, aChromeWindow, aCallbackID) { Task.spawn(function*() { let window = aChromeWindow; let data = this.availableTargetsCache.get(window); @@ -1941,7 +1941,7 @@ this.UITour = { }); }, - startSubTour: function(aFeature) { + startSubTour(aFeature) { if (aFeature != "string") { log.error("startSubTour: No feature option specified"); return; @@ -1955,7 +1955,7 @@ this.UITour = { } }, - addNavBarWidget: function(aTarget, aMessageManager, aCallbackID) { + addNavBarWidget(aTarget, aMessageManager, aCallbackID) { if (aTarget.node) { log.error("addNavBarWidget: can't add a widget already present:", aTarget); return; @@ -1973,7 +1973,7 @@ this.UITour = { this.sendPageCallback(aMessageManager, aCallbackID); }, - _addAnnotationPanelMutationObserver: function(aPanelEl) { + _addAnnotationPanelMutationObserver(aPanelEl) { if (AppConstants.platform == "linux") { let observer = this._annotationPanelMutationObservers.get(aPanelEl); if (observer) { @@ -1990,7 +1990,7 @@ this.UITour = { } }, - _removeAnnotationPanelMutationObserver: function(aPanelEl) { + _removeAnnotationPanelMutationObserver(aPanelEl) { if (AppConstants.platform == "linux") { let observer = this._annotationPanelMutationObservers.get(aPanelEl); if (observer) { @@ -2005,7 +2005,7 @@ this.UITour = { * nsXULPopupManager::PopupResized and lead to incorrect width and height attributes getting * set on the panel. */ - _annotationMutationCallback: function(aMutations) { + _annotationMutationCallback(aMutations) { for (let mutation of aMutations) { // Remove both attributes at once and ignore remaining mutations to be proccessed. mutation.target.removeAttribute("width"); @@ -2055,7 +2055,7 @@ this.UITour = { } let detail = { event: eventName, - params: params, + params, }; messageManager.sendAsyncMessage("UITour:SendPageNotification", detail); } @@ -2096,7 +2096,7 @@ this.UITour.init(); * Public API to be called by the UITour code */ const UITourHealthReport = { - recordTreatmentTag: function(tag, value) { + recordTreatmentTag(tag, value) { return TelemetryController.submitExternalPing("uitour-tag", { version: 1, diff --git a/browser/components/uitour/content-UITour.js b/browser/components/uitour/content-UITour.js index f5646486f653..f7ef7d371a59 100644 --- a/browser/components/uitour/content-UITour.js +++ b/browser/components/uitour/content-UITour.js @@ -8,7 +8,7 @@ const PREF_TEST_WHITELIST = "browser.uitour.testingOrigins"; const UITOUR_PERMISSION = "uitour"; var UITourListener = { - handleEvent: function(event) { + handleEvent(event) { if (!Services.prefs.getBoolPref("browser.uitour.enabled")) { return; } @@ -24,7 +24,7 @@ var UITourListener = { }); }, - isTestingOrigin: function(aURI) { + isTestingOrigin(aURI) { if (Services.prefs.getPrefType(PREF_TEST_WHITELIST) != Services.prefs.PREF_STRING) { return false; } @@ -44,7 +44,7 @@ var UITourListener = { }, // This function is copied from UITour.jsm. - isSafeScheme: function(aURI) { + isSafeScheme(aURI) { let allowedSchemes = new Set(["https", "about"]); if (!Services.prefs.getBoolPref("browser.uitour.requireSecure")) allowedSchemes.add("http"); @@ -55,7 +55,7 @@ var UITourListener = { return true; }, - ensureTrustedOrigin: function() { + ensureTrustedOrigin() { if (content.top != content) return false; @@ -74,7 +74,7 @@ var UITourListener = { return this.isTestingOrigin(uri); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "UITour:SendPageCallback": this.sendPageEvent("Response", aMessage.data); @@ -85,7 +85,7 @@ var UITourListener = { } }, - sendPageEvent: function(type, detail) { + sendPageEvent(type, detail) { if (!this.ensureTrustedOrigin()) { return; } diff --git a/browser/components/uitour/test/browser_UITour_defaultBrowser.js b/browser/components/uitour/test/browser_UITour_defaultBrowser.js index 5ebf553b0562..f5f529d30b19 100644 --- a/browser/components/uitour/test/browser_UITour_defaultBrowser.js +++ b/browser/components/uitour/test/browser_UITour_defaultBrowser.js @@ -12,8 +12,8 @@ Cc["@mozilla.org/moz/jssubscript-loader;1"] function MockShellService() {} MockShellService.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIShellService]), - isDefaultBrowser: function(aStartupCheck, aForAllTypes) { return false; }, - setDefaultBrowser: function(aClaimAllTypes, aForAllUsers) { + isDefaultBrowser(aStartupCheck, aForAllTypes) { return false; }, + setDefaultBrowser(aClaimAllTypes, aForAllUsers) { setDefaultBrowserCalled = true; }, shouldCheckDefaultBrowser: false, @@ -23,12 +23,12 @@ MockShellService.prototype = { BACKGROUND_CENTER : 3, BACKGROUND_FILL : 4, BACKGROUND_FIT : 5, - setDesktopBackground: function(aElement, aPosition) {}, + setDesktopBackground(aElement, aPosition) {}, APPLICATION_MAIL : 0, APPLICATION_NEWS : 1, - openApplication: function(aApplication) {}, + openApplication(aApplication) {}, desktopBackgroundColor: 0, - openApplicationWithURI: function(aApplication, aURI) {}, + openApplicationWithURI(aApplication, aURI) {}, defaultFeedReader: 0, }; diff --git a/browser/components/uitour/test/browser_UITour_heartbeat.js b/browser/components/uitour/test/browser_UITour_heartbeat.js index 6cfeb2a2732c..5b6a3ba717ef 100644 --- a/browser/components/uitour/test/browser_UITour_heartbeat.js +++ b/browser/components/uitour/test/browser_UITour_heartbeat.js @@ -221,7 +221,7 @@ add_UITour_task(function* test_heartbeat_take_optional_icon_URL() { // Show the Heartbeat notification and wait for it to be displayed. let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL, null, null, { - iconURL: iconURL + iconURL }); // Validate the returned timestamp. diff --git a/browser/components/uitour/test/browser_UITour_modalDialog.js b/browser/components/uitour/test/browser_UITour_modalDialog.js index 49d01474f9c2..a697d5f2df3a 100644 --- a/browser/components/uitour/test/browser_UITour_modalDialog.js +++ b/browser/components/uitour/test/browser_UITour_modalDialog.js @@ -22,7 +22,7 @@ function startCallbackTimer() { var observer = SpecialPowers.wrapCallbackObject({ - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports, Ci.nsISupportsWeakReference]; @@ -31,7 +31,7 @@ var observer = SpecialPowers.wrapCallbackObject({ return this; }, - observe : function(subject, topic, data) { + observe(subject, topic, data) { var doc = getDialogDoc(); if (doc) handleDialog(doc); diff --git a/browser/components/uitour/test/browser_no_tabs.js b/browser/components/uitour/test/browser_no_tabs.js index 62048b1568d3..05c0f2b9f67f 100644 --- a/browser/components/uitour/test/browser_no_tabs.js +++ b/browser/components/uitour/test/browser_no_tabs.js @@ -26,7 +26,7 @@ function createHiddenBrowser(aURL) { browser.setAttribute("src", aURL); doc.documentElement.appendChild(browser); - resolve({frame: frame, browser: browser}); + resolve({frame, browser}); })); } diff --git a/browser/experiments/Experiments.jsm b/browser/experiments/Experiments.jsm index f76092f497f9..9038c7d801b4 100644 --- a/browser/experiments/Experiments.jsm +++ b/browser/experiments/Experiments.jsm @@ -211,7 +211,7 @@ var Experiments = { /** * Provides access to the global `Experiments.Experiments` instance. */ - instance: function() { + instance() { if (!gExperiments) { gExperiments = new Experiments.Experiments(); } @@ -236,11 +236,11 @@ Experiments.Policy = function() { }; Experiments.Policy.prototype = { - now: function() { + now() { return new Date(); }, - random: function() { + random() { let pref = gPrefs.get(PREF_FORCE_SAMPLE); if (pref !== undefined) { let val = Number.parseFloat(pref); @@ -256,19 +256,19 @@ Experiments.Policy.prototype = { return Math.random(); }, - futureDate: function(offset) { + futureDate(offset) { return new Date(this.now().getTime() + offset); }, - oneshotTimer: function(callback, timeout, thisObj, name) { + oneshotTimer(callback, timeout, thisObj, name) { return CommonUtils.namedTimer(callback, timeout, thisObj, name); }, - updatechannel: function() { + updatechannel() { return UpdateUtils.UpdateChannel; }, - locale: function() { + locale() { let chrome = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry); return chrome.getSelectedLocale("global"); }, @@ -277,7 +277,7 @@ Experiments.Policy.prototype = { * For testing a race condition, one of the tests delays the callback of * writing the cache by replacing this policy function. */ - delayCacheWrite: function(promise) { + delayCacheWrite(promise) { return promise; }, }; @@ -373,7 +373,7 @@ Experiments.Experiments.prototype = { return !this._shutdown; }, - init: function() { + init() { this._shutdown = false; configureLogging(); @@ -467,7 +467,7 @@ Experiments.Experiments.prototype = { }), // Return state information, for debugging purposes. - _getState: function() { + _getState() { let activeExperiment = this._getActiveExperiment(); let state = { isShutdown: this._shutdown, @@ -497,13 +497,13 @@ Experiments.Experiments.prototype = { return state; }, - _addToForensicsLog: function(what, string) { + _addToForensicsLog(what, string) { this._forensicsLogs.shift(); let timeInSec = Math.floor(Services.telemetry.msSinceProcessStart() / 1000); this._forensicsLogs.push(`${timeInSec}: ${what} - ${string}`); }, - _registerWithAddonManager: function(previousExperimentsProvider) { + _registerWithAddonManager(previousExperimentsProvider) { this._log.trace("Registering instance with Addon Manager."); AddonManager.addAddonListener(this); @@ -526,7 +526,7 @@ Experiments.Experiments.prototype = { }, - _unregisterWithAddonManager: function() { + _unregisterWithAddonManager() { this._log.trace("Unregistering instance with Addon Manager."); this._log.trace("Removing install listener from add-on manager."); @@ -546,7 +546,7 @@ Experiments.Experiments.prototype = { * Change the PreviousExperimentsProvider that this instance uses. * For testing only. */ - _setPreviousExperimentsProvider: function(provider) { + _setPreviousExperimentsProvider(provider) { this._unregisterWithAddonManager(); this._registerWithAddonManager(provider); }, @@ -554,7 +554,7 @@ Experiments.Experiments.prototype = { /** * Throws an exception if we've already shut down. */ - _checkForShutdown: function() { + _checkForShutdown() { if (this._shutdown) { throw new AlreadyShutdownError("uninit() already called"); } @@ -594,7 +594,7 @@ Experiments.Experiments.prototype = { } }), - _telemetryStatusChanged: function() { + _telemetryStatusChanged() { this._toggleExperimentsEnabled(gExperimentsEnabled); }, @@ -616,7 +616,7 @@ Experiments.Experiments.prototype = { * * @return Promise> Array of experiment info objects. */ - getExperiments: function() { + getExperiments() { return Task.spawn(function*() { yield this._loadTask; let list = []; @@ -628,7 +628,7 @@ Experiments.Experiments.prototype = { } list.push({ - id: id, + id, name: experiment._name, description: experiment._description, active: experiment.enabled, @@ -648,7 +648,7 @@ Experiments.Experiments.prototype = { * Returns the ExperimentInfo for the active experiment, or null * if there is none. */ - getActiveExperiment: function() { + getActiveExperiment() { let experiment = this._getActiveExperiment(); if (!experiment) { return null; @@ -718,7 +718,7 @@ Experiments.Experiments.prototype = { /** * Determine whether another date has the same UTC day as now(). */ - _dateIsTodayUTC: function(d) { + _dateIsTodayUTC(d) { let now = this._policy.now(); return stripDateToMidnight(now).getTime() == stripDateToMidnight(d).getTime(); @@ -734,7 +734,7 @@ Experiments.Experiments.prototype = { * * @return Promise */ - lastActiveToday: function() { + lastActiveToday() { return Task.spawn(function* getMostRecentActiveExperimentTask() { let experiments = yield this.getExperiments(); @@ -753,7 +753,7 @@ Experiments.Experiments.prototype = { }.bind(this)); }, - _run: function() { + _run() { this._log.trace("_run"); this._checkForShutdown(); if (!this._mainTask) { @@ -783,7 +783,7 @@ Experiments.Experiments.prototype = { return this._mainTask; }, - _main: function*() { + *_main() { do { this._log.trace("_main iteration"); yield this._loadTask; @@ -804,7 +804,7 @@ Experiments.Experiments.prototype = { while (this._refresh || this._terminateReason || this._dirty); }, - _loadManifest: function*() { + *_loadManifest() { this._log.trace("_loadManifest"); let uri = Services.urlFormatter.formatURLPref(PREF_BRANCH + PREF_MANIFEST_URI); @@ -833,7 +833,7 @@ Experiments.Experiments.prototype = { * @return Promise<> * The promise is resolved when the manifest and experiment list is updated. */ - updateManifest: function() { + updateManifest() { this._log.trace("updateManifest()"); if (!gExperimentsEnabled) { @@ -848,7 +848,7 @@ Experiments.Experiments.prototype = { return this._run(); }, - notify: function(timer) { + notify(timer) { this._log.trace("notify()"); this._checkForShutdown(); return this._run(); @@ -856,7 +856,7 @@ Experiments.Experiments.prototype = { // START OF ADD-ON LISTENERS - onUninstalled: function(addon) { + onUninstalled(addon) { this._log.trace("onUninstalled() - addon id: " + addon.id); if (gActiveUninstallAddonIDs.has(addon.id)) { this._log.trace("matches pending uninstall"); @@ -873,7 +873,7 @@ Experiments.Experiments.prototype = { /** * @returns {Boolean} returns false when we cancel the install. */ - onInstallStarted: function(install) { + onInstallStarted(install) { if (install.addon.type != "experiment") { return true; } @@ -917,7 +917,7 @@ Experiments.Experiments.prototype = { // END OF ADD-ON LISTENERS. - _getExperimentByAddonId: function(addonId) { + _getExperimentByAddonId(addonId) { for (let [, entry] of this._experiments) { if (entry._addonId === addonId) { return entry; @@ -931,7 +931,7 @@ Experiments.Experiments.prototype = { * Helper function to make HTTP GET requests. Returns a promise that is resolved with * the responseText when the request is complete. */ - _httpGetRequest: function(url) { + _httpGetRequest(url) { this._log.trace("httpGetRequest(" + url + ")"); let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest); @@ -986,7 +986,7 @@ Experiments.Experiments.prototype = { /* * Part of the main task to save the cache to disk, called from _main. */ - _saveToCache: function* () { + *_saveToCache() { this._log.trace("_saveToCache"); let path = this._cacheFilePath; this._dirty = false; @@ -1029,7 +1029,7 @@ Experiments.Experiments.prototype = { } }), - _populateFromCache: function(data) { + _populateFromCache(data) { this._log.trace("populateFromCache() - data: " + JSON.stringify(data)); // If the user has a newer cache version than we can understand, we fail @@ -1062,7 +1062,7 @@ Experiments.Experiments.prototype = { * Update the experiment entries from the experiments * array in the manifest */ - _updateExperiments: function(manifestObject) { + _updateExperiments(manifestObject) { this._log.trace("_updateExperiments() - experiments: " + JSON.stringify(manifestObject)); if (manifestObject.version !== MANIFEST_VERSION) { @@ -1113,7 +1113,7 @@ Experiments.Experiments.prototype = { this._dirty = true; }, - getActiveExperimentID: function() { + getActiveExperimentID() { if (!this._experiments) { return null; } @@ -1124,7 +1124,7 @@ Experiments.Experiments.prototype = { return e.id; }, - getActiveExperimentBranch: function() { + getActiveExperimentBranch() { if (!this._experiments) { return null; } @@ -1135,7 +1135,7 @@ Experiments.Experiments.prototype = { return e.branch; }, - _getActiveExperiment: function() { + _getActiveExperiment() { let enabled = [...this._experiments.values()].filter(experiment => experiment._enabled); if (enabled.length == 1) { @@ -1155,7 +1155,7 @@ Experiments.Experiments.prototype = { * * @return Promise<> Promise that will get resolved once the task is done or failed. */ - disableExperiment: function(reason) { + disableExperiment(reason) { if (!reason) { throw new Error("Must specify a termination reason."); } @@ -1180,7 +1180,7 @@ Experiments.Experiments.prototype = { * Task function to check applicability of experiments, disable the active * experiment if needed and activate the first applicable candidate. */ - _evaluateExperiments: function*() { + *_evaluateExperiments() { this._log.trace("_evaluateExperiments"); this._checkForShutdown(); @@ -1317,7 +1317,7 @@ Experiments.Experiments.prototype = { /* * Schedule the soonest re-check of experiment applicability that is needed. */ - _scheduleNextRun: function() { + _scheduleNextRun() { this._checkForShutdown(); if (this._timer) { @@ -1462,7 +1462,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The experiment data from the manifest. * @return boolean Whether initialization succeeded. */ - initFromManifestData: function(data) { + initFromManifestData(data) { if (!this._isManifestDataValid(data)) { return false; } @@ -1522,7 +1522,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The entry data from the cache. * @return boolean Whether initialization succeeded. */ - initFromCacheData: function(data) { + initFromCacheData(data) { for (let [key, dval] of this.UPGRADE_KEYS) { if (!(key in data)) { data[key] = dval; @@ -1567,7 +1567,7 @@ Experiments.ExperimentEntry.prototype = { /* * Returns a JSON representation of this object. */ - toJSON: function() { + toJSON() { let obj = {}; // Dates are serialized separately as epoch ms. @@ -1592,7 +1592,7 @@ Experiments.ExperimentEntry.prototype = { * @param data The experiment data from the manifest. * @return boolean Whether updating succeeded. */ - updateFromManifestData: function(data) { + updateFromManifestData(data) { let old = this._manifestData; if (!this._isManifestDataValid(data)) { @@ -1624,7 +1624,7 @@ Experiments.ExperimentEntry.prototype = { * If it is not applicable it is rejected with * a Promise which contains the reason. */ - isApplicable: function() { + isApplicable() { let versionCmp = Cc["@mozilla.org/xpcom/version-comparator;1"] .getService(Ci.nsIVersionComparator); let app = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo); @@ -2015,7 +2015,7 @@ Experiments.ExperimentEntry.prototype = { * * @return Promise */ - _getAddon: function() { + _getAddon() { if (!this._addonId) { return Promise.resolve(null); } @@ -2030,7 +2030,7 @@ Experiments.ExperimentEntry.prototype = { }); }, - _logTermination: function(terminationKind, terminationReason) { + _logTermination(terminationKind, terminationReason) { if (terminationKind === undefined) { return; } @@ -2051,7 +2051,7 @@ Experiments.ExperimentEntry.prototype = { /** * Determine whether an active experiment should be stopped. */ - shouldStop: function() { + shouldStop() { if (!this._enabled) { throw new Error("shouldStop must not be called on disabled experiments."); } @@ -2059,7 +2059,7 @@ Experiments.ExperimentEntry.prototype = { let deferred = Promise.defer(); this.isApplicable().then( () => deferred.resolve({shouldStop: false}), - reason => deferred.resolve({shouldStop: true, reason: reason}) + reason => deferred.resolve({shouldStop: true, reason}) ); return deferred.promise; @@ -2068,7 +2068,7 @@ Experiments.ExperimentEntry.prototype = { /* * Should this be discarded from the cache due to age? */ - shouldDiscard: function() { + shouldDiscard() { let limit = this._policy.now(); limit.setDate(limit.getDate() - KEEP_HISTORY_N_DAYS); return (this._lastChangedDate < limit); @@ -2078,7 +2078,7 @@ Experiments.ExperimentEntry.prototype = { * Get next date (in epoch-ms) to schedule a re-evaluation for this. * Returns 0 if it doesn't need one. */ - getScheduleTime: function() { + getScheduleTime() { if (this._enabled) { let startTime = this._startDate.getTime(); let maxActiveTime = startTime + 1000 * this._manifestData.maxActiveSeconds; @@ -2095,7 +2095,7 @@ Experiments.ExperimentEntry.prototype = { /* * Perform sanity checks on the experiment data. */ - _isManifestDataValid: function(data) { + _isManifestDataValid(data) { this._log.trace("isManifestDataValid() - data: " + JSON.stringify(data)); for (let key of this.MANIFEST_REQUIRED_FIELDS) { @@ -2148,12 +2148,12 @@ this.Experiments.PreviousExperimentProvider = function(experiments) { this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ name: "PreviousExperimentProvider", - startup: function() { + startup() { this._log.trace("startup()"); Services.obs.addObserver(this, EXPERIMENTS_CHANGED_TOPIC, false); }, - shutdown: function() { + shutdown() { this._log.trace("shutdown()"); try { Services.obs.removeObserver(this, EXPERIMENTS_CHANGED_TOPIC); @@ -2162,7 +2162,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ } }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case EXPERIMENTS_CHANGED_TOPIC: this._updateExperimentList(); @@ -2170,7 +2170,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ } }, - getAddonByID: function(id, cb) { + getAddonByID(id, cb) { for (let experiment of this._experimentList) { if (experiment.id == id) { cb(new PreviousExperimentAddon(experiment)); @@ -2181,7 +2181,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ cb(null); }, - getAddonsByTypes: function(types, cb) { + getAddonsByTypes(types, cb) { if (types && types.length > 0 && types.indexOf("experiment") == -1) { cb([]); return; @@ -2190,7 +2190,7 @@ this.Experiments.PreviousExperimentProvider.prototype = Object.freeze({ cb(this._experimentList.map(e => new PreviousExperimentAddon(e))); }, - _updateExperimentList: function() { + _updateExperimentList() { return this._experiments.getExperiments().then((experiments) => { let list = experiments.filter(e => !e.active); @@ -2323,11 +2323,11 @@ PreviousExperimentAddon.prototype = Object.freeze({ // BEGIN REQUIRED METHODS - isCompatibleWith: function(appVersion, platformVersion) { + isCompatibleWith(appVersion, platformVersion) { return true; }, - findUpdates: function(listener, reason, appVersion, platformVersion) { + findUpdates(listener, reason, appVersion, platformVersion) { AddonManagerPrivate.callNoUpdateListeners(this, listener, reason, appVersion, platformVersion); }, diff --git a/browser/experiments/ExperimentsService.js b/browser/experiments/ExperimentsService.js index 478793617f29..28da659bb0a9 100644 --- a/browser/experiments/ExperimentsService.js +++ b/browser/experiments/ExperimentsService.js @@ -54,7 +54,7 @@ ExperimentsService.prototype = { classID: Components.ID("{f7800463-3b97-47f9-9341-b7617e6d8d49}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback, Ci.nsIObserver]), - notify: function(timer) { + notify(timer) { if (!gExperimentsEnabled) { return; } @@ -67,14 +67,14 @@ ExperimentsService.prototype = { } }, - _delayedInit: function() { + _delayedInit() { if (!this._initialized) { this._initialized = true; Experiments.instance(); // for side effects } }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "profile-after-change": if (gExperimentsEnabled) { diff --git a/browser/experiments/test/xpcshell/test_activate.js b/browser/experiments/test/xpcshell/test_activate.js index 60deafbfb3d5..3e62c896241d 100644 --- a/browser/experiments/test/xpcshell/test_activate.js +++ b/browser/experiments/test/xpcshell/test_activate.js @@ -52,7 +52,7 @@ function isApplicable(experiment) { let deferred = Promise.defer(); experiment.isApplicable().then( result => deferred.resolve({ applicable: true, reason: null }), - reason => deferred.resolve({ applicable: false, reason: reason }) + reason => deferred.resolve({ applicable: false, reason }) ); return deferred.promise; diff --git a/browser/extensions/pocket/bootstrap.js b/browser/extensions/pocket/bootstrap.js index a9a70d0b7011..1d2f7313679f 100644 --- a/browser/extensions/pocket/bootstrap.js +++ b/browser/extensions/pocket/bootstrap.js @@ -91,13 +91,13 @@ function CreatePocketWidget(reason) { label: gPocketBundle.GetStringFromName("pocket-button.label"), tooltiptext: gPocketBundle.GetStringFromName("pocket-button.tooltiptext"), // Use forwarding functions here to avoid loading Pocket.jsm on startup: - onViewShowing: function() { + onViewShowing() { return Pocket.onPanelViewShowing.apply(this, arguments); }, - onViewHiding: function() { + onViewHiding() { return Pocket.onPanelViewHiding.apply(this, arguments); }, - onBeforeCreated: function(doc) { + onBeforeCreated(doc) { // Bug 1223127,CUI should make this easier to do. if (doc.getElementById("PanelUI-pocketView")) return; @@ -158,10 +158,10 @@ function CreatePocketWidget(reason) { // PocketContextMenu // When the context menu is opened check if we need to build and enable pocket UI. var PocketContextMenu = { - init: function() { + init() { Services.obs.addObserver(this, "on-build-contextmenu", false); }, - shutdown: function() { + shutdown() { Services.obs.removeObserver(this, "on-build-contextmenu"); // loop through windows and remove context menus // iterate through all windows and add pocket to them @@ -174,7 +174,7 @@ var PocketContextMenu = { } } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { let subject = aSubject.wrappedJSObject; let document = subject.menu.ownerDocument; let pocketEnabled = CustomizableUI.getPlacementOfWidget("pocket-button"); @@ -240,20 +240,20 @@ var PocketReader = { this._hidden = hide; this.update(); }, - startup: function() { + startup() { // Setup the listeners, update will be called when the widget is added, // no need to do that now. let mm = Services.mm; mm.addMessageListener("Reader:OnSetup", this); mm.addMessageListener("Reader:Clicked-pocket-button", this); }, - shutdown: function() { + shutdown() { let mm = Services.mm; mm.removeMessageListener("Reader:OnSetup", this); mm.removeMessageListener("Reader:Clicked-pocket-button", this); this.hidden = true; }, - update: function() { + update() { if (this.hidden) { Services.mm.broadcastAsyncMessage("Reader:RemoveButton", { id: "pocket-button" }); } else { @@ -263,7 +263,7 @@ var PocketReader = { image: "chrome://pocket/content/panels/img/pocket.svg#pocket-mark" }); } }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Reader:OnSetup": { // Tell the reader about our button. @@ -299,7 +299,7 @@ var PocketReader = { function pktUIGetter(prop, window) { return { - get: function() { + get() { // delete any getters for properties loaded from main.js so we only load main.js once delete window.pktUI; delete window.pktApi; @@ -313,7 +313,7 @@ function pktUIGetter(prop, window) { } var PocketOverlay = { - startup: function(reason) { + startup(reason) { let styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"] .getService(Ci.nsIStyleSheetService); this._sheetType = styleSheetService.AUTHOR_SHEET; @@ -329,7 +329,7 @@ var PocketOverlay = { this.onWindowOpened(win); } }, - shutdown: function(reason) { + shutdown(reason) { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.broadcastAsyncMessage("PocketShuttingDown"); @@ -359,14 +359,14 @@ var PocketOverlay = { PocketContextMenu.shutdown(); PocketReader.shutdown(); }, - onWindowOpened: function(window) { + onWindowOpened(window) { if (window.hasOwnProperty("pktUI")) return; this.setWindowScripts(window); this.addStyles(window); this.updateWindow(window); }, - setWindowScripts: function(window) { + setWindowScripts(window) { XPCOMUtils.defineLazyModuleGetter(window, "Pocket", "chrome://pocket/content/Pocket.jsm"); // Can't use XPCOMUtils for these because the scripts try to define the variables @@ -376,7 +376,7 @@ var PocketOverlay = { Object.defineProperty(window, "pktUIMessaging", pktUIGetter("pktUIMessaging", window)); }, // called for each window as it is opened - updateWindow: function(window) { + updateWindow(window) { // insert our three menu items let document = window.document; let hidden = !CustomizableUI.getPlacementOfWidget("pocket-button"); @@ -438,7 +438,7 @@ var PocketOverlay = { sib.parentNode.insertBefore(menu, sib); } }, - onWidgetAfterDOMChange: function(aWidgetNode) { + onWidgetAfterDOMChange(aWidgetNode) { if (aWidgetNode.id != "pocket-button") { return; } @@ -455,12 +455,12 @@ var PocketOverlay = { PocketReader.hidden = hidden; }, - addStyles: function(win) { + addStyles(win) { let utils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); utils.addSheet(this._cachedSheet, this._sheetType); }, - removeStyles: function(win) { + removeStyles(win) { let utils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); utils.removeSheet(gPocketStyleURI, this._sheetType); } diff --git a/browser/extensions/pocket/content/AboutPocket.jsm b/browser/extensions/pocket/content/AboutPocket.jsm index c7f57aa87304..53e7788b3e47 100644 --- a/browser/extensions/pocket/content/AboutPocket.jsm +++ b/browser/extensions/pocket/content/AboutPocket.jsm @@ -31,11 +31,11 @@ function AboutPage(chromeURL, aboutHost, classID, description, uriFlags) { AboutPage.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]), - getURIFlags: function(aURI) { // eslint-disable-line no-unused-vars + getURIFlags(aURI) { // eslint-disable-line no-unused-vars return this.uriFlags; }, - newChannel: function(aURI, aLoadInfo) { + newChannel(aURI, aLoadInfo) { let newURI = Services.io.newURI(this.chromeURL, null, null); let channel = Services.io.newChannelFromURIWithLoadInfo(newURI, aLoadInfo); @@ -48,20 +48,20 @@ AboutPage.prototype = { return channel; }, - createInstance: function(outer, iid) { + createInstance(outer, iid) { if (outer !== null) { throw Cr.NS_ERROR_NO_AGGREGATION; } return this.QueryInterface(iid); }, - register: function() { + register() { Cm.QueryInterface(Ci.nsIComponentRegistrar).registerFactory( this.classID, this.description, "@mozilla.org/network/protocol/about;1?what=" + this.aboutHost, this); }, - unregister: function() { + unregister() { Cm.QueryInterface(Ci.nsIComponentRegistrar).unregisterFactory( this.classID, this); } diff --git a/browser/extensions/pocket/content/main.js b/browser/extensions/pocket/content/main.js index ff3b5eccaff2..07147fd2155a 100644 --- a/browser/extensions/pocket/content/main.js +++ b/browser/extensions/pocket/content/main.js @@ -175,7 +175,7 @@ var pktUI = (function() { + inOverflowMenu + "&locale=" + getUILocale(), { - onShow: function() { + onShow() { }, onHide: panelDidHide, width: inOverflowMenu ? overflowMenuWidth : 300, @@ -203,7 +203,7 @@ var pktUI = (function() { } var panelId = showPanel("about:pocket-saved?pockethost=" + Services.prefs.getCharPref("extensions.pocket.site") + "&premiumStatus=" + (pktApi.isPremiumUser() ? '1' : '0') + '&inoverflowmenu=' + inOverflowMenu + "&locale=" + getUILocale(), { - onShow: function() { + onShow() { var saveLinkMessageId = 'saveLink'; // Send error message for invalid url @@ -229,15 +229,15 @@ var pktUI = (function() { // Add url var options = { - success: function(data, request) { + success(data, request) { var item = data.item; var successResponse = { status: "success", - item: item + item }; pktUIMessaging.sendMessageToPanel(panelId, saveLinkMessageId, successResponse); }, - error: function(error, request) { + error(error, request) { // If user is not authorized show singup page if (request.status === 401) { showSignUp(); @@ -418,8 +418,8 @@ var pktUI = (function() { pktUIMessaging.addMessageListener(iframe, _getTagsMessageId, function(panelId, data) { pktApi.getTags(function(tags, usedTags) { pktUIMessaging.sendResponseMessageToPanel(panelId, _getTagsMessageId, { - tags: tags, - usedTags: usedTags + tags, + usedTags }); }); }); @@ -428,17 +428,17 @@ var pktUI = (function() { var _getSuggestedTagsMessageId = "getSuggestedTags"; pktUIMessaging.addMessageListener(iframe, _getSuggestedTagsMessageId, function(panelId, data) { pktApi.getSuggestedTagsForURL(data.url, { - success: function(data, response) { + success(data, response) { var suggestedTags = data.suggested_tags; var successResponse = { status: "success", value: { - suggestedTags: suggestedTags + suggestedTags } } pktUIMessaging.sendResponseMessageToPanel(panelId, _getSuggestedTagsMessageId, successResponse); }, - error: function(error, response) { + error(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _getSuggestedTagsMessageId, error); } }) @@ -448,11 +448,11 @@ var pktUI = (function() { var _addTagsMessageId = "addTags"; pktUIMessaging.addMessageListener(iframe, _addTagsMessageId, function(panelId, data) { pktApi.addTagsToURL(data.url, data.tags, { - success: function(data, response) { + success(data, response) { var successResponse = {status: "success"}; pktUIMessaging.sendResponseMessageToPanel(panelId, _addTagsMessageId, successResponse); }, - error: function(error, response) { + error(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _addTagsMessageId, error); } }); @@ -462,11 +462,11 @@ var pktUI = (function() { var _deleteItemMessageId = "deleteItem"; pktUIMessaging.addMessageListener(iframe, _deleteItemMessageId, function(panelId, data) { pktApi.deleteItem(data.itemId, { - success: function(data, response) { + success(data, response) { var successResponse = {status: "success"}; pktUIMessaging.sendResponseMessageToPanel(panelId, _deleteItemMessageId, successResponse); }, - error: function(error, response) { + error(error, response) { pktUIMessaging.sendErrorResponseMessageToPanel(panelId, _deleteItemMessageId, error); } }) @@ -485,7 +485,7 @@ var pktUI = (function() { strings[str.key] = str.value; } } - pktUIMessaging.sendResponseMessageToPanel(panelId, _initL10NMessageId, { strings: strings }); + pktUIMessaging.sendResponseMessageToPanel(panelId, _initL10NMessageId, { strings }); }); } @@ -588,15 +588,15 @@ var pktUI = (function() { * Public functions */ return { - getPanelFrame: getPanelFrame, + getPanelFrame, - openTabWithUrl: openTabWithUrl, + openTabWithUrl, - pocketPanelDidShow: pocketPanelDidShow, - pocketPanelDidHide: pocketPanelDidHide, + pocketPanelDidShow, + pocketPanelDidHide, - tryToSaveUrl: tryToSaveUrl, - tryToSaveCurrentPage: tryToSaveCurrentPage + tryToSaveUrl, + tryToSaveCurrentPage }; }()); @@ -669,12 +669,12 @@ var pktUIMessaging = (function() { * iframe as a message response */ function sendErrorMessageToPanel(panelId, messageId, error) { - var errorResponse = {status: "error", error: error}; + var errorResponse = {status: "error", error}; sendMessageToPanel(panelId, messageId, errorResponse); } function sendErrorResponseMessageToPanel(panelId, messageId, error) { - var errorResponse = {status: "error", error: error}; + var errorResponse = {status: "error", error}; sendResponseMessageToPanel(panelId, messageId, errorResponse); } @@ -730,10 +730,10 @@ var pktUIMessaging = (function() { * Public */ return { - addMessageListener: addMessageListener, - sendMessageToPanel: sendMessageToPanel, - sendResponseMessageToPanel: sendResponseMessageToPanel, - sendErrorMessageToPanel: sendErrorMessageToPanel, - sendErrorResponseMessageToPanel: sendErrorResponseMessageToPanel + addMessageListener, + sendMessageToPanel, + sendResponseMessageToPanel, + sendErrorMessageToPanel, + sendErrorResponseMessageToPanel } }()); diff --git a/browser/extensions/pocket/content/panels/js/messages.js b/browser/extensions/pocket/content/panels/js/messages.js index ae08c3e73a3b..eeeceb0a78f4 100644 --- a/browser/extensions/pocket/content/panels/js/messages.js +++ b/browser/extensions/pocket/content/panels/js/messages.js @@ -40,7 +40,7 @@ var pktPanelMessaging = (function() { // Payload needs to be an object in format: // { panelId: panelId, data: {} } var messagePayload = { - panelId: panelId, + panelId, data: (payload || {}) }; @@ -70,9 +70,9 @@ var pktPanelMessaging = (function() { * Public functions */ return { - panelIdFromURL: panelIdFromURL, - addMessageListener : addMessageListener, - removeMessageListener : removeMessageListener, - sendMessage: sendMessage + panelIdFromURL, + addMessageListener, + removeMessageListener, + sendMessage }; }()); diff --git a/browser/extensions/pocket/content/panels/js/saved.js b/browser/extensions/pocket/content/panels/js/saved.js index ff47020d040c..64642f474a75 100644 --- a/browser/extensions/pocket/content/panels/js/saved.js +++ b/browser/extensions/pocket/content/panels/js/saved.js @@ -173,7 +173,7 @@ var PKT_SAVED_OVERLAY = function(options) noResultsHideDropdown: true, scrollKeyboard: true, emptyInputLength: 200, - search_function: function(term, cb) { + search_function(term, cb) { var returnlist = []; if (term.length) { var limit = 15; @@ -191,7 +191,7 @@ var PKT_SAVED_OVERLAY = function(options) } cb(returnlist); }, - textToData: function(text) { + textToData(text) { if ($.trim(text).length > 25 || !$.trim(text).length) { if (text.length > 25) { myself.showTagsError(myself.dictJSON.maxtaglength); @@ -205,7 +205,7 @@ var PKT_SAVED_OVERLAY = function(options) myself.hideTagsError(); return {name:myself.sanitizeText(text.toLowerCase())}; }, - onReady: function() { + onReady() { $('.token-input-dropdown').addClass('token-input-dropdown-tag'); inputwrapper.find('.token-input-input-token input').attr('placeholder', $('.tag-input').attr('placeholder')).css('width', '200px'); if ($('.pkt_ext_suggestedtag_detail').length) { @@ -237,22 +237,22 @@ var PKT_SAVED_OVERLAY = function(options) }); myself.checkPlaceholderStatus(); }, - onAdd: function() { + onAdd() { myself.checkValidTagSubmit(); changestamp = Date.now(); myself.hideInactiveTags(); myself.checkPlaceholderStatus(); }, - onDelete: function() { + onDelete() { myself.checkValidTagSubmit(); changestamp = Date.now(); myself.showActiveTags(); myself.checkPlaceholderStatus(); }, - onShowDropdown: function() { + onShowDropdown() { thePKT_SAVED.sendMessage("expandSavePanel"); }, - onHideDropdown: function() { + onHideDropdown() { thePKT_SAVED.sendMessage("collapseSavePanel"); } }); @@ -457,7 +457,7 @@ var PKT_SAVED_OVERLAY = function(options) }; PKT_SAVED_OVERLAY.prototype = { - create : function() + create() { if (this.active) { @@ -497,7 +497,7 @@ PKT_SAVED_OVERLAY.prototype = { this.initOpenListInput(); this.initAutoCloseEvents(); }, - createPremiumFunctionality: function() + createPremiumFunctionality() { if (this.premiumStatus && !$('.pkt_ext_suggestedtag_detail').length) { @@ -512,7 +512,7 @@ PKT_SAVED_OVERLAY.prototype = { var PKT_SAVED = function() {}; PKT_SAVED.prototype = { - init: function() { + init() { if (this.inited) { return; } @@ -522,15 +522,15 @@ PKT_SAVED.prototype = { this.inited = true; }, - addMessageListener: function(messageId, callback) { + addMessageListener(messageId, callback) { pktPanelMessaging.addMessageListener(this.panelId, messageId, callback); }, - sendMessage: function(messageId, payload, callback) { + sendMessage(messageId, payload, callback) { pktPanelMessaging.sendMessage(this.panelId, messageId, payload, callback); }, - create: function() { + create() { var myself = this; var url = window.location.href.match(/premiumStatus=([\w|\d|\.]*)&?/); if (url && url.length > 1) diff --git a/browser/extensions/pocket/content/panels/js/signup.js b/browser/extensions/pocket/content/panels/js/signup.js index 08821be99324..13794995286d 100644 --- a/browser/extensions/pocket/content/panels/js/signup.js +++ b/browser/extensions/pocket/content/panels/js/signup.js @@ -61,7 +61,7 @@ var PKT_SIGNUP_OVERLAY = function(options) }; PKT_SIGNUP_OVERLAY.prototype = { - create : function() + create() { var controlvariant = window.location.href.match(/controlvariant=([\w|\.]*)&?/); if (controlvariant && controlvariant.length > 1) @@ -145,7 +145,7 @@ PKT_SIGNUP_OVERLAY.prototype = { var PKT_SIGNUP = function() {}; PKT_SIGNUP.prototype = { - init: function() { + init() { if (this.inited) { return; } @@ -155,15 +155,15 @@ PKT_SIGNUP.prototype = { this.inited = true; }, - addMessageListener: function(messageId, callback) { + addMessageListener(messageId, callback) { pktPanelMessaging.addMessageListener(this.panelId, messageId, callback); }, - sendMessage: function(messageId, payload, callback) { + sendMessage(messageId, payload, callback) { pktPanelMessaging.sendMessage(this.panelId, messageId, payload, callback); }, - create: function() { + create() { this.overlay.create(); // tell back end we're ready diff --git a/browser/extensions/pocket/content/pktApi.jsm b/browser/extensions/pocket/content/pktApi.jsm index 63b6d415c9e8..f18117ec0a13 100644 --- a/browser/extensions/pocket/content/pktApi.jsm +++ b/browser/extensions/pocket/content/pktApi.jsm @@ -337,7 +337,7 @@ var pktApi = (function() { var sendData = { access_token: accessToken, - url: url, + url, since: since ? since : 0 }; @@ -348,7 +348,7 @@ var pktApi = (function() { return apiRequest({ path: "/firefox/save", data: sendData, - success: function(data) { + success(data) { // Update premium status, tags and since var tags = data.tags; @@ -458,7 +458,7 @@ var pktApi = (function() { * @return {Boolean} Returns Boolean whether the api call started sucessfully */ function addTagsToURL(url, tags, options) { - return addTags({url: url}, tags, options); + return addTags({url}, tags, options); } /** @@ -475,7 +475,7 @@ var pktApi = (function() { // Tags add action var action = { action: "tags_add", - tags: tags + tags }; action = extend(action, actionPart); @@ -584,7 +584,7 @@ var pktApi = (function() { * @return {Boolean} Returns Boolean whether the api call started sucessfully */ function getSuggestedTagsForURL(url, options) { - return getSuggestedTags({url: url}, options); + return getSuggestedTags({url}, options); } /** @@ -600,7 +600,7 @@ var pktApi = (function() { return apiRequest({ path: "/getSuggestedTags", - data: data, + data, success: options.success, error: options.error }); @@ -642,16 +642,16 @@ var pktApi = (function() { * Public functions */ return { - isUserLoggedIn : isUserLoggedIn, - clearUserData: clearUserData, - addLink: addLink, - deleteItem: deleteItem, - addTagsToItem: addTagsToItem, - addTagsToURL: addTagsToURL, - getTags: getTags, - isPremiumUser: isPremiumUser, - getSuggestedTagsForItem: getSuggestedTagsForItem, - getSuggestedTagsForURL: getSuggestedTagsForURL, - getSignupPanelTabTestVariant: getSignupPanelTabTestVariant, + isUserLoggedIn, + clearUserData, + addLink, + deleteItem, + addTagsToItem, + addTagsToURL, + getTags, + isPremiumUser, + getSuggestedTagsForItem, + getSuggestedTagsForURL, + getSignupPanelTabTestVariant, }; }()); diff --git a/browser/extensions/pocket/test/head.js b/browser/extensions/pocket/test/head.js index e044a42c76ba..a4cf877b0196 100644 --- a/browser/extensions/pocket/test/head.js +++ b/browser/extensions/pocket/test/head.js @@ -36,7 +36,7 @@ function promisePocketDisabled() { } return new Promise((resolve, reject) => { let listener = { - onWidgetDestroyed: function(widgetid) { + onWidgetDestroyed(widgetid) { if (widgetid == "pocket-button") { CustomizableUI.removeListener(listener); info( "pocket-button destroyed"); diff --git a/browser/extensions/presentation/bootstrap.js b/browser/extensions/presentation/bootstrap.js index 5cd2f11036b9..d81e3643adaa 100644 --- a/browser/extensions/presentation/bootstrap.js +++ b/browser/extensions/presentation/bootstrap.js @@ -33,7 +33,7 @@ function shutdown(aData, aReason) { // Register/unregister a constructor as a factory. function Factory() {} Factory.prototype = { - register: function(targetConstructor) { + register(targetConstructor) { let proto = targetConstructor.prototype; this._classID = proto.classID; @@ -45,7 +45,7 @@ Factory.prototype = { proto.contractID, factory); }, - unregister: function() { + unregister() { let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(this._classID, this._factory); this._factory = null; @@ -55,14 +55,14 @@ Factory.prototype = { var Presentation = { // PUBLIC APIs - init: function() { + init() { log("init"); // Register PresentationDevicePrompt into a XPCOM component. Cu.import(PRESENTATION_DEVICE_PROMPT_PATH); this._register(); }, - uninit: function() { + uninit() { log("uninit"); // Unregister PresentationDevicePrompt XPCOM component. this._unregister(); @@ -70,13 +70,13 @@ var Presentation = { }, // PRIVATE APIs - _register: function() { + _register() { log("_register"); this._devicePromptFactory = new Factory(); this._devicePromptFactory.register(PresentationDevicePrompt); }, - _unregister: function() { + _unregister() { log("_unregister"); this._devicePromptFactory.unregister(); delete this._devicePromptFactory; diff --git a/browser/extensions/presentation/content/PresentationDevicePrompt.jsm b/browser/extensions/presentation/content/PresentationDevicePrompt.jsm index 883ffff34fa3..949040192712 100644 --- a/browser/extensions/presentation/content/PresentationDevicePrompt.jsm +++ b/browser/extensions/presentation/content/PresentationDevicePrompt.jsm @@ -171,7 +171,7 @@ PresentationPermissionPrompt.prototype = { } return this.principal.URI.hostPort; }, - _createPopupContent: function() { + _createPopupContent() { log("_createPopupContent"); if (!this._devices.length) { @@ -223,7 +223,7 @@ PresentationDevicePrompt.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIPresentationDevicePrompt]), // This will be fired when window.PresentationRequest(URL).start() is called. - promptDeviceSelection: function(aRequest) { + promptDeviceSelection(aRequest) { log("promptDeviceSelection"); // Cancel request if no available device. @@ -238,7 +238,7 @@ PresentationDevicePrompt.prototype = { let promptUI = new PresentationPermissionPrompt(aRequest, devices); promptUI.prompt(); }, - _loadDevices: function() { + _loadDevices() { let deviceManager = Cc["@mozilla.org/presentation-device/manager;1"] .getService(Ci.nsIPresentationDeviceManager); let devices = deviceManager.getAvailableDevices().QueryInterface(Ci.nsIArray); diff --git a/browser/modules/AboutHome.jsm b/browser/modules/AboutHome.jsm index 01cbafba99f4..627e7bd56af2 100644 --- a/browser/modules/AboutHome.jsm +++ b/browser/modules/AboutHome.jsm @@ -104,7 +104,7 @@ var AboutHome = { "AboutHome:MaybeShowAutoMigrationUndoNotification", ], - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); for (let msg of this.MESSAGES) { @@ -112,7 +112,7 @@ var AboutHome = { } }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { let window = aMessage.target.ownerGlobal; switch (aMessage.name) { @@ -160,7 +160,7 @@ var AboutHome = { // Send all the chrome-privileged data needed by about:home. This // gets re-sent when the search engine changes. - sendAboutHomeData: function(target) { + sendAboutHomeData(target) { let wrapper = {}; Components.utils.import("resource:///modules/sessionstore/SessionStore.jsm", wrapper); diff --git a/browser/modules/AboutNewTab.jsm b/browser/modules/AboutNewTab.jsm index 145cec09a71a..afb04ad499fb 100644 --- a/browser/modules/AboutNewTab.jsm +++ b/browser/modules/AboutNewTab.jsm @@ -22,17 +22,17 @@ var AboutNewTab = { pageListener: null, - init: function() { + init() { this.pageListener = new RemotePages("about:newtab"); this.pageListener.addMessageListener("NewTab:Customize", this.customize.bind(this)); }, - customize: function(message) { + customize(message) { NewTabUtils.allPages.enabled = message.data.enabled; NewTabUtils.allPages.enhanced = message.data.enhanced; }, - uninit: function() { + uninit() { this.pageListener.destroy(); this.pageListener = null; }, diff --git a/browser/modules/BrowserUITelemetry.jsm b/browser/modules/BrowserUITelemetry.jsm index 6e54d45df651..8f74aca423a8 100644 --- a/browser/modules/BrowserUITelemetry.jsm +++ b/browser/modules/BrowserUITelemetry.jsm @@ -170,7 +170,7 @@ const BUCKET_PREFIX = "bucket_"; const BUCKET_SEPARATOR = "|"; this.BrowserUITelemetry = { - init: function() { + init() { UITelemetry.addSimpleMeasureFunction("toolbars", this.getToolbarMeasures.bind(this)); UITelemetry.addSimpleMeasureFunction("contextmenu", @@ -189,7 +189,7 @@ this.BrowserUITelemetry = { CustomizableUI.addListener(this); }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "sessionstore-windows-restored": this._gatherFirstWindowMeasurements(); @@ -241,7 +241,7 @@ this.BrowserUITelemetry = { * @returns a reference to the second last object in the chain - * so in our example, that'd be "b". */ - _ensureObjectChain: function(aKeys, aEndWith, aRoot) { + _ensureObjectChain(aKeys, aEndWith, aRoot) { let current = aRoot; let parent = null; aKeys.unshift(this._bucket); @@ -260,13 +260,13 @@ this.BrowserUITelemetry = { }, _countableEvents: {}, - _countEvent: function(aKeyArray, root = this._countableEvents) { + _countEvent(aKeyArray, root = this._countableEvents) { let countObject = this._ensureObjectChain(aKeyArray, 0, root); let lastItemKey = aKeyArray[aKeyArray.length - 1]; countObject[lastItemKey]++; }, - _countMouseUpEvent: function(aCategory, aAction, aButton) { + _countMouseUpEvent(aCategory, aAction, aButton) { const BUTTONS = ["left", "middle", "right"]; let buttonKey = BUTTONS[aButton]; if (buttonKey) { @@ -275,7 +275,7 @@ this.BrowserUITelemetry = { }, _firstWindowMeasurements: null, - _gatherFirstWindowMeasurements: function() { + _gatherFirstWindowMeasurements() { // We'll gather measurements as soon as the session has restored. // We do this here instead of waiting for UITelemetry to ask for // our measurements because at that point all browser windows have @@ -295,7 +295,7 @@ this.BrowserUITelemetry = { }); }, - _registerWindow: function(aWindow) { + _registerWindow(aWindow) { aWindow.addEventListener("unload", this); let document = aWindow.document; @@ -323,7 +323,7 @@ this.BrowserUITelemetry = { WINDOW_DURATION_MAP.set(aWindow, {}); }, - _unregisterWindow: function(aWindow) { + _unregisterWindow(aWindow) { aWindow.removeEventListener("unload", this); let document = aWindow.document; @@ -349,7 +349,7 @@ this.BrowserUITelemetry = { } }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "unload": this._unregisterWindow(aEvent.currentTarget); @@ -363,7 +363,7 @@ this.BrowserUITelemetry = { } }, - _handleMouseUp: function(aEvent) { + _handleMouseUp(aEvent) { let targetID = aEvent.currentTarget.id; switch (targetID) { @@ -381,7 +381,7 @@ this.BrowserUITelemetry = { } }, - _handleMouseDown: function(aEvent) { + _handleMouseDown(aEvent) { if (aEvent.currentTarget.id == "PanelUI-menu-button") { // _countMouseUpEvent expects a detail for the second argument, // but we don't really have any details to give. Just passing in @@ -391,13 +391,13 @@ this.BrowserUITelemetry = { } }, - _PlacesChevronMouseUp: function(aEvent) { + _PlacesChevronMouseUp(aEvent) { let target = aEvent.originalTarget; let result = target.id == "PlacesChevron" ? "chevron" : "overflowed-item"; this._countMouseUpEvent("click-bookmarks-bar", result, aEvent.button); }, - _PlacesToolbarItemsMouseUp: function(aEvent) { + _PlacesToolbarItemsMouseUp(aEvent) { let target = aEvent.originalTarget; // If this isn't a bookmark-item, we don't care about it. if (!target.classList.contains("bookmark-item")) { @@ -408,14 +408,14 @@ this.BrowserUITelemetry = { this._countMouseUpEvent("click-bookmarks-bar", result, aEvent.button); }, - _menubarMouseUp: function(aEvent) { + _menubarMouseUp(aEvent) { let target = aEvent.originalTarget; let tag = target.localName let result = (tag == "menu" || tag == "menuitem") ? tag : "other"; this._countMouseUpEvent("click-menubar", result, aEvent.button); }, - _bookmarksMenuButtonMouseUp: function(aEvent) { + _bookmarksMenuButtonMouseUp(aEvent) { let bookmarksWidget = CustomizableUI.getWidget("bookmarks-menu-button"); if (bookmarksWidget.areaType == CustomizableUI.TYPE_MENU_PANEL) { // In the menu panel, only the star is visible, and that opens up the @@ -441,7 +441,7 @@ this.BrowserUITelemetry = { } }, - _checkForBuiltinItem: function(aEvent) { + _checkForBuiltinItem(aEvent) { let item = aEvent.originalTarget; // We don't want to count clicks on the private browsing @@ -482,7 +482,7 @@ this.BrowserUITelemetry = { } }, - _getWindowMeasurements: function(aWindow, searchResult) { + _getWindowMeasurements(aWindow, searchResult) { let document = aWindow.document; let result = {}; @@ -582,14 +582,14 @@ this.BrowserUITelemetry = { return result; }, - getToolbarMeasures: function() { + getToolbarMeasures() { let result = this._firstWindowMeasurements || {}; result.countableEvents = this._countableEvents; result.durations = this._durations; return result; }, - getSyncState: function() { + getSyncState() { let result = {}; for (let sub of ["desktop", "mobile"]) { let count = 0; @@ -601,11 +601,11 @@ this.BrowserUITelemetry = { return result; }, - countCustomizationEvent: function(aEventType) { + countCustomizationEvent(aEventType) { this._countEvent(["customize", aEventType]); }, - countSearchEvent: function(source, query, selection) { + countSearchEvent(source, query, selection) { this._countEvent(["search", source]); if ((/^[a-zA-Z]+:[^\/\\]/).test(query)) { this._countEvent(["search", "urlbar-keyword"]); @@ -615,35 +615,35 @@ this.BrowserUITelemetry = { } }, - countOneoffSearchEvent: function(id, type, where) { + countOneoffSearchEvent(id, type, where) { this._countEvent(["search-oneoff", id, type, where]); }, - countSearchSettingsEvent: function(source) { + countSearchSettingsEvent(source) { this._countEvent(["click-builtin-item", source, "search-settings"]); }, - countPanicEvent: function(timeId) { + countPanicEvent(timeId) { this._countEvent(["forget-button", timeId]); }, - countTabMutingEvent: function(action, reason) { + countTabMutingEvent(action, reason) { this._countEvent(["tab-audio-control", action, reason || "no reason given"]); }, - countSyncedTabEvent: function(what, where) { + countSyncedTabEvent(what, where) { // "what" will be, eg, "open" // "where" will be "toolbarbutton-subview" or "sidebar" this._countEvent(["synced-tabs", what, where]); }, - countSidebarEvent: function(sidebarID, action) { + countSidebarEvent(sidebarID, action) { // sidebarID is the ID of the sidebar (duh!) // action will be "hide" or "show" this._countEvent(["sidebar", sidebarID, action]); }, - _logAwesomeBarSearchResult: function(url) { + _logAwesomeBarSearchResult(url) { let spec = Services.search.parseSubmissionURL(url); if (spec.engine) { let matchedEngine = "default"; @@ -658,7 +658,7 @@ this.BrowserUITelemetry = { customization: [], }, - onCustomizeStart: function(aWindow) { + onCustomizeStart(aWindow) { this._countEvent(["customize", "start"]); let durationMap = WINDOW_DURATION_MAP.get(aWindow); if (!durationMap) { @@ -672,12 +672,12 @@ this.BrowserUITelemetry = { }; }, - onCustomizeEnd: function(aWindow) { + onCustomizeEnd(aWindow) { let durationMap = WINDOW_DURATION_MAP.get(aWindow); if (durationMap && "customization" in durationMap) { let duration = aWindow.performance.now() - durationMap.customization.start; this._durations.customization.push({ - duration: duration, + duration, bucket: durationMap.customization.bucket, }); delete durationMap.customization; @@ -720,7 +720,7 @@ this.BrowserUITelemetry = { _contextMenuInteractions: {}, - registerContextMenuInteraction: function(keys, itemID) { + registerContextMenuInteraction(keys, itemID) { if (itemID) { if (itemID == "openlinkprivate") { // Don't record anything, not even an other-item count @@ -738,7 +738,7 @@ this.BrowserUITelemetry = { this._countEvent(keys, this._contextMenuInteractions); }, - getContextMenuInfo: function() { + getContextMenuInfo() { return this._contextMenuInteractions; }, @@ -777,7 +777,7 @@ this.BrowserUITelemetry = { * * @param aName Name of bucket, or null for default bucket name (__DEFAULT__) */ - setBucket: function(aName) { + setBucket(aName) { if (this._bucketTimer) { Timer.clearTimeout(this._bucketTimer); this._bucketTimer = null; @@ -820,7 +820,7 @@ this.BrowserUITelemetry = { * timed as though they started expiring 300ms before * setExpiringBucket was called. */ - setExpiringBucket: function(aName, aTimeSteps, aTimeOffset = 0) { + setExpiringBucket(aName, aTimeSteps, aTimeOffset = 0) { if (aTimeSteps.length === 0) { this.setBucket(null); return; @@ -858,7 +858,7 @@ this.BrowserUITelemetry = { * * @return Minimal string representation. */ - _toTimeStr: function(aTimeMS) { + _toTimeStr(aTimeMS) { let timeStr = ""; function reduce(aUnitLength, aSymbol) { diff --git a/browser/modules/CastingApps.jsm b/browser/modules/CastingApps.jsm index 6f9be7c3ba5a..3d4f6f5b0941 100644 --- a/browser/modules/CastingApps.jsm +++ b/browser/modules/CastingApps.jsm @@ -12,17 +12,17 @@ Cu.import("resource://gre/modules/SimpleServiceDiscovery.jsm"); var CastingApps = { - _sendEventToVideo: function(element, data) { + _sendEventToVideo(element, data) { let event = element.ownerDocument.createEvent("CustomEvent"); event.initCustomEvent("media-videoCasting", false, true, JSON.stringify(data)); element.dispatchEvent(event); }, - makeURI: function(url, charset, baseURI) { + makeURI(url, charset, baseURI) { return Services.io.newURI(url, charset, baseURI); }, - getVideo: function(element) { + getVideo(element) { if (!element) { return null; } @@ -45,7 +45,7 @@ var CastingApps = { // Use the file extension to guess the mime type let sourceURI = this.makeURI(sourceURL, null, this.makeURI(element.baseURI)); if (this.allowableExtension(sourceURI, extensions)) { - return { element: element, source: sourceURI.spec, poster: posterURL, sourceURI: sourceURI}; + return { element, source: sourceURI.spec, poster: posterURL, sourceURI}; } } @@ -58,14 +58,14 @@ var CastingApps = { // Using the type attribute is our ideal way to guess the mime type. Otherwise, // fallback to using the file extension to guess the mime type if (this.allowableMimeType(sourceNode.type, types) || this.allowableExtension(sourceURI, extensions)) { - return { element: element, source: sourceURI.spec, poster: posterURL, sourceURI: sourceURI, type: sourceNode.type }; + return { element, source: sourceURI.spec, poster: posterURL, sourceURI, type: sourceNode.type }; } } return null; }, - sendVideoToService: function(videoElement, service) { + sendVideoToService(videoElement, service) { if (!service) return; @@ -101,9 +101,9 @@ var CastingApps = { } this.session = { - service: service, - app: app, - remoteMedia: remoteMedia, + service, + app, + remoteMedia, data: { title: video.title, source: video.source, @@ -116,7 +116,7 @@ var CastingApps = { }); }, - getServicesForVideo: function(videoElement) { + getServicesForVideo(videoElement) { let video = this.getVideo(videoElement); if (!video) { return {}; @@ -130,12 +130,12 @@ var CastingApps = { return filteredServices; }, - getServicesForMirroring: function() { + getServicesForMirroring() { return SimpleServiceDiscovery.services.filter(service => service.mirror); }, // RemoteMedia callback API methods - onRemoteMediaStart: function(remoteMedia) { + onRemoteMediaStart(remoteMedia) { if (!this.session) { return; } @@ -148,17 +148,17 @@ var CastingApps = { } }, - onRemoteMediaStop: function(remoteMedia) { + onRemoteMediaStop(remoteMedia) { }, - onRemoteMediaStatus: function(remoteMedia) { + onRemoteMediaStatus(remoteMedia) { }, - allowableExtension: function(uri, extensions) { + allowableExtension(uri, extensions) { return (uri instanceof Ci.nsIURL) && extensions.indexOf(uri.fileExtension) != -1; }, - allowableMimeType: function(type, types) { + allowableMimeType(type, types) { return types.indexOf(type) != -1; } }; diff --git a/browser/modules/ContentClick.jsm b/browser/modules/ContentClick.jsm index 997588bcd5ba..d2e0419054c4 100644 --- a/browser/modules/ContentClick.jsm +++ b/browser/modules/ContentClick.jsm @@ -16,12 +16,12 @@ Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); var ContentClick = { - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Content:Click", this); }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Content:Click": this.contentAreaClick(message.json, message.target) @@ -29,7 +29,7 @@ var ContentClick = { } }, - contentAreaClick: function(json, browser) { + contentAreaClick(json, browser) { // This is heavily based on contentAreaClick from browser.js (Bug 903016) // The json is set up in a way to look like an Event. let window = browser.ownerGlobal; diff --git a/browser/modules/ContentCrashHandlers.jsm b/browser/modules/ContentCrashHandlers.jsm index 18dd516391a6..dda1780ac1fc 100644 --- a/browser/modules/ContentCrashHandlers.jsm +++ b/browser/modules/ContentCrashHandlers.jsm @@ -55,7 +55,7 @@ this.TabCrashHandler = { return this.prefs = Services.prefs.getBranch("browser.tabs.crashReporting."); }, - init: function() { + init() { if (this.initialized) return; this.initialized = true; @@ -74,7 +74,7 @@ this.TabCrashHandler = { this.pageListener.addMessageListener("restoreAll", this.receiveMessage.bind(this)); }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "ipc:content-shutdown": { aSubject.QueryInterface(Ci.nsIPropertyBag2); @@ -140,7 +140,7 @@ this.TabCrashHandler = { } }, - receiveMessage: function(message) { + receiveMessage(message) { let browser = message.target.browser; let gBrowser = browser.ownerGlobal.gBrowser; let tab = gBrowser.getTabForBrowser(browser); @@ -400,7 +400,7 @@ this.TabCrashHandler = { this.removeSubmitCheckboxesForSameCrash(childID); }, - removeSubmitCheckboxesForSameCrash: function(childID) { + removeSubmitCheckboxesForSameCrash(childID) { let enumerator = Services.wm.getEnumerator("navigator:browser"); while (enumerator.hasMoreElements()) { let window = enumerator.getNext(); @@ -428,7 +428,7 @@ this.TabCrashHandler = { } }, - onAboutTabCrashedLoad: function(message) { + onAboutTabCrashedLoad(message) { this._crashedTabCount++; // Broadcast to all about:tabcrashed pages a count of @@ -834,7 +834,7 @@ this.UnsubmittedCrashHandler = { }, { label: gNavigatorBundle.GetStringFromName("pendingCrashReports.viewAll"), - callback: function() { + callback() { chromeWin.openUILinkIn("about:crashes", "tab"); return true; }, diff --git a/browser/modules/ContentLinkHandler.jsm b/browser/modules/ContentLinkHandler.jsm index 443cae2daf71..90e33470d0f5 100644 --- a/browser/modules/ContentLinkHandler.jsm +++ b/browser/modules/ContentLinkHandler.jsm @@ -27,7 +27,7 @@ const SIZES_TELEMETRY_ENUM = { }; this.ContentLinkHandler = { - init: function(chromeGlobal) { + init(chromeGlobal) { chromeGlobal.addEventListener("DOMLinkAdded", (event) => { this.onLinkEvent(event, chromeGlobal); }, false); @@ -36,7 +36,7 @@ this.ContentLinkHandler = { }, false); }, - onLinkEvent: function(event, chromeGlobal) { + onLinkEvent(event, chromeGlobal) { var link = event.originalTarget; var rel = link.rel && link.rel.toLowerCase(); if (!link || !link.ownerDocument || !rel || !link.href) @@ -124,7 +124,7 @@ this.ContentLinkHandler = { { let engine = { title: link.title, href: link.href }; chromeGlobal.sendAsyncMessage("Link:AddSearch", - {engine: engine, + {engine, url: link.ownerDocument.documentURI}); searchAdded = true; } @@ -134,7 +134,7 @@ this.ContentLinkHandler = { } }, - getLinkIconURI: function(aLink) { + getLinkIconURI(aLink) { let targetDoc = aLink.ownerDocument; var uri = BrowserUtils.makeURI(aLink.href, targetDoc.characterSet); try { diff --git a/browser/modules/ContentSearch.jsm b/browser/modules/ContentSearch.jsm index 42525702905c..a825cc698559 100644 --- a/browser/modules/ContentSearch.jsm +++ b/browser/modules/ContentSearch.jsm @@ -108,7 +108,7 @@ this.ContentSearch = { // fetch cancellation from _cancelSuggestions. _currentSuggestion: null, - init: function() { + init() { Cc["@mozilla.org/globalmessagemanager;1"]. getService(Ci.nsIMessageListenerManager). addMessageListener(INBOUND_MESSAGE, this); @@ -133,7 +133,7 @@ this.ContentSearch = { return this._searchSuggestionUIStrings; }, - destroy: function() { + destroy() { if (this._destroyedPromise) { return this._destroyedPromise; } @@ -154,13 +154,13 @@ this.ContentSearch = { * @param messageManager * The MessageManager object of the selected browser. */ - focusInput: function(messageManager) { + focusInput(messageManager) { messageManager.sendAsyncMessage(OUTBOUND_MESSAGE, { type: "FocusInput" }); }, - receiveMessage: function(msg) { + receiveMessage(msg) { // Add a temporary event handler that exists only while the message is in // the event queue. If the message's source docshell changes browsers in // the meantime, then we need to update msg.target. event.detail will be @@ -190,13 +190,13 @@ this.ContentSearch = { this._processEventQueue(); }, - observe: function(subj, topic, data) { + observe(subj, topic, data) { switch (topic) { case "nsPref:changed": case "browser-search-engine-modified": this._eventQueue.push({ type: "Observe", - data: data, + data, }); this._processEventQueue(); break; @@ -207,7 +207,7 @@ this.ContentSearch = { } }, - removeFormHistoryEntry: function(msg, entry) { + removeFormHistoryEntry(msg, entry) { let browserData = this._suggestionDataForBrowser(msg.target); if (browserData && browserData.previousFormHistoryResult) { let { previousFormHistoryResult } = browserData; @@ -220,7 +220,7 @@ this.ContentSearch = { } }, - performSearch: function(msg, data) { + performSearch(msg, data) { this._ensureDataHasProperties(data, [ "engineName", "searchString", @@ -273,7 +273,7 @@ this.ContentSearch = { let priv = PrivateBrowsingUtils.isBrowserPrivate(browser); // fetch() rejects its promise if there's a pending request, but since we // process our event queue serially, there's never a pending request. - this._currentSuggestion = { controller: controller, target: browser }; + this._currentSuggestion = { controller, target: browser }; let suggestions = yield controller.fetch(searchString, priv, engine); this._currentSuggestion = null; @@ -350,7 +350,7 @@ this.ContentSearch = { return state; }), - _processEventQueue: function() { + _processEventQueue() { if (this._currentEventPromise || !this._eventQueue.length) { return; } @@ -369,7 +369,7 @@ this.ContentSearch = { }.bind(this)); }, - _cancelSuggestions: function(msg) { + _cancelSuggestions(msg) { let cancelled = false; // cancel active suggestion request if (this._currentSuggestion && this._currentSuggestion.target === msg.target) { @@ -401,25 +401,25 @@ this.ContentSearch = { } }), - _onMessageGetState: function(msg, data) { + _onMessageGetState(msg, data) { return this.currentStateObj().then(state => { this._reply(msg, "State", state); }); }, - _onMessageGetStrings: function(msg, data) { + _onMessageGetStrings(msg, data) { this._reply(msg, "Strings", this.searchSuggestionUIStrings); }, - _onMessageSearch: function(msg, data) { + _onMessageSearch(msg, data) { this.performSearch(msg, data); }, - _onMessageSetCurrentEngine: function(msg, data) { + _onMessageSetCurrentEngine(msg, data) { Services.search.currentEngine = Services.search.getEngineByName(data); }, - _onMessageManageEngines: function(msg, data) { + _onMessageManageEngines(msg, data) { let browserWin = msg.target.ownerGlobal; browserWin.openPreferences("paneSearch"); }, @@ -444,11 +444,11 @@ this.ContentSearch = { yield this.addFormHistoryEntry(msg, entry); }), - _onMessageRemoveFormHistoryEntry: function(msg, entry) { + _onMessageRemoveFormHistoryEntry(msg, entry) { this.removeFormHistoryEntry(msg, entry); }, - _onMessageSpeculativeConnect: function(msg, engineName) { + _onMessageSpeculativeConnect(msg, engineName) { let engine = Services.search.getEngineByName(engineName); if (!engine) { throw new Error("Unknown engine name: " + engineName); @@ -473,7 +473,7 @@ this.ContentSearch = { } }), - _suggestionDataForBrowser: function(browser, create = false) { + _suggestionDataForBrowser(browser, create = false) { let data = this._suggestionMap.get(browser); if (!data && create) { // Since one SearchSuggestionController instance is meant to be used per @@ -487,7 +487,7 @@ this.ContentSearch = { return data; }, - _reply: function(msg, type, data) { + _reply(msg, type, data) { // We reply asyncly to messages, and by the time we reply the browser we're // responding to may have been destroyed. messageManager is null then. if (!Cu.isDeadWrapper(msg.target) && msg.target.messageManager) { @@ -495,16 +495,16 @@ this.ContentSearch = { } }, - _broadcast: function(type, data) { + _broadcast(type, data) { Cc["@mozilla.org/globalmessagemanager;1"]. getService(Ci.nsIMessageListenerManager). broadcastAsyncMessage(...this._msgArgs(type, data)); }, - _msgArgs: function(type, data) { + _msgArgs(type, data) { return [OUTBOUND_MESSAGE, { - type: type, - data: data, + type, + data, }]; }, @@ -515,13 +515,13 @@ this.ContentSearch = { "searchWithEngine", [engine.name], 1); let obj = { name: engine.name, - placeholder: placeholder, + placeholder, iconBuffer: yield this._arrayBufferFromDataURI(favicon), }; return obj; }), - _arrayBufferFromDataURI: function(uri) { + _arrayBufferFromDataURI(uri) { if (!uri) { return Promise.resolve(null); } @@ -546,7 +546,7 @@ this.ContentSearch = { return deferred.promise; }, - _ensureDataHasProperties: function(data, requiredProperties) { + _ensureDataHasProperties(data, requiredProperties) { for (let prop of requiredProperties) { if (!(prop in data)) { throw new Error("Message data missing required property: " + prop); @@ -554,7 +554,7 @@ this.ContentSearch = { } }, - _initService: function() { + _initService() { if (!this._initServicePromise) { let deferred = Promise.defer(); this._initServicePromise = deferred.promise; diff --git a/browser/modules/ContentWebRTC.jsm b/browser/modules/ContentWebRTC.jsm index 24c25a3b2b19..bc6930ea34ba 100644 --- a/browser/modules/ContentWebRTC.jsm +++ b/browser/modules/ContentWebRTC.jsm @@ -19,7 +19,7 @@ const kBrowserURL = "chrome://browser/content/browser.xul"; this.ContentWebRTC = { _initialized: false, - init: function() { + init() { if (this._initialized) return; @@ -33,7 +33,7 @@ this.ContentWebRTC = { Services.obs.addObserver(processShutdown, "content-child-shutdown", false); }, - uninit: function() { + uninit() { Services.obs.removeObserver(handleGUMRequest, "getUserMedia:request"); Services.obs.removeObserver(handlePCRequest, "PeerConnection:request"); Services.obs.removeObserver(updateIndicators, "recording-device-events"); @@ -46,7 +46,7 @@ this.ContentWebRTC = { }, // Called only for 'unload' to remove pending gUM prompts in reloaded frames. - handleEvent: function(aEvent) { + handleEvent(aEvent) { let contentWindow = aEvent.target.defaultView; let mm = getMessageManagerForWindow(contentWindow); for (let key of contentWindow.pendingGetUserMediaRequests.keys()) { @@ -57,7 +57,7 @@ this.ContentWebRTC = { } }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "rtcpeer:Allow": case "rtcpeer:Deny": { @@ -115,9 +115,9 @@ function handlePCRequest(aSubject, aTopic, aData) { contentWindow.pendingPeerConnectionRequests.add(callID); let request = { - windowID: windowID, - innerWindowID: innerWindowID, - callID: callID, + windowID, + innerWindowID, + callID, documentURI: contentWindow.document.documentURI, secure: isSecure, }; @@ -210,11 +210,11 @@ function prompt(aContentWindow, aWindowID, aCallID, aConstraints, aDevices, aSec windowID: aWindowID, documentURI: aContentWindow.document.documentURI, secure: aSecure, - requestTypes: requestTypes, - sharingScreen: sharingScreen, - sharingAudio: sharingAudio, - audioDevices: audioDevices, - videoDevices: videoDevices + requestTypes, + sharingScreen, + sharingAudio, + audioDevices, + videoDevices }; let mm = getMessageManagerForWindow(aContentWindow); diff --git a/browser/modules/DirectoryLinksProvider.jsm b/browser/modules/DirectoryLinksProvider.jsm index 9a15397a410f..2563436c553e 100644 --- a/browser/modules/DirectoryLinksProvider.jsm +++ b/browser/modules/DirectoryLinksProvider.jsm @@ -268,7 +268,7 @@ var DirectoryLinksProvider = { } }, - _cacheSuggestedLinks: function(link) { + _cacheSuggestedLinks(link) { // Don't cache links that don't have the expected 'frecent_sites' if (!link.frecent_sites) { return; @@ -729,7 +729,7 @@ var DirectoryLinksProvider = { }.bind(this)); }, - _handleManyLinksChanged: function() { + _handleManyLinksChanged() { this._topSitesWithSuggestedLinks.clear(); this._suggestedLinks.forEach((suggestedLinks, site) => { if (NewTabUtils.isTopPlacesSite(site)) { @@ -744,7 +744,7 @@ var DirectoryLinksProvider = { * * @return true if _topSitesWithSuggestedLinks was modified, false otherwise. */ - _handleLinkChanged: function(aLink) { + _handleLinkChanged(aLink) { let changedLinkSite = NewTabUtils.extractSite(aLink.url); let linkStored = this._topSitesWithSuggestedLinks.has(changedLinkSite); @@ -768,13 +768,13 @@ var DirectoryLinksProvider = { return false; }, - _populatePlacesLinks: function() { + _populatePlacesLinks() { NewTabUtils.links.populateProviderCache(NewTabUtils.placesProvider, () => { this._handleManyLinksChanged(); }); }, - onDeleteURI: function(aProvider, aLink) { + onDeleteURI(aProvider, aLink) { let {url} = aLink; // remove clicked flag for that url and // call observer upon disk write completion @@ -783,14 +783,14 @@ var DirectoryLinksProvider = { }); }, - onClearHistory: function() { + onClearHistory() { // remove all clicked flags and call observers upon file write this._removeAllTileClicks().then(() => { this._callObservers("onClearHistory"); }); }, - onLinkChanged: function(aProvider, aLink) { + onLinkChanged(aProvider, aLink) { // Make sure NewTabUtils.links handles the notification first. setTimeout(() => { if (this._handleLinkChanged(aLink) || this._shouldUpdateSuggestedTile()) { @@ -799,14 +799,14 @@ var DirectoryLinksProvider = { }, 0); }, - onManyLinksChanged: function() { + onManyLinksChanged() { // Make sure NewTabUtils.links handles the notification first. setTimeout(() => { this._handleManyLinksChanged(); }, 0); }, - _getCurrentTopSiteCount: function() { + _getCurrentTopSiteCount() { let visibleTopSiteCount = 0; let newTabLinks = NewTabUtils.links.getLinks(); for (let link of newTabLinks.slice(0, MIN_VISIBLE_HISTORY_TILES)) { @@ -822,7 +822,7 @@ var DirectoryLinksProvider = { return visibleTopSiteCount; }, - _shouldUpdateSuggestedTile: function() { + _shouldUpdateSuggestedTile() { let sortedLinks = NewTabUtils.getProviderLinks(this); let mostFrecentLink = {}; @@ -850,7 +850,7 @@ var DirectoryLinksProvider = { * * @return the chosen suggested tile, or undefined if there isn't one */ - _updateSuggestedTile: function() { + _updateSuggestedTile() { let sortedLinks = NewTabUtils.getProviderLinks(this); if (!sortedLinks) { @@ -1249,7 +1249,7 @@ var DirectoryLinksProvider = { } }, - _removeObservers: function() { + _removeObservers() { this._observers.clear(); } }; diff --git a/browser/modules/E10SUtils.jsm b/browser/modules/E10SUtils.jsm index fdfde0a157d0..5f6e9243d152 100644 --- a/browser/modules/E10SUtils.jsm +++ b/browser/modules/E10SUtils.jsm @@ -46,13 +46,13 @@ this.E10SUtils = { WEB_REMOTE_TYPE, FILE_REMOTE_TYPE, - canLoadURIInProcess: function(aURL, aProcess) { + canLoadURIInProcess(aURL, aProcess) { let remoteType = aProcess == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT ? DEFAULT_REMOTE_TYPE : NOT_REMOTE; return remoteType == this.getRemoteTypeForURI(aURL, true, remoteType); }, - getRemoteTypeForURI: function(aURL, aMultiProcess, + getRemoteTypeForURI(aURL, aMultiProcess, aPreferredRemoteType = DEFAULT_REMOTE_TYPE) { if (!aMultiProcess) { return NOT_REMOTE; @@ -143,12 +143,12 @@ this.E10SUtils = { return validatedWebRemoteType(aPreferredRemoteType); }, - shouldLoadURIInThisProcess: function(aURI) { + shouldLoadURIInThisProcess(aURI) { let remoteType = Services.appinfo.remoteType; return remoteType == this.getRemoteTypeForURI(aURI.spec, true, remoteType); }, - shouldLoadURI: function(aDocShell, aURI, aReferrer) { + shouldLoadURI(aDocShell, aURI, aReferrer) { // Inner frames should always load in the current process if (aDocShell.QueryInterface(Ci.nsIDocShellTreeItem).sameTypeParent) return true; @@ -157,7 +157,7 @@ this.E10SUtils = { return this.shouldLoadURIInThisProcess(aURI); }, - redirectLoad: function(aDocShell, aURI, aReferrer, aFreshProcess) { + redirectLoad(aDocShell, aURI, aReferrer, aFreshProcess) { // Retarget the load to the correct process let messageManager = aDocShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIContentFrameMessageManager); @@ -175,7 +175,7 @@ this.E10SUtils = { return false; }, - wrapHandlingUserInput: function(aWindow, aIsHandling, aCallback) { + wrapHandlingUserInput(aWindow, aIsHandling, aCallback) { var handlingUserInput; try { handlingUserInput = aWindow.QueryInterface(Ci.nsIInterfaceRequestor) diff --git a/browser/modules/Feeds.jsm b/browser/modules/Feeds.jsm index 179d2b83d23e..c9708488080a 100644 --- a/browser/modules/Feeds.jsm +++ b/browser/modules/Feeds.jsm @@ -72,7 +72,7 @@ this.Feeds = { * Whether this is already a known feed or not, if true only a security * check will be performed. */ - isValidFeed: function(aLink, aPrincipal, aIsFeed) { + isValidFeed(aLink, aPrincipal, aIsFeed) { if (!aLink || !aPrincipal) return false; diff --git a/browser/modules/FormSubmitObserver.jsm b/browser/modules/FormSubmitObserver.jsm index 7de3ab30de8a..01bd144739df 100644 --- a/browser/modules/FormSubmitObserver.jsm +++ b/browser/modules/FormSubmitObserver.jsm @@ -38,7 +38,7 @@ FormSubmitObserver.prototype = * Public apis */ - init: function(aWindow, aTabChildGlobal) + init(aWindow, aTabChildGlobal) { this._content = aWindow; this._tab = aTabChildGlobal; @@ -57,7 +57,7 @@ FormSubmitObserver.prototype = this._tab.addEventListener("unload", this, false); }, - uninit: function() + uninit() { Services.obs.removeObserver(this, "invalidformsubmit"); this._content.removeEventListener("pageshow", this, false); @@ -72,7 +72,7 @@ FormSubmitObserver.prototype = * Events */ - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "pageshow": if (this._isRootDocumentEvent(aEvent)) { @@ -95,7 +95,7 @@ FormSubmitObserver.prototype = * nsIFormSubmitObserver */ - notifyInvalidSubmit : function(aFormElement, aInvalidElements) + notifyInvalidSubmit(aFormElement, aInvalidElements) { // We are going to handle invalid form submission attempt by focusing the // first invalid element and show the corresponding validation message in a @@ -149,7 +149,7 @@ FormSubmitObserver.prototype = * with. Updates the validation message or closes the popup if form data * becomes valid. */ - _onInput: function(aEvent) { + _onInput(aEvent) { let element = aEvent.originalTarget; // If the form input is now valid, hide the popup. @@ -170,7 +170,7 @@ FormSubmitObserver.prototype = * Blur event handler in which we disconnect from the form element and * hide the popup. */ - _onBlur: function(aEvent) { + _onBlur(aEvent) { aEvent.originalTarget.removeEventListener("input", this, false); aEvent.originalTarget.removeEventListener("blur", this, false); this._element = null; @@ -182,7 +182,7 @@ FormSubmitObserver.prototype = * information. Can be called repetitively to update the currently * displayed popup position and text. */ - _showPopup: function(aElement) { + _showPopup(aElement) { // Collect positional information and show the popup let panelData = {}; @@ -214,15 +214,15 @@ FormSubmitObserver.prototype = this._mm.sendAsyncMessage("FormValidation:ShowPopup", panelData); }, - _hidePopup: function() { + _hidePopup() { this._mm.sendAsyncMessage("FormValidation:HidePopup", {}); }, - _getWindowUtils: function() { + _getWindowUtils() { return this._content.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils); }, - _isRootDocumentEvent: function(aEvent) { + _isRootDocumentEvent(aEvent) { if (this._content == null) { return true; } diff --git a/browser/modules/FormValidationHandler.jsm b/browser/modules/FormValidationHandler.jsm index 62565af58d97..0193d644dfe6 100644 --- a/browser/modules/FormValidationHandler.jsm +++ b/browser/modules/FormValidationHandler.jsm @@ -25,13 +25,13 @@ var FormValidationHandler = * Public apis */ - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("FormValidation:ShowPopup", this); mm.addMessageListener("FormValidation:HidePopup", this); }, - uninit: function() { + uninit() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.removeMessageListener("FormValidation:ShowPopup", this); mm.removeMessageListener("FormValidation:HidePopup", this); @@ -39,7 +39,7 @@ var FormValidationHandler = this._anchor = null; }, - hidePopup: function() { + hidePopup() { this._hidePopup(); }, @@ -47,7 +47,7 @@ var FormValidationHandler = * Events */ - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { let window = aMessage.target.ownerGlobal; let json = aMessage.json; let tabBrowser = window.gBrowser; @@ -66,11 +66,11 @@ var FormValidationHandler = } }, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { this._hidePopup(); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "FullZoomChange": case "TextZoomChange": @@ -88,7 +88,7 @@ var FormValidationHandler = * Internal */ - _onPopupHiding: function(aEvent) { + _onPopupHiding(aEvent) { aEvent.originalTarget.removeEventListener("popuphiding", this, true); let tabBrowser = aEvent.originalTarget.ownerDocument.getElementById("content"); tabBrowser.selectedBrowser.removeEventListener("scroll", this, true); @@ -115,7 +115,7 @@ var FormValidationHandler = * position - popup positional string constants. * message - the form element validation message text. */ - _showPopup: function(aWindow, aPanelData) { + _showPopup(aWindow, aPanelData) { let previouslyShown = !!this._panel; this._panel = aWindow.document.getElementById("invalid-form-popup"); this._panel.firstChild.textContent = aPanelData.message; @@ -149,7 +149,7 @@ var FormValidationHandler = * Hide the popup if currently displayed. Will fire an event to onPopupHiding * above if visible. */ - _hidePopup: function() { + _hidePopup() { if (this._panel) { this._panel.hidePopup(); } diff --git a/browser/modules/HiddenFrame.jsm b/browser/modules/HiddenFrame.jsm index b5582bd97f37..207ffe9bf50e 100644 --- a/browser/modules/HiddenFrame.jsm +++ b/browser/modules/HiddenFrame.jsm @@ -39,7 +39,7 @@ HiddenFrame.prototype = { * @returns Promise Returns a promise which is resolved when the hidden frame has finished * loading. */ - get: function() { + get() { if (!this._deferred) { this._deferred = PromiseUtils.defer(); this._create(); @@ -48,7 +48,7 @@ HiddenFrame.prototype = { return this._deferred.promise; }, - destroy: function() { + destroy() { clearTimeout(this._retryTimerId); if (this._frame) { @@ -62,7 +62,7 @@ HiddenFrame.prototype = { } }, - handleEvent: function() { + handleEvent() { let contentWindow = this._frame.contentWindow; if (contentWindow.location.href === XUL_PAGE) { this._frame.removeEventListener("load", this, true); @@ -72,7 +72,7 @@ HiddenFrame.prototype = { } }, - _create: function() { + _create() { if (this.isReady) { let doc = this.hiddenDOMDocument; this._frame = doc.createElementNS(HTML_NS, "iframe"); diff --git a/browser/modules/NetworkPrioritizer.jsm b/browser/modules/NetworkPrioritizer.jsm index ef71d320dfb6..82cdc6dd03be 100644 --- a/browser/modules/NetworkPrioritizer.jsm +++ b/browser/modules/NetworkPrioritizer.jsm @@ -87,7 +87,7 @@ var BrowserHelper = { windowEntry.lastSelectedBrowser = aBrowser; }, - onRemotenessChange: function(aBrowser) { + onRemotenessChange(aBrowser) { aBrowser.setPriority(_priorityBackup.get(aBrowser.permanentKey)); }, diff --git a/browser/modules/PermissionUI.jsm b/browser/modules/PermissionUI.jsm index 19b4faaabdb8..e6d95ab437eb 100644 --- a/browser/modules/PermissionUI.jsm +++ b/browser/modules/PermissionUI.jsm @@ -481,7 +481,7 @@ GeolocationPermissionPrompt.prototype = { gBrowserBundle.GetStringFromName("geolocation.allowLocation.accesskey"), action: null, expireType: null, - callback: function(state) { + callback(state) { if (state && state.checkboxChecked) { secHistogram.add(ALWAYS_SHARE); } else { @@ -496,7 +496,7 @@ GeolocationPermissionPrompt.prototype = { expireType: PrivateBrowsingUtils.isWindowPrivate(this.browser.ownerGlobal) ? Ci.nsIPermissionManager.EXPIRE_SESSION : null, - callback: function(state) { + callback(state) { if (state && state.checkboxChecked) { secHistogram.add(NEVER_SHARE); } diff --git a/browser/modules/PluginContent.jsm b/browser/modules/PluginContent.jsm index 7c1139f6285a..c087576e842f 100644 --- a/browser/modules/PluginContent.jsm +++ b/browser/modules/PluginContent.jsm @@ -31,7 +31,7 @@ const FLASH_MIME_TYPE = "application/x-shockwave-flash"; const REPLACEMENT_STYLE_SHEET = Services.io.newURI("chrome://pluginproblem/content/pluginReplaceBinding.css", null, null); PluginContent.prototype = { - init: function(global) { + init(global) { this.global = global; // Need to hold onto the content window or else it'll get destroyed this.content = this.global.content; @@ -62,7 +62,7 @@ PluginContent.prototype = { Services.obs.addObserver(this, "decoder-doctor-notification", false); }, - uninit: function() { + uninit() { let global = this.global; global.removeEventListener("PluginBindingAttached", this, true); @@ -89,7 +89,7 @@ PluginContent.prototype = { delete this.content; }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "BrowserPlugins:ActivatePlugins": this.activatePlugins(msg.data.pluginInfo, msg.data.newState); @@ -143,7 +143,7 @@ PluginContent.prototype = { } }, - onPageShow: function(event) { + onPageShow(event) { // Ignore events that aren't from the main document. if (!this.content || event.target != this.content.document) { return; @@ -157,7 +157,7 @@ PluginContent.prototype = { } }, - onPageHide: function(event) { + onPageHide(event) { // Ignore events that aren't from the main document. if (!this.content || event.target != this.content.document) { return; @@ -168,12 +168,12 @@ PluginContent.prototype = { this.haveShownNotification = false; }, - getPluginUI: function(plugin, anonid) { + getPluginUI(plugin, anonid) { return plugin.ownerDocument. getAnonymousElementByAttribute(plugin, "anonid", anonid); }, - _getPluginInfo: function(pluginElement) { + _getPluginInfo(pluginElement) { if (pluginElement instanceof Ci.nsIDOMHTMLAnchorElement) { // Anchor elements are our place holders, and we only have them for Flash let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); @@ -223,11 +223,11 @@ PluginContent.prototype = { } return { mimetype: tagMimetype, - pluginName: pluginName, - pluginTag: pluginTag, - permissionString: permissionString, - fallbackType: fallbackType, - blocklistState: blocklistState, + pluginName, + pluginTag, + permissionString, + fallbackType, + blocklistState, }; }, @@ -237,7 +237,7 @@ PluginContent.prototype = { * nsIObjectLoadingContent. This only should happen if the plugin is * click-to-play (see bug 1186948). */ - _getPluginInfoForTag: function(pluginTag, tagMimetype) { + _getPluginInfoForTag(pluginTag, tagMimetype) { let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); let pluginName = gNavigatorBundle.GetStringFromName("pluginInfo.unknownPlugin"); @@ -268,22 +268,22 @@ PluginContent.prototype = { } return { mimetype: tagMimetype, - pluginName: pluginName, - pluginTag: pluginTag, - permissionString: permissionString, + pluginName, + pluginTag, + permissionString, // Since we should only have entered _getPluginInfoForTag when // examining a click-to-play plugin, we can safely hard-code // this fallback type, since we don't actually have an // nsIObjectLoadingContent to check. fallbackType: Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY, - blocklistState: blocklistState, + blocklistState, }; }, /** * Update the visibility of the plugin overlay. */ - setVisibility : function(plugin, overlay, shouldShow) { + setVisibility(plugin, overlay, shouldShow) { overlay.classList.toggle("visible", shouldShow); if (shouldShow) { overlay.removeAttribute("dismissed"); @@ -298,7 +298,7 @@ PluginContent.prototype = { * This function will handle showing or hiding the overlay. * @returns true if the plugin is invisible. */ - shouldShowOverlay : function(plugin, overlay) { + shouldShowOverlay(plugin, overlay) { // If the overlay size is 0, we haven't done layout yet. Presume that // plugins are visible until we know otherwise. if (overlay.scrollWidth == 0) { @@ -347,7 +347,7 @@ PluginContent.prototype = { return true; }, - addLinkClickCallback: function(linkNode, callbackName /* callbackArgs...*/) { + addLinkClickCallback(linkNode, callbackName /* callbackArgs...*/) { // XXX just doing (callback)(arg) was giving a same-origin error. bug? let self = this; let callbackArgs = Array.prototype.slice.call(arguments).slice(2); @@ -378,7 +378,7 @@ PluginContent.prototype = { }, // Helper to get the binding handler type from a plugin object - _getBindingType : function(plugin) { + _getBindingType(plugin) { if (!(plugin instanceof Ci.nsIObjectLoadingContent)) return null; @@ -403,7 +403,7 @@ PluginContent.prototype = { } }, - handleEvent: function(event) { + handleEvent(event) { let eventType = event.type; if (eventType == "unload") { @@ -583,7 +583,7 @@ PluginContent.prototype = { } }, - _recordFlashPluginTelemetry: function(eventType, plugin) { + _recordFlashPluginTelemetry(eventType, plugin) { if (!Services.telemetry.canRecordExtended) { return; } @@ -618,7 +618,7 @@ PluginContent.prototype = { } }, - _finishRecordingFlashPluginTelemetry: function() { + _finishRecordingFlashPluginTelemetry() { if (this.flashPluginStats) { Services.telemetry.getHistogramById('FLASH_PLUGIN_INSTANCES_ON_PAGE') .add(this.flashPluginStats.instancesCount); @@ -626,12 +626,12 @@ PluginContent.prototype = { } }, - isKnownPlugin: function(objLoadingContent) { + isKnownPlugin(objLoadingContent) { return (objLoadingContent.getContentTypeForMIMEType(objLoadingContent.actualType) == Ci.nsIObjectLoadingContent.TYPE_PLUGIN); }, - canActivatePlugin: function(objLoadingContent) { + canActivatePlugin(objLoadingContent) { // if this isn't a known plugin, we can't activate it // (this also guards pluginHost.getPermissionStringForType against // unexpected input) @@ -652,7 +652,7 @@ PluginContent.prototype = { isFallbackTypeValid; }, - hideClickToPlayOverlay: function(plugin) { + hideClickToPlayOverlay(plugin) { let overlay = this.getPluginUI(plugin, "main"); if (overlay) { overlay.classList.remove("visible"); @@ -660,7 +660,7 @@ PluginContent.prototype = { }, // Forward a link click callback to the chrome process. - forwardCallback: function(name, pluginTag) { + forwardCallback(name, pluginTag) { this.global.sendAsyncMessage("PluginContent:LinkClickCallback", { name, pluginTag }); }, @@ -692,12 +692,12 @@ PluginContent.prototype = { { runID, keyVals, submitURLOptIn }); }, - reloadPage: function() { + reloadPage() { this.global.content.location.reload(); }, // Event listener for click-to-play plugins. - _handleClickToPlayEvent: function(plugin) { + _handleClickToPlayEvent(plugin) { let doc = plugin.ownerDocument; let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); let permissionString; @@ -730,7 +730,7 @@ PluginContent.prototype = { } }, - onOverlayClick: function(event) { + onOverlayClick(event) { let document = event.target.ownerDocument; let plugin = document.getBindingParent(event.target); let contentWindow = plugin.ownerGlobal.top; @@ -747,7 +747,7 @@ PluginContent.prototype = { } }, - reshowClickToPlayNotification: function() { + reshowClickToPlayNotification() { let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -766,7 +766,7 @@ PluginContent.prototype = { /** * Activate the plugins that the user has specified. */ - activatePlugins: function(pluginInfo, newState) { + activatePlugins(pluginInfo, newState) { let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); @@ -812,7 +812,7 @@ PluginContent.prototype = { this.updateNotificationUI(); }, - _showClickToPlayNotification: function(plugin, showNow) { + _showClickToPlayNotification(plugin, showNow) { let plugins = []; // If plugin is null, that means the user has navigated back to a page with @@ -872,8 +872,8 @@ PluginContent.prototype = { this.global.sendAsyncMessage("PluginContent:ShowClickToPlayNotification", { plugins: [...this.pluginData.values()], - showNow: showNow, - location: location, + showNow, + location, }, null, principal); }, @@ -888,7 +888,7 @@ PluginContent.prototype = { * document). If this parameter is omitted, it defaults * to the current top-level document. */ - updateNotificationUI: function(document) { + updateNotificationUI(document) { document = document || this.content.document; // We're only interested in the top-level document, since that's @@ -953,23 +953,23 @@ PluginContent.prototype = { // If there are any items remaining in `actions` now, they are hidden // plugins that need a notification bar. this.global.sendAsyncMessage("PluginContent:UpdateHiddenPluginUI", { - haveInsecure: haveInsecure, + haveInsecure, actions: [...actions.values()], - location: location, + location, }, null, principal); }, - removeNotification: function(name) { - this.global.sendAsyncMessage("PluginContent:RemoveNotification", { name: name }); + removeNotification(name) { + this.global.sendAsyncMessage("PluginContent:RemoveNotification", { name }); }, - clearPluginCaches: function() { + clearPluginCaches() { this.pluginData.clear(); this.pluginCrashData.clear(); }, - hideNotificationBar: function(name) { - this.global.sendAsyncMessage("PluginContent:HideNotificationBar", { name: name }); + hideNotificationBar(name) { + this.global.sendAsyncMessage("PluginContent:HideNotificationBar", { name }); }, /** @@ -983,7 +983,7 @@ PluginContent.prototype = { * @returns bool * True if the plugin is a descendant of the full screen DOM element, false otherwise. **/ - isWithinFullScreenElement: function(fullScreenElement, domElement) { + isWithinFullScreenElement(fullScreenElement, domElement) { /** * Traverses down iframes until it find a non-iframe full screen DOM element. @@ -1018,7 +1018,7 @@ PluginContent.prototype = { * fired for both NPAPI and Gecko Media plugins. In the latter case, the * target of the event is the document that the GMP is being used in. */ - onPluginCrashed: function(target, aEvent) { + onPluginCrashed(target, aEvent) { if (!(aEvent instanceof this.content.PluginCrashedEvent)) return; @@ -1057,7 +1057,7 @@ PluginContent.prototype = { }); }, - NPAPIPluginProcessCrashed: function({pluginName, runID, state}) { + NPAPIPluginProcessCrashed({pluginName, runID, state}) { let message = gNavigatorBundle.formatStringFromName("crashedpluginsMessage.title", [pluginName], 1); @@ -1086,8 +1086,8 @@ PluginContent.prototype = { // WeakSet. Once the WeakSet is empty, we can clear the map. if (!this.pluginCrashData.has(runID)) { this.pluginCrashData.set(runID, { - state: state, - message: message, + state, + message, instances: new WeakSet(), }); } @@ -1098,7 +1098,7 @@ PluginContent.prototype = { } }, - setCrashedNPAPIPluginState: function({plugin, state, message}) { + setCrashedNPAPIPluginState({plugin, state, message}) { // Force a layout flush so the binding is attached. plugin.clientTop; let overlay = this.getPluginUI(plugin, "main"); @@ -1165,7 +1165,7 @@ PluginContent.prototype = { } }, - NPAPIPluginCrashReportSubmitted: function({ runID, state }) { + NPAPIPluginCrashReportSubmitted({ runID, state }) { this.pluginCrashData.delete(runID); let contentWindow = this.global.content; let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) @@ -1181,7 +1181,7 @@ PluginContent.prototype = { } }, - GMPCrashed: function(aEvent) { + GMPCrashed(aEvent) { let target = aEvent.target; let pluginName = aEvent.pluginName; let gmpPlugin = aEvent.gmpPlugin; diff --git a/browser/modules/ProcessHangMonitor.jsm b/browser/modules/ProcessHangMonitor.jsm index 7c7c86b2c129..8f439f4335c6 100644 --- a/browser/modules/ProcessHangMonitor.jsm +++ b/browser/modules/ProcessHangMonitor.jsm @@ -49,7 +49,7 @@ var ProcessHangMonitor = { /** * Initialize hang reporting. Called once in the parent process. */ - init: function() { + init() { Services.obs.addObserver(this, "process-hang-report", false); Services.obs.addObserver(this, "clear-hang-report", false); Services.obs.addObserver(this, "xpcom-shutdown", false); @@ -60,7 +60,7 @@ var ProcessHangMonitor = { * Terminate JavaScript associated with the hang being reported for * the selected browser in |win|. */ - terminateScript: function(win) { + terminateScript(win) { this.handleUserInput(win, report => report.terminateScript()); }, @@ -68,7 +68,7 @@ var ProcessHangMonitor = { * Start devtools debugger for JavaScript associated with the hang * being reported for the selected browser in |win|. */ - debugScript: function(win) { + debugScript(win) { this.handleUserInput(win, report => { function callback() { report.endStartingDebugger(); @@ -87,7 +87,7 @@ var ProcessHangMonitor = { * for the selected browser in |win|. Will attempt to generate a combined * crash report for all processes. */ - terminatePlugin: function(win) { + terminatePlugin(win) { this.handleUserInput(win, report => report.terminatePlugin()); }, @@ -95,7 +95,7 @@ var ProcessHangMonitor = { * Dismiss the browser notification and invoke an appropriate action based on * the hang type. */ - stopIt: function(win) { + stopIt(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return; @@ -115,7 +115,7 @@ var ProcessHangMonitor = { * Dismiss the notification, clear the report from the active list and set up * a new timer to track a wait period during which we won't notify. */ - waitLonger: function(win) { + waitLonger(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return; @@ -155,7 +155,7 @@ var ProcessHangMonitor = { * |win|, invoke |func| on that report and stop notifying the user * about it. */ - handleUserInput: function(win, func) { + handleUserInput(win, func) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (!report) { return null; @@ -165,7 +165,7 @@ var ProcessHangMonitor = { return func(report); }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "xpcom-shutdown": Services.obs.removeObserver(this, "xpcom-shutdown"); @@ -198,7 +198,7 @@ var ProcessHangMonitor = { /** * Find a active hang report for the given element. */ - findActiveReport: function(browser) { + findActiveReport(browser) { let frameLoader = browser.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader; for (let report of this._activeReports) { if (report.isReportForBrowser(frameLoader)) { @@ -211,7 +211,7 @@ var ProcessHangMonitor = { /** * Find a paused hang report for the given element. */ - findPausedReport: function(browser) { + findPausedReport(browser) { let frameLoader = browser.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader; for (let [report, ] of this._pausedReports) { if (report.isReportForBrowser(frameLoader)) { @@ -225,7 +225,7 @@ var ProcessHangMonitor = { * Remove an active hang report from the active list and cancel the timer * associated with it. */ - removeActiveReport: function(report) { + removeActiveReport(report) { this._activeReports.delete(report); this.updateWindows(); }, @@ -234,7 +234,7 @@ var ProcessHangMonitor = { * Remove a paused hang report from the paused list and cancel the timer * associated with it. */ - removePausedReport: function(report) { + removePausedReport(report) { let timer = this._pausedReports.get(report); if (timer) { timer.cancel(); @@ -248,7 +248,7 @@ var ProcessHangMonitor = { * each window to watch for events that would cause a different hang * report to be displayed. */ - updateWindows: function() { + updateWindows() { let e = Services.wm.getEnumerator("navigator:browser"); while (e.hasMoreElements()) { let win = e.getNext(); @@ -267,7 +267,7 @@ var ProcessHangMonitor = { /** * If there is a hang report for the current tab in |win|, display it. */ - updateWindow: function(win) { + updateWindow(win) { let report = this.findActiveReport(win.gBrowser.selectedBrowser); if (report) { @@ -280,7 +280,7 @@ var ProcessHangMonitor = { /** * Show the notification for a hang. */ - showNotification: function(win, report) { + showNotification(win, report) { let nb = win.document.getElementById("high-priority-global-notificationbox"); let notification = nb.getNotificationWithValue("process-hang"); if (notification) { @@ -292,14 +292,14 @@ var ProcessHangMonitor = { let buttons = [{ label: bundle.getString("processHang.button_stop.label"), accessKey: bundle.getString("processHang.button_stop.accessKey"), - callback: function() { + callback() { ProcessHangMonitor.stopIt(win); } }, { label: bundle.getString("processHang.button_wait.label"), accessKey: bundle.getString("processHang.button_wait.accessKey"), - callback: function() { + callback() { ProcessHangMonitor.waitLonger(win); } }]; @@ -308,7 +308,7 @@ var ProcessHangMonitor = { buttons.push({ label: bundle.getString("processHang.button_debug.label"), accessKey: bundle.getString("processHang.button_debug.accessKey"), - callback: function() { + callback() { ProcessHangMonitor.debugScript(win); } }); @@ -323,7 +323,7 @@ var ProcessHangMonitor = { /** * Ensure that no hang notifications are visible in |win|. */ - hideNotification: function(win) { + hideNotification(win) { let nb = win.document.getElementById("high-priority-global-notificationbox"); let notification = nb.getNotificationWithValue("process-hang"); if (notification) { @@ -335,17 +335,17 @@ var ProcessHangMonitor = { * Install event handlers on |win| to watch for events that would * cause a different hang report to be displayed. */ - trackWindow: function(win) { + trackWindow(win) { win.gBrowser.tabContainer.addEventListener("TabSelect", this, true); win.gBrowser.tabContainer.addEventListener("TabRemotenessChange", this, true); }, - untrackWindow: function(win) { + untrackWindow(win) { win.gBrowser.tabContainer.removeEventListener("TabSelect", this, true); win.gBrowser.tabContainer.removeEventListener("TabRemotenessChange", this, true); }, - handleEvent: function(event) { + handleEvent(event) { let win = event.target.ownerGlobal; // If a new tab is selected or if a tab changes remoteness, then @@ -360,7 +360,7 @@ var ProcessHangMonitor = { * Handle a potentially new hang report. If it hasn't been seen * before, show a notification for it in all open XUL windows. */ - reportHang: function(report) { + reportHang(report) { // If this hang was already reported reset the timer for it. if (this._activeReports.has(report)) { // if this report is in active but doesn't have a notification associated @@ -389,7 +389,7 @@ var ProcessHangMonitor = { this.updateWindows(); }, - clearHang: function(report) { + clearHang(report) { this.removeActiveReport(report); this.removePausedReport(report); report.userCanceled(); diff --git a/browser/modules/ReaderParent.jsm b/browser/modules/ReaderParent.jsm index 6fcaada42685..8b59ac5d15a9 100644 --- a/browser/modules/ReaderParent.jsm +++ b/browser/modules/ReaderParent.jsm @@ -28,20 +28,20 @@ var ReaderParent = { "Reader:UpdateReaderButton", ], - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); for (let msg of this.MESSAGES) { mm.addMessageListener(msg, this); } }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Reader:ArticleGet": this._getArticle(message.data.url, message.target).then((article) => { // Make sure the target browser is still alive before trying to send data back. if (message.target.messageManager) { - message.target.messageManager.sendAsyncMessage("Reader:ArticleData", { article: article }); + message.target.messageManager.sendAsyncMessage("Reader:ArticleData", { article }); } }, e => { if (e && e.newURL) { @@ -80,7 +80,7 @@ var ReaderParent = { } }, - updateReaderButton: function(browser) { + updateReaderButton(browser) { let win = browser.ownerGlobal; if (browser != win.gBrowser.selectedBrowser) { return; @@ -124,7 +124,7 @@ var ReaderParent = { } }, - forceShowReaderIcon: function(browser) { + forceShowReaderIcon(browser) { browser.isArticle = true; this.updateReaderButton(browser); }, @@ -136,7 +136,7 @@ var ReaderParent = { this.toggleReaderMode(event); }, - toggleReaderMode: function(event) { + toggleReaderMode(event) { let win = event.target.ownerGlobal; let browser = win.gBrowser.selectedBrowser; browser.messageManager.sendAsyncMessage("Reader:ToggleReaderMode"); diff --git a/browser/modules/RemotePrompt.jsm b/browser/modules/RemotePrompt.jsm index da4945c2eb8d..9dde55b8f6dd 100644 --- a/browser/modules/RemotePrompt.jsm +++ b/browser/modules/RemotePrompt.jsm @@ -17,12 +17,12 @@ Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/SharedPromptUtils.jsm"); var RemotePrompt = { - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Prompt:Open", this); }, - receiveMessage: function(message) { + receiveMessage(message) { switch (message.name) { case "Prompt:Open": if (message.data.uri) { @@ -34,7 +34,7 @@ var RemotePrompt = { } }, - openTabPrompt: function(args, browser) { + openTabPrompt(args, browser) { let window = browser.ownerGlobal; let tabPrompt = window.gBrowser.getTabModalPromptBox(browser) let newPrompt; @@ -92,7 +92,7 @@ var RemotePrompt = { } }, - openModalWindow: function(args, browser) { + openModalWindow(args, browser) { let window = browser.ownerGlobal; try { PromptUtils.fireDialogEvent(window, "DOMWillOpenModalDialog", browser); diff --git a/browser/modules/SelfSupportBackend.jsm b/browser/modules/SelfSupportBackend.jsm index d25b4a74fbd6..d8fbb71dca54 100644 --- a/browser/modules/SelfSupportBackend.jsm +++ b/browser/modules/SelfSupportBackend.jsm @@ -53,11 +53,11 @@ const IS_UNIFIED_TELEMETRY = Preferences.get(PREF_TELEMETRY_UNIFIED, false); var gLogAppenderDump = null; this.SelfSupportBackend = Object.freeze({ - init: function() { + init() { SelfSupportBackendInternal.init(); }, - uninit: function() { + uninit() { SelfSupportBackendInternal.uninit(); }, }); @@ -75,7 +75,7 @@ var SelfSupportBackendInternal = { /** * Initializes the self support backend. */ - init: function() { + init() { this._configureLogging(); this._log.trace("init"); @@ -108,7 +108,7 @@ var SelfSupportBackendInternal = { /** * Shut down the self support backend, if active. */ - uninit: function() { + uninit() { this._log.trace("uninit"); Preferences.ignore(PREF_BRANCH_LOG, this._configureLogging, this); @@ -142,7 +142,7 @@ var SelfSupportBackendInternal = { * Handle notifications. Once all windows are created, we wait a little bit more * since tabs might still be loading. Then, we open the self support. */ - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { this._log.trace("observe - Topic " + aTopic); if (aTopic === "sessionstore-windows-restored") { @@ -154,7 +154,7 @@ var SelfSupportBackendInternal = { /** * Configure the logger based on the preferences. */ - _configureLogging: function() { + _configureLogging() { if (!this._log) { this._log = Log.repository.getLogger(LOGGER_NAME); @@ -183,7 +183,7 @@ var SelfSupportBackendInternal = { * Create an hidden frame to host our |browser|, then load the SelfSupport page in it. * @param aURL The URL to load in the browser. */ - _makeHiddenBrowser: function(aURL) { + _makeHiddenBrowser(aURL) { this._frame = new HiddenFrame(); return this._frame.get().then(aFrame => { let doc = aFrame.document; @@ -197,7 +197,7 @@ var SelfSupportBackendInternal = { }); }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { this._log.trace("handleEvent - aEvent.type " + aEvent.type + ", Trusted " + aEvent.isTrusted); if (aEvent.type === "DOMWindowClose") { @@ -217,7 +217,7 @@ var SelfSupportBackendInternal = { /** * Called when the self support page correctly loads. */ - _pageSuccessCallback: function() { + _pageSuccessCallback() { this._log.debug("_pageSuccessCallback - Page correctly loaded."); this._browser.removeProgressListener(this._progressListener); this._progressListener.destroy(); @@ -230,7 +230,7 @@ var SelfSupportBackendInternal = { /** * Called when the self support page fails to load. */ - _pageLoadErrorCallback: function() { + _pageLoadErrorCallback() { this._log.info("_pageLoadErrorCallback - Too many failed load attempts. Giving up."); this.uninit(); }, @@ -240,7 +240,7 @@ var SelfSupportBackendInternal = { * self support page and attempt to load the page content. If loading fails, try again * after an interval. */ - _loadSelfSupport: function() { + _loadSelfSupport() { // Fetch the Self Support URL from the preferences. let unformattedURL = Preferences.get(PREF_URL, null); let url = Services.urlFormatter.formatURL(unformattedURL); @@ -290,7 +290,7 @@ function ProgressListener(aLoadErrorCallback, aLoadSuccessCallback) { } ProgressListener.prototype = { - onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { + onLocationChange(aWebProgress, aRequest, aLocation, aFlags) { if (aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) { this._log.warn("onLocationChange - There was a problem fetching the SelfSupport URL (attempt " + this._loadAttempts + ")."); @@ -312,7 +312,7 @@ ProgressListener.prototype = { } }, - onStateChange: function(aWebProgress, aRequest, aFlags, aStatus) { + onStateChange(aWebProgress, aRequest, aFlags, aStatus) { if (aFlags & Ci.nsIWebProgressListener.STATE_STOP && aFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK && aFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW && @@ -321,7 +321,7 @@ ProgressListener.prototype = { } }, - destroy: function() { + destroy() { // Make sure we don't try to reload self support when shutting down. clearTimeout(this._reloadTimerId); }, diff --git a/browser/modules/SitePermissions.jsm b/browser/modules/SitePermissions.jsm index 38fd1ab93b61..c384a22cfa63 100644 --- a/browser/modules/SitePermissions.jsm +++ b/browser/modules/SitePermissions.jsm @@ -27,7 +27,7 @@ this.SitePermissions = { * * install addon permission is excluded, check bug 1303108 */ - getAllByURI: function(aURI) { + getAllByURI(aURI) { let result = []; if (!this.isSupportedURI(aURI)) { return result; @@ -64,7 +64,7 @@ this.SitePermissions = { * - id: the state constant * - label: the translated label of that state */ - getPermissionItem: function(aId, aState) { + getPermissionItem(aId, aState) { let availableStates = this.getAvailableStates(aId).map(state => { return { id: state, label: this.getStateLabel(aId, state) }; }); @@ -77,7 +77,7 @@ this.SitePermissions = { /* Returns a list of objects representing all permissions that are currently * set for the given URI. See getPermissionItem for the content of each object. */ - getPermissionDetailsByURI: function(aURI) { + getPermissionDetailsByURI(aURI) { let permissions = []; for (let {state, id} of this.getAllByURI(aURI)) { permissions.push(this.getPermissionItem(id, state)); @@ -90,20 +90,20 @@ this.SitePermissions = { * URI. This excludes file URIs, for instance, as they don't have a host, * even though nsIPermissionManager can still handle them. */ - isSupportedURI: function(aURI) { + isSupportedURI(aURI) { return aURI.schemeIs("http") || aURI.schemeIs("https"); }, /* Returns an array of all permission IDs. */ - listPermissions: function() { + listPermissions() { return Object.keys(gPermissionObject); }, /* Returns an array of permission states to be exposed to the user for a * permission with the given ID. */ - getAvailableStates: function(aPermissionID) { + getAvailableStates(aPermissionID) { if (aPermissionID in gPermissionObject && gPermissionObject[aPermissionID].states) return gPermissionObject[aPermissionID].states; @@ -116,7 +116,7 @@ this.SitePermissions = { /* Returns the default state of a particular permission. */ - getDefault: function(aPermissionID) { + getDefault(aPermissionID) { if (aPermissionID in gPermissionObject && gPermissionObject[aPermissionID].getDefault) return gPermissionObject[aPermissionID].getDefault(); @@ -126,7 +126,7 @@ this.SitePermissions = { /* Returns the state of a particular permission for a given URI. */ - get: function(aURI, aPermissionID) { + get(aURI, aPermissionID) { if (!this.isSupportedURI(aURI)) return this.UNKNOWN; @@ -141,7 +141,7 @@ this.SitePermissions = { /* Sets the state of a particular permission for a given URI. */ - set: function(aURI, aPermissionID, aState) { + set(aURI, aPermissionID, aState) { if (!this.isSupportedURI(aURI)) return; @@ -155,7 +155,7 @@ this.SitePermissions = { /* Removes the saved state of a particular permission for a given URI. */ - remove: function(aURI, aPermissionID) { + remove(aURI, aPermissionID) { if (!this.isSupportedURI(aURI)) return; @@ -165,7 +165,7 @@ this.SitePermissions = { /* Returns the localized label for the permission with the given ID, to be * used in a UI for managing permissions. */ - getPermissionLabel: function(aPermissionID) { + getPermissionLabel(aPermissionID) { let labelID = gPermissionObject[aPermissionID].labelID || aPermissionID; return gStringBundle.GetStringFromName("permission." + labelID + ".label"); }, @@ -173,7 +173,7 @@ this.SitePermissions = { /* Returns the localized label for the given permission state, to be used in * a UI for managing permissions. */ - getStateLabel: function(aPermissionID, aState, aInUse = false) { + getStateLabel(aPermissionID, aState, aInUse = false) { switch (aState) { case this.UNKNOWN: if (aInUse) @@ -215,7 +215,7 @@ var gPermissionObject = { */ "image": { - getDefault: function() { + getDefault() { return Services.prefs.getIntPref("permissions.default.image") == 2 ? SitePermissions.BLOCK : SitePermissions.ALLOW; } @@ -223,7 +223,7 @@ var gPermissionObject = { "cookie": { states: [ SitePermissions.ALLOW, SitePermissions.SESSION, SitePermissions.BLOCK ], - getDefault: function() { + getDefault() { if (Services.prefs.getIntPref("network.cookie.cookieBehavior") == 2) return SitePermissions.BLOCK; @@ -246,14 +246,14 @@ var gPermissionObject = { }, "popup": { - getDefault: function() { + getDefault() { return Services.prefs.getBoolPref("dom.disable_open_during_load") ? SitePermissions.BLOCK : SitePermissions.ALLOW; } }, "install": { - getDefault: function() { + getDefault() { return Services.prefs.getBoolPref("xpinstall.whitelist.required") ? SitePermissions.BLOCK : SitePermissions.ALLOW; } diff --git a/browser/modules/Social.jsm b/browser/modules/Social.jsm index 25e9a6f41614..510c2d4acf4d 100644 --- a/browser/modules/Social.jsm +++ b/browser/modules/Social.jsm @@ -92,14 +92,14 @@ this.Social = { return deferred.promise; }, - _updateEnabledState: function(enable) { + _updateEnabledState(enable) { for (let p of Social.providers) { p.enabled = enable; } }, // Called to update our cache of providers and set the current provider - _updateProviderCache: function(providers) { + _updateProviderCache(providers) { this.providers = providers; Services.obs.notifyObservers(null, "social:providers-changed", null); }, @@ -108,7 +108,7 @@ this.Social = { return !this._disabledForSafeMode && this.providers.length > 0; }, - _getProviderFromOrigin: function(origin) { + _getProviderFromOrigin(origin) { for (let p of this.providers) { if (p.origin == origin) { return p; @@ -117,20 +117,20 @@ this.Social = { return null; }, - getManifestByOrigin: function(origin) { + getManifestByOrigin(origin) { return SocialService.getManifestByOrigin(origin); }, - installProvider: function(data, installCallback, options = {}) { + installProvider(data, installCallback, options = {}) { SocialService.installProvider(data, installCallback, options); }, - uninstallProvider: function(origin, aCallback) { + uninstallProvider(origin, aCallback) { SocialService.uninstallProvider(origin, aCallback); }, // Activation functionality - activateFromOrigin: function(origin, callback) { + activateFromOrigin(origin, callback) { // It's OK if the provider has already been activated - we still get called // back with it. SocialService.enableProvider(origin, callback); @@ -225,7 +225,7 @@ DynamicResizeWatcher.prototype = { this.OpenGraphBuilder = { - generateEndpointURL: function(URLTemplate, pageData) { + generateEndpointURL(URLTemplate, pageData) { // support for existing oexchange style endpoints by supporting their // querystring arguments. parse the query string template and do // replacements where necessary the query names may be different than ours, diff --git a/browser/modules/SocialService.jsm b/browser/modules/SocialService.jsm index 2cc4255d1f00..c1dfce37fc20 100644 --- a/browser/modules/SocialService.jsm +++ b/browser/modules/SocialService.jsm @@ -58,7 +58,7 @@ var SocialServiceInternal = { get manifests() { return this.manifestsGenerator(); }, - getManifestPrefname: function(origin) { + getManifestPrefname(origin) { // Retrieve the prefname for a given origin/manifest. // If no existing pref, return a generated prefname. let MANIFEST_PREFS = Services.prefs.getBranch("social.manifest."); @@ -77,7 +77,7 @@ var SocialServiceInternal = { let originUri = Services.io.newURI(origin, null, null); return originUri.hostPort.replace('.', '-'); }, - orderedProviders: function(aCallback) { + orderedProviders(aCallback) { if (SocialServiceInternal.providerArray.length < 2) { schedule(function() { aCallback(SocialServiceInternal.providerArray); @@ -106,7 +106,7 @@ var SocialServiceInternal = { try { stmt.executeAsync({ - handleResult: function(aResultSet) { + handleResult(aResultSet) { let row; while ((row = aResultSet.getNextRow())) { let rh = row.getResultByName("host"); @@ -114,10 +114,10 @@ var SocialServiceInternal = { providers[rh].frecency = parseInt(frecency) || 0; } }, - handleError: function(aError) { + handleError(aError) { Cu.reportError(aError.message + " (Result = " + aError.result + ")"); }, - handleCompletion: function(aReason) { + handleCompletion(aReason) { // the query may not have returned all our providers, so we have // stamped the frecency on the provider and sort here. This makes sure // all enabled providers get sorted even with frecency zero. @@ -177,21 +177,21 @@ var ActiveProviders = { return this._providers; }, - has: function(origin) { + has(origin) { return (origin in this._providers); }, - add: function(origin) { + add(origin) { this._providers[origin] = 1; this._deferredTask.arm(); }, - delete: function(origin) { + delete(origin) { delete this._providers[origin]; this._deferredTask.arm(); }, - flush: function() { + flush() { this._deferredTask.disarm(); this._persist(); }, @@ -201,7 +201,7 @@ var ActiveProviders = { return this._deferredTask = new DeferredTask(this._persist.bind(this), 0); }, - _persist: function() { + _persist() { let string = Cc["@mozilla.org/supports-string;1"]. createInstance(Ci.nsISupportsString); string.data = JSON.stringify(this._providers); @@ -454,13 +454,13 @@ this.SocialService = { }, // Returns an unordered array of installed providers - getProviderList: function(onDone) { + getProviderList(onDone) { schedule(function() { onDone(SocialServiceInternal.providerArray); }); }, - getManifestByOrigin: function(origin) { + getManifestByOrigin(origin) { for (let manifest of SocialServiceInternal.manifests) { if (origin == manifest.origin) { return manifest; @@ -470,11 +470,11 @@ this.SocialService = { }, // Returns an array of installed providers, sorted by frecency - getOrderedProviderList: function(onDone) { + getOrderedProviderList(onDone) { SocialServiceInternal.orderedProviders(onDone); }, - getOriginActivationType: function(origin) { + getOriginActivationType(origin) { return getOriginActivationType(origin); }, @@ -486,7 +486,7 @@ this.SocialService = { this._providerListeners.delete(listener); }, - _notifyProviderListeners: function(topic, origin, providers) { + _notifyProviderListeners(topic, origin, providers) { for (let [listener, ] of this._providerListeners) { try { listener(topic, origin, providers); @@ -496,7 +496,7 @@ this.SocialService = { } }, - _manifestFromData: function(type, data, installOrigin) { + _manifestFromData(type, data, installOrigin) { let featureURLs = ['shareURL']; let resolveURLs = featureURLs.concat(['postActivationURL']); @@ -541,7 +541,7 @@ this.SocialService = { return data; }, - _showInstallNotification: function(data, aAddonInstaller) { + _showInstallNotification(data, aAddonInstaller) { let brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties"); let browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties"); @@ -560,7 +560,7 @@ this.SocialService = { let action = { label: browserBundle.GetStringFromName("service.install.ok.label"), accessKey: browserBundle.GetStringFromName("service.install.ok.accesskey"), - callback: function() { + callback() { aAddonInstaller.install(); }, }; @@ -576,7 +576,7 @@ this.SocialService = { action, [], options); }, - installProvider: function(data, installCallback, options = {}) { + installProvider(data, installCallback, options = {}) { data.installType = getOriginActivationType(data.origin); // if we get data, we MUST have a valid manifest generated from the data let manifest = this._manifestFromData(data.installType, data.manifest, data.origin); @@ -611,7 +611,7 @@ this.SocialService = { }.bind(this)); }, - _installProvider: function(data, options, installCallback) { + _installProvider(data, options, installCallback) { if (!data.manifest) throw new Error("Cannot install provider without manifest data"); @@ -633,7 +633,7 @@ this.SocialService = { this._showInstallNotification(data, installer); }, - createWrapper: function(manifest) { + createWrapper(manifest) { return new AddonWrapper(manifest); }, @@ -642,7 +642,7 @@ this.SocialService = { * have knowledge of the currently selected provider here, we will notify * the front end to deal with any reload. */ - updateProvider: function(aUpdateOrigin, aManifest) { + updateProvider(aUpdateOrigin, aManifest) { let installType = this.getOriginActivationType(aUpdateOrigin); // if we get data, we MUST have a valid manifest generated from the data let manifest = this._manifestFromData(installType, aManifest, aUpdateOrigin); @@ -670,7 +670,7 @@ this.SocialService = { }, - uninstallProvider: function(origin, aCallback) { + uninstallProvider(origin, aCallback) { let manifest = SocialService.getManifestByOrigin(origin); let addon = new AddonWrapper(manifest); addon.uninstall(aCallback); @@ -716,7 +716,7 @@ function SocialProvider(input) { } SocialProvider.prototype = { - reload: function() { + reload() { // calling terminate/activate does not set the enabled state whereas setting // enabled will call terminate/activate this.enabled = false; @@ -747,7 +747,7 @@ SocialProvider.prototype = { return SocialService.getManifestByOrigin(this.origin); }, - getPageSize: function(name) { + getPageSize(name) { let manifest = this.manifest; if (manifest && manifest.pageSize) return manifest.pageSize[name]; @@ -854,11 +854,11 @@ function AddonInstaller(sourceURI, aManifest, installCallback) { } var SocialAddonProvider = { - startup: function() {}, + startup() {}, - shutdown: function() {}, + shutdown() {}, - updateAddonAppDisabledStates: function() { + updateAddonAppDisabledStates() { // we wont bother with "enabling" services that are released from blocklist for (let manifest of SocialServiceInternal.manifests) { try { @@ -874,7 +874,7 @@ var SocialAddonProvider = { } }, - getAddonByID: function(aId, aCallback) { + getAddonByID(aId, aCallback) { for (let manifest of SocialServiceInternal.manifests) { if (aId == getAddonIDFromOrigin(manifest.origin)) { aCallback(new AddonWrapper(manifest)); @@ -884,7 +884,7 @@ var SocialAddonProvider = { aCallback(null); }, - getAddonsByTypes: function(aTypes, aCallback) { + getAddonsByTypes(aTypes, aCallback) { if (aTypes && aTypes.indexOf(ADDON_TYPE_SERVICE) == -1) { aCallback([]); return; @@ -892,7 +892,7 @@ var SocialAddonProvider = { aCallback([...SocialServiceInternal.manifests].map(a => new AddonWrapper(a))); }, - removeAddon: function(aAddon, aCallback) { + removeAddon(aAddon, aCallback) { AddonManagerPrivate.callAddonListeners("onUninstalling", aAddon, false); aAddon.pendingOperations |= AddonManager.PENDING_UNINSTALL; Services.prefs.clearUserPref(getPrefnameFromOrigin(aAddon.manifest.origin)); @@ -943,7 +943,7 @@ AddonWrapper.prototype = { return false; }, - isCompatibleWith: function(appVersion, platformVersion) { + isCompatibleWith(appVersion, platformVersion) { return true; }, @@ -993,7 +993,7 @@ AddonWrapper.prototype = { return permissions; }, - findUpdates: function(listener, reason, appVersion, platformVersion) { + findUpdates(listener, reason, appVersion, platformVersion) { if ("onNoCompatibilityUpdateAvailable" in listener) listener.onNoCompatibilityUpdateAvailable(this); if ("onNoUpdateAvailable" in listener) @@ -1069,7 +1069,7 @@ AddonWrapper.prototype = { return val; }, - uninstall: function(aCallback) { + uninstall(aCallback) { let prefName = getPrefnameFromOrigin(this.manifest.origin); if (Services.prefs.prefHasUserValue(prefName)) { if (ActiveProviders.has(this.manifest.origin)) { @@ -1084,7 +1084,7 @@ AddonWrapper.prototype = { } }, - cancelUninstall: function() { + cancelUninstall() { this._pending -= AddonManager.PENDING_UNINSTALL; AddonManagerPrivate.callAddonListeners("onOperationCancelled", this); } diff --git a/browser/modules/TransientPrefs.jsm b/browser/modules/TransientPrefs.jsm index aa2bd20c9ab2..a12c3c2c94d6 100644 --- a/browser/modules/TransientPrefs.jsm +++ b/browser/modules/TransientPrefs.jsm @@ -15,7 +15,7 @@ var prefVisibility = new Map; application. */ this.TransientPrefs = { - prefShouldBeVisible: function(prefName) { + prefShouldBeVisible(prefName) { if (Preferences.isSet(prefName)) prefVisibility.set(prefName, true); diff --git a/browser/modules/URLBarZoom.jsm b/browser/modules/URLBarZoom.jsm index 3e1c0f70761c..c496c339bbbc 100644 --- a/browser/modules/URLBarZoom.jsm +++ b/browser/modules/URLBarZoom.jsm @@ -11,7 +11,7 @@ Components.utils.import("resource://gre/modules/Services.jsm"); var URLBarZoom = { - init: function(aWindow) { + init(aWindow) { // Register ourselves with the service so we know when the zoom prefs change. Services.obs.addObserver(updateZoomButton, "browser-fullZoom:zoomChange", false); Services.obs.addObserver(updateZoomButton, "browser-fullZoom:zoomReset", false); diff --git a/browser/modules/Windows8WindowFrameColor.jsm b/browser/modules/Windows8WindowFrameColor.jsm index 911333747f6f..245ced4aea5e 100644 --- a/browser/modules/Windows8WindowFrameColor.jsm +++ b/browser/modules/Windows8WindowFrameColor.jsm @@ -14,7 +14,7 @@ var Registry = Cu.import("resource://gre/modules/WindowsRegistry.jsm").WindowsRe var Windows8WindowFrameColor = { _windowFrameColor: null, - get: function() { + get() { if (this._windowFrameColor) return this._windowFrameColor; diff --git a/browser/modules/WindowsJumpLists.jsm b/browser/modules/WindowsJumpLists.jsm index fff70148690f..8f4088cf257f 100644 --- a/browser/modules/WindowsJumpLists.jsm +++ b/browser/modules/WindowsJumpLists.jsm @@ -426,7 +426,7 @@ this.WinTaskbarJumpList = // Return the pending statement to the caller, to allow cancelation. return PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase) .asyncExecuteLegacyQueries([query], 1, options, { - handleResult: function(aResultSet) { + handleResult(aResultSet) { for (let row; (row = aResultSet.getNextRow());) { try { aCallback.call(aScope, @@ -436,11 +436,11 @@ this.WinTaskbarJumpList = } catch (e) {} } }, - handleError: function(aError) { + handleError(aError) { Components.utils.reportError( "Async execution error (" + aError.result + "): " + aError.message); }, - handleCompletion: function(aReason) { + handleCompletion(aReason) { aCallback.call(WinTaskbarJumpList, null); }, }); diff --git a/browser/modules/WindowsPreviewPerTab.jsm b/browser/modules/WindowsPreviewPerTab.jsm index 66488310f2eb..04d76feb4fbc 100644 --- a/browser/modules/WindowsPreviewPerTab.jsm +++ b/browser/modules/WindowsPreviewPerTab.jsm @@ -72,7 +72,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "PageThumbs", // nsIURI -> imgIContainer function _imageFromURI(uri, privateMode, callback) { let channel = NetUtil.newChannel({ - uri: uri, + uri, loadUsingSystemPrincipal: true, contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE }); @@ -158,7 +158,7 @@ PreviewController.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsITaskbarPreviewController, Ci.nsIDOMEventListener]), - destroy: function() { + destroy() { this.tab.removeEventListener("TabAttrModified", this, false); // Break cycles, otherwise we end up leaking the window with everything @@ -172,7 +172,7 @@ PreviewController.prototype = { }, // Resizes the canvasPreview to 0x0, essentially freeing its memory. - resetCanvasPreview: function() { + resetCanvasPreview() { this.canvasPreview.width = 0; this.canvasPreview.height = 0; }, @@ -180,7 +180,7 @@ PreviewController.prototype = { /** * Set the canvas dimensions. */ - resizeCanvasPreview: function(aRequestedWidth, aRequestedHeight) { + resizeCanvasPreview(aRequestedWidth, aRequestedHeight) { this.canvasPreview.width = aRequestedWidth; this.canvasPreview.height = aRequestedHeight; }, @@ -204,13 +204,13 @@ PreviewController.prototype = { return this.tab.linkedBrowser.getBoundingClientRect(); }, - cacheBrowserDims: function() { + cacheBrowserDims() { let dims = this.browserDims; this._cachedWidth = dims.width; this._cachedHeight = dims.height; }, - testCacheBrowserDims: function() { + testCacheBrowserDims() { let dims = this.browserDims; return this._cachedWidth == dims.width && this._cachedHeight == dims.height; @@ -220,7 +220,7 @@ PreviewController.prototype = { * Capture a new thumbnail image for this preview. Called by the controller * in response to a request for a new thumbnail image. */ - updateCanvasPreview: function(aFullScale, aCallback) { + updateCanvasPreview(aFullScale, aCallback) { // Update our cached browser dims so that delayed resize // events don't trigger another invalidation if this tab becomes active. this.cacheBrowserDims(); @@ -231,7 +231,7 @@ PreviewController.prototype = { AeroPeek.resetCacheTimer(); }, - updateTitleAndTooltip: function() { + updateTitleAndTooltip() { let title = this.win.tabbrowser.getWindowTitleForBrowser(this.linkedBrowser); this.preview.title = title; this.preview.tooltip = title; @@ -264,7 +264,7 @@ PreviewController.prototype = { * * @param aTaskbarCallback nsITaskbarPreviewCallback results callback */ - requestPreview: function(aTaskbarCallback) { + requestPreview(aTaskbarCallback) { // Grab a high res content preview this.resetCanvasPreview(); this.updateCanvasPreview(true, (aPreviewCanvas) => { @@ -312,7 +312,7 @@ PreviewController.prototype = { * @param aRequestedWidth width of the requested thumbnail * @param aRequestedHeight height of the requested thumbnail */ - requestThumbnail: function(aTaskbarCallback, aRequestedWidth, aRequestedHeight) { + requestThumbnail(aTaskbarCallback, aRequestedWidth, aRequestedHeight) { this.resizeCanvasPreview(aRequestedWidth, aRequestedHeight); this.updateCanvasPreview(false, (aThumbnailCanvas) => { aTaskbarCallback.done(aThumbnailCanvas, false); @@ -321,11 +321,11 @@ PreviewController.prototype = { // Event handling - onClose: function() { + onClose() { this.win.tabbrowser.removeTab(this.tab); }, - onActivate: function() { + onActivate() { this.win.tabbrowser.selectedTab = this.tab; // Accept activation - this will restore the browser window @@ -334,7 +334,7 @@ PreviewController.prototype = { }, // nsIDOMEventListener - handleEvent: function(evt) { + handleEvent(evt) { switch (evt.type) { case "TabAttrModified": this.updateTitleAndTooltip(); @@ -389,7 +389,7 @@ TabWindow.prototype = { tabEvents: ["TabOpen", "TabClose", "TabSelect", "TabMove"], winEvents: ["resize"], - destroy: function() { + destroy() { this._destroying = true; let tabs = this.tabbrowser.tabs; @@ -417,17 +417,17 @@ TabWindow.prototype = { return this.win.innerHeight; }, - cacheDims: function() { + cacheDims() { this._cachedWidth = this.width; this._cachedHeight = this.height; }, - testCacheDims: function() { + testCacheDims() { return this._cachedWidth == this.width && this._cachedHeight == this.height; }, // Invoked when the given tab is added to this window - newTab: function(tab) { + newTab(tab) { let controller = new PreviewController(this, tab); // It's OK to add the preview now while the favicon still loads. this.previews.set(tab, controller.preview); @@ -437,7 +437,7 @@ TabWindow.prototype = { controller.updateTitleAndTooltip(); }, - createTabPreview: function(controller) { + createTabPreview(controller) { let docShell = this.win .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) @@ -451,7 +451,7 @@ TabWindow.prototype = { }, // Invoked when the given tab is closed - removeTab: function(tab) { + removeTab(tab) { let preview = this.previewFromTab(tab); preview.active = false; preview.visible = false; @@ -478,11 +478,11 @@ TabWindow.prototype = { this.updateTabOrdering(); }, - previewFromTab: function(tab) { + previewFromTab(tab) { return this.previews.get(tab); }, - updateTabOrdering: function() { + updateTabOrdering() { let previews = this.previews; let tabs = this.tabbrowser.tabs; @@ -505,7 +505,7 @@ TabWindow.prototype = { }, // nsIDOMEventListener - handleEvent: function(evt) { + handleEvent(evt) { let tab = evt.originalTarget; switch (evt.type) { case "TabOpen": @@ -531,7 +531,7 @@ TabWindow.prototype = { }, // Set or reset a timer that will invalidate visible thumbnails soon. - setInvalidationTimer: function() { + setInvalidationTimer() { if (!this.invalidateTimer) { this.invalidateTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); } @@ -551,7 +551,7 @@ TabWindow.prototype = { }, 1000, Ci.nsITimer.TYPE_ONE_SHOT); }, - onResize: function() { + onResize() { // Specific to a window. // Call invalidate on each tab thumbnail so that Windows will request an @@ -569,7 +569,7 @@ TabWindow.prototype = { this.setInvalidationTimer(); }, - invalidateTabPreview: function(aBrowser) { + invalidateTabPreview(aBrowser) { for (let [tab, preview] of this.previews) { if (aBrowser == tab.linkedBrowser) { preview.invalidate(); @@ -580,13 +580,13 @@ TabWindow.prototype = { // Browser progress listener - onLocationChange: function(aBrowser) { + onLocationChange(aBrowser) { // I'm not sure we need this, onStateChange does a really good job // of picking up page changes. // this.invalidateTabPreview(aBrowser); }, - onStateChange: function(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { + onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP && aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) { this.invalidateTabPreview(aBrowser); @@ -596,7 +596,7 @@ TabWindow.prototype = { directRequestProtocols: new Set([ "file", "chrome", "resource", "about" ]), - onLinkIconAvailable: function(aBrowser, aIconURL) { + onLinkIconAvailable(aBrowser, aIconURL) { let requestURL = null; if (aIconURL) { let shouldRequestFaviconURL = true; @@ -662,7 +662,7 @@ this.AeroPeek = { // Length of time in seconds that previews are cached cacheLifespan: 20, - initialize: function() { + initialize() { if (!(WINTASKBAR_CONTRACTID in Cc)) return; this.taskbar = Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar); @@ -752,25 +752,25 @@ this.AeroPeek = { } }, - addPreview: function(preview) { + addPreview(preview) { this.previews.push(preview); this.checkPreviewCount(); }, - removePreview: function(preview) { + removePreview(preview) { let idx = this.previews.indexOf(preview); this.previews.splice(idx, 1); this.checkPreviewCount(); }, - checkPreviewCount: function() { + checkPreviewCount() { if (!this._prefenabled) { return; } this.enabled = this.previews.length <= this.maxpreviews; }, - onOpenWindow: function(win) { + onOpenWindow(win) { // This occurs when the taskbar service is not available (xp, vista) if (!this.available || !this._prefenabled) return; @@ -778,7 +778,7 @@ this.AeroPeek = { win.gTaskbarTabGroup = new TabWindow(win); }, - onCloseWindow: function(win) { + onCloseWindow(win) { // This occurs when the taskbar service is not available (xp, vista) if (!this.available || !this._prefenabled) return; @@ -790,13 +790,13 @@ this.AeroPeek = { this.destroy(); }, - resetCacheTimer: function() { + resetCacheTimer() { this.cacheTimer.cancel(); this.cacheTimer.init(this, 1000 * this.cacheLifespan, Ci.nsITimer.TYPE_ONE_SHOT); }, // nsIObserver - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (aTopic == "nsPref:changed" && aData == TOGGLE_PREF_NAME) { this._prefenabled = this.prefs.getBoolPref(TOGGLE_PREF_NAME); } diff --git a/browser/modules/offlineAppCache.jsm b/browser/modules/offlineAppCache.jsm index 5d0e3481a713..cbf561943467 100644 --- a/browser/modules/offlineAppCache.jsm +++ b/browser/modules/offlineAppCache.jsm @@ -10,7 +10,7 @@ const Cc = Components.classes; const Ci = Components.interfaces; this.OfflineAppCacheHelper = { - clear: function() { + clear() { var cacheService = Cc["@mozilla.org/netwerk/cache-storage-service;1"].getService(Ci.nsICacheStorageService); var appCacheStorage = cacheService.appCacheStorage(LoadContextInfo.default, null); try { diff --git a/browser/modules/test/browser_ContentSearch.js b/browser/modules/test/browser_ContentSearch.js index 22665f21bc18..ae2f2b1b8dc8 100644 --- a/browser/modules/test/browser_ContentSearch.js +++ b/browser/modules/test/browser_ContentSearch.js @@ -97,7 +97,7 @@ add_task(function* search() { engine.getSubmission(data.searchString, "", data.whence).uri.spec; gMsgMan.sendAsyncMessage(TEST_MSG, { type: "Search", - data: data, + data, expectedURL: submissionURL, }); let msg = yield waitForTestMsg("loadStopped"); @@ -121,7 +121,7 @@ add_task(function* searchInBackgroundTab() { engine.getSubmission(data.searchString, "", data.whence).uri.spec; gMsgMan.sendAsyncMessage(TEST_MSG, { type: "Search", - data: data, + data, expectedURL: submissionURL, }); @@ -315,11 +315,11 @@ function waitForNewEngine(basename, numImages) { let addDeferred = Promise.defer(); let url = getRootDirectory(gTestPath) + basename; Services.search.addEngine(url, null, "", false, { - onSuccess: function(engine) { + onSuccess(engine) { info("Search engine added: " + basename); addDeferred.resolve(engine); }, - onError: function(errCode) { + onError(errCode) { ok(false, "addEngine failed with error code " + errCode); addDeferred.reject(); }, diff --git a/browser/modules/test/browser_PermissionUI.js b/browser/modules/test/browser_PermissionUI.js index ddb8832ebfae..f396217f7974 100644 --- a/browser/modules/test/browser_PermissionUI.js +++ b/browser/modules/test/browser_PermissionUI.js @@ -223,7 +223,7 @@ add_task(function* test_with_permission_key() { accessKey: "M", action: Ci.nsIPermissionManager.ALLOW_ACTION, expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION, - callback: function() { + callback() { allowed = true; } }; @@ -234,7 +234,7 @@ add_task(function* test_with_permission_key() { accessKey: "D", action: Ci.nsIPermissionManager.DENY_ACTION, expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION, - callback: function() { + callback() { denied = true; } }; @@ -376,7 +376,7 @@ add_task(function* test_no_request() { let mainAction = { label: "Allow", accessKey: "M", - callback: function() { + callback() { allowed = true; } }; @@ -385,7 +385,7 @@ add_task(function* test_no_request() { let secondaryAction = { label: "Deny", accessKey: "D", - callback: function() { + callback() { denied = true; } }; diff --git a/browser/modules/test/browser_ProcessHangNotifications.js b/browser/modules/test/browser_ProcessHangNotifications.js index 715801b35b66..87a7c8811a8c 100644 --- a/browser/modules/test/browser_ProcessHangNotifications.js +++ b/browser/modules/test/browser_ProcessHangNotifications.js @@ -44,7 +44,7 @@ let gTestHangReport = { TEST_CALLBACK_TERMPLUGIN: 3, _hangType: 1, - _tcb: function(aCallbackType) {}, + _tcb(aCallbackType) {}, get hangType() { return this._hangType; @@ -58,26 +58,26 @@ let gTestHangReport = { this._tcb = aValue; }, - QueryInterface: function(aIID) { + QueryInterface(aIID) { if (aIID.equals(Components.interfaces.nsIHangReport) || aIID.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_NOINTERFACE; }, - userCanceled: function() { + userCanceled() { this._tcb(this.TEST_CALLBACK_CANCELED); }, - terminateScript: function() { + terminateScript() { this._tcb(this.TEST_CALLBACK_TERMSCRIPT); }, - terminatePlugin: function() { + terminatePlugin() { this._tcb(this.TEST_CALLBACK_TERMPLUGIN); }, - isReportForBrowser: function(aFrameLoader) { + isReportForBrowser(aFrameLoader) { return true; } }; diff --git a/browser/modules/test/contentSearch.js b/browser/modules/test/contentSearch.js index fda68a7a4104..8b2b498da7a8 100644 --- a/browser/modules/test/contentSearch.js +++ b/browser/modules/test/contentSearch.js @@ -30,7 +30,7 @@ addMessageListener(TEST_MSG, msg => { waitForLoadAndStopIt(msg.data.expectedURL, url => { sendAsyncMessage(TEST_MSG, { type: "loadStopped", - url: url, + url, }); }); } @@ -41,7 +41,7 @@ function waitForLoadAndStopIt(expectedURL, callback) { let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); let listener = { - onStateChange: function(webProg, req, flags, status) { + onStateChange(webProg, req, flags, status) { if (req instanceof Ci.nsIChannel) { let url = req.originalURI.spec; dump("waitForLoadAndStopIt: onStateChange " + url + "\n"); diff --git a/browser/modules/test/unit/social/head.js b/browser/modules/test/unit/social/head.js index b7f06d33b2d4..0a94f536deec 100644 --- a/browser/modules/test/unit/social/head.js +++ b/browser/modules/test/unit/social/head.js @@ -132,7 +132,7 @@ function AsyncRunner() { this._callbacks = { done: do_test_finished, - error: function(err) { + error(err) { // xpcshell test functions like do_check_eq throw NS_ERROR_ABORT on // failure. Ignore those so they aren't rethrown here. if (err !== Cr.NS_ERROR_ABORT) { @@ -143,7 +143,7 @@ function AsyncRunner() { do_throw(err); } }, - consoleError: function(scriptErr) { + consoleError(scriptErr) { // Try to ensure the error is related to the test. let filename = scriptErr.sourceName || scriptErr.toString() || ""; if (filename.indexOf("/toolkit/components/social/") >= 0) diff --git a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js index b74250fc69c4..a72dbd492e4d 100644 --- a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js +++ b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js @@ -247,7 +247,7 @@ function setTimeout(fun, timeout) { let timer = Components.classes["@mozilla.org/timer;1"] .createInstance(Components.interfaces.nsITimer); var event = { - notify: function() { + notify() { fun(); } }; @@ -1062,7 +1062,7 @@ add_task(function* test_DirectoryLinksProvider_getEnhancedLink() { do_check_eq(links.length, 0); // There are no directory links. function checkEnhanced(url, image) { - let enhanced = DirectoryLinksProvider.getEnhancedLink({url: url}); + let enhanced = DirectoryLinksProvider.getEnhancedLink({url}); do_check_eq(enhanced && enhanced.enhancedImageURI, image); } @@ -1487,7 +1487,7 @@ add_task(function* test_DirectoryLinksProvider_getFrequencyCapReportSiteAction() targetedSite: "foo.com", url: "bar.com" }, - isPinned: function() { return false; }, + isPinned() { return false; }, }], "view", 0); // read file content and ensure that view counters are updated @@ -1531,9 +1531,9 @@ add_task(function* test_DirectoryLinksProvider_ClickRemoval() { }] }, { - handleError: function() { do_check_true(false); }, - handleResult: function() {}, - handleCompletion: function() { resolve(); } + handleError() { do_check_true(false); }, + handleResult() {}, + handleCompletion() { resolve(); } } ); }); @@ -1827,7 +1827,7 @@ add_task(function* test_blockSuggestedTiles() { // block suggested tile in a regular way DirectoryLinksProvider.reportSitesAction([{ - isPinned: function() { return false; }, + isPinned() { return false; }, link: Object.assign({frecency: 1000}, suggestedLink) }], "block", 0); diff --git a/browser/modules/webrtcUI.jsm b/browser/modules/webrtcUI.jsm index 4f818a6194d1..fd40ca0cf1fb 100644 --- a/browser/modules/webrtcUI.jsm +++ b/browser/modules/webrtcUI.jsm @@ -29,7 +29,7 @@ this.webrtcUI = { peerConnectionBlockers: new Set(), emitter: new EventEmitter(), - init: function() { + init() { Services.obs.addObserver(maybeAddMenuIndicator, "browser-delayed-startup-finished", false); let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] @@ -47,7 +47,7 @@ this.webrtcUI = { mm.addMessageListener("webrtc:UpdateBrowserIndicators", this); }, - uninit: function() { + uninit() { Services.obs.removeObserver(maybeAddMenuIndicator, "browser-delayed-startup-finished"); let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] @@ -113,7 +113,7 @@ this.webrtcUI = { _streams: [], // The boolean parameters indicate which streams should be included in the result. - getActiveStreams: function(aCamera, aMicrophone, aScreen) { + getActiveStreams(aCamera, aMicrophone, aScreen) { return webrtcUI._streams.filter(aStream => { let state = aStream.state; return aCamera && state.camera || @@ -127,22 +127,22 @@ this.webrtcUI = { let browserWindow = browser.ownerGlobal; let tab = browserWindow.gBrowser && browserWindow.gBrowser.getTabForBrowser(browser); - return {uri: state.documentURI, tab: tab, browser: browser, types: types}; + return {uri: state.documentURI, tab, browser, types}; }); }, - swapBrowserForNotification: function(aOldBrowser, aNewBrowser) { + swapBrowserForNotification(aOldBrowser, aNewBrowser) { for (let stream of this._streams) { if (stream.browser == aOldBrowser) stream.browser = aNewBrowser; } }, - forgetStreamsFromBrowser: function(aBrowser) { + forgetStreamsFromBrowser(aBrowser) { this._streams = this._streams.filter(stream => stream.browser != aBrowser); }, - showSharingDoorhanger: function(aActiveStream) { + showSharingDoorhanger(aActiveStream) { let browserWindow = aActiveStream.browser.ownerGlobal; if (aActiveStream.tab) { browserWindow.gBrowser.selectedTab = aActiveStream.tab; @@ -165,7 +165,7 @@ this.webrtcUI = { identityBox.click(); }, - updateWarningLabel: function(aMenuList) { + updateWarningLabel(aMenuList) { let type = aMenuList.selectedItem.getAttribute("devicetype"); let document = aMenuList.ownerDocument; document.getElementById("webRTC-all-windows-shared").hidden = type != "Screen"; @@ -195,23 +195,23 @@ this.webrtcUI = { // is canceled. (This would typically be used in // conjunction with a blocking handler to cancel // a user prompt or other work done by the handler) - addPeerConnectionBlocker: function(aCallback) { + addPeerConnectionBlocker(aCallback) { this.peerConnectionBlockers.add(aCallback); }, - removePeerConnectionBlocker: function(aCallback) { + removePeerConnectionBlocker(aCallback) { this.peerConnectionBlockers.delete(aCallback); }, - on: function(...args) { + on(...args) { return this.emitter.on(...args); }, - off: function(...args) { + off(...args) { return this.emitter.off(...args); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "rtcpeer:Request": { @@ -348,14 +348,14 @@ function prompt(aBrowser, aRequest) { // The real callback will be set during the "showing" event. The // empty function here is so that PopupNotifications.show doesn't // reject the action. - callback: function() {} + callback() {} }; let secondaryActions = [ { label: stringBundle.getString("getUserMedia.dontAllow.label"), accessKey: stringBundle.getString("getUserMedia.dontAllow.accesskey"), - callback: function(aState) { + callback(aState) { denyRequest(notification.browser, aRequest); if (aState && aState.checkboxChecked) { let perms = Services.perms; @@ -393,7 +393,7 @@ function prompt(aBrowser, aRequest) { [productName]) } : undefined, }, - eventCallback: function(aTopic, aNewBrowser) { + eventCallback(aTopic, aNewBrowser) { if (aTopic == "swapping") return true; @@ -746,11 +746,11 @@ function getGlobalIndicator() { _statusBar: Cc["@mozilla.org/widget/macsystemstatusbar;1"] .getService(Ci.nsISystemStatusBar), - _command: function(aEvent) { + _command(aEvent) { webrtcUI.showSharingDoorhanger(aEvent.target.stream); }, - _popupShowing: function(aEvent) { + _popupShowing(aEvent) { let type = this.getAttribute("type"); let activeStreams; if (type == "Camera") { @@ -809,12 +809,12 @@ function getGlobalIndicator() { return true; }, - _popupHiding: function(aEvent) { + _popupHiding(aEvent) { while (this.firstChild) this.firstChild.remove(); }, - _setIndicatorState: function(aName, aState) { + _setIndicatorState(aName, aState) { let field = "_" + aName.toLowerCase(); if (aState && !this[field]) { let menu = this._hiddenDoc.createElement("menu"); @@ -840,12 +840,12 @@ function getGlobalIndicator() { this[field] = null } }, - updateIndicatorState: function() { + updateIndicatorState() { this._setIndicatorState("Camera", webrtcUI.showCameraIndicator); this._setIndicatorState("Microphone", webrtcUI.showMicrophoneIndicator); this._setIndicatorState("Screen", webrtcUI.showScreenSharingIndicator); }, - close: function() { + close() { this._setIndicatorState("Camera", false); this._setIndicatorState("Microphone", false); this._setIndicatorState("Screen", false); diff --git a/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm b/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm index 557b867b9bf1..5feb7bd17093 100644 --- a/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm +++ b/browser/tools/mozscreenshots/mozscreenshots/extension/TestRunner.jsm @@ -150,7 +150,7 @@ this.TestRunner = { // helpers - _performCombo: function*(combo) { + *_performCombo(combo) { let paddedComboIndex = padLeft(this.currentComboIndex + 1, String(this.combos.length).length); log.info("Combination " + paddedComboIndex + "/" + this.combos.length + ": " + this._comboName(combo).substring(1)); diff --git a/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm b/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm index 97d8354d5b0a..f501ea140422 100644 --- a/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm +++ b/browser/tools/mozscreenshots/mozscreenshots/extension/configurations/Buttons.jsm @@ -64,7 +64,7 @@ this.Buttons = { function createWidget() { let id = "screenshot-widget"; let spec = { - id: id, + id, label: "My Button", removable: true, tooltiptext: "", diff --git a/storage/test/unit/head_storage.js b/storage/test/unit/head_storage.js index 27a4749eda18..ab05e10b593b 100644 --- a/storage/test/unit/head_storage.js +++ b/storage/test/unit/head_storage.js @@ -316,15 +316,15 @@ function openAsyncDatabase(file, options) { function executeAsync(statement, onResult) { let deferred = Promise.defer(); statement.executeAsync({ - handleError: function(error) { + handleError(error) { deferred.reject(error); }, - handleResult: function(result) { + handleResult(result) { if (onResult) { onResult(result); } }, - handleCompletion: function(result) { + handleCompletion(result) { deferred.resolve(result); } }); @@ -334,15 +334,15 @@ function executeAsync(statement, onResult) { function executeMultipleStatementsAsync(db, statements, onResult) { let deferred = Promise.defer(); db.executeAsync(statements, statements.length, { - handleError: function(error) { + handleError(error) { deferred.reject(error); }, - handleResult: function(result) { + handleResult(result) { if (onResult) { onResult(result); } }, - handleCompletion: function(result) { + handleCompletion(result) { deferred.resolve(result); } }); diff --git a/toolkit/.eslintrc.js b/toolkit/.eslintrc.js index c79d8702d966..5eec2b565574 100644 --- a/toolkit/.eslintrc.js +++ b/toolkit/.eslintrc.js @@ -163,6 +163,9 @@ module.exports = { // No using with "no-with": "error", + // Require object-literal shorthand with ES6 method syntax + "object-shorthand": ["error", "always", { "avoidQuotes": true }], + // No spacing inside rest or spread expressions "rest-spread-spacing": "error", diff --git a/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js b/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js index 4cbd141f7662..091a8a6750db 100644 --- a/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js +++ b/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js @@ -114,7 +114,7 @@ function loadData() { if (destIndex == 0) { // create the initial frame renderData.push({ - timestamp: timestamp, + timestamp, rects: {}, }); } else if (renderData[destIndex - 1].timestamp == timestamp) { diff --git a/toolkit/components/aboutmemory/content/aboutMemory.js b/toolkit/components/aboutmemory/content/aboutMemory.js index c62416dc5427..7856aa9feb57 100644 --- a/toolkit/components/aboutmemory/content/aboutMemory.js +++ b/toolkit/components/aboutmemory/content/aboutMemory.js @@ -498,7 +498,7 @@ function dumpGCLogAndCCLog(aVerbose) dumper.dumpGCAndCCLogsToFile("", aVerbose, /* dumpChildProcesses = */ true, { onDump: displayInfo, - onFinish: function() { + onFinish() { inProgress.remove(); } }); @@ -657,12 +657,12 @@ function loadMemoryReportsFromFile(aFilename, aTitleNote, aFn) let converter = new nsGzipConverter(); converter.asyncConvertData("gzip", "uncompressed", { data: [], - onStartRequest: function(aR, aC) {}, - onDataAvailable: function(aR, aC, aStream, aO, aCount) { + onStartRequest(aR, aC) {}, + onDataAvailable(aR, aC, aStream, aO, aCount) { let bi = new nsBinaryStream(aStream); this.data.push(bi.readBytes(aCount)); }, - onStopRequest: function(aR, aC, aStatusCode) { + onStopRequest(aR, aC, aStatusCode) { try { if (!Components.isSuccessCode(aStatusCode)) { throw new Components.Exception("Error while reading gzip file", aStatusCode); @@ -746,7 +746,7 @@ function DReport(aKind, aUnits, aAmount, aDescription, aNMerged, aPresence) } DReport.prototype = { - assertCompatible: function(aKind, aUnits) + assertCompatible(aKind, aUnits) { assert(this._kind == aKind, "Mismatched kinds"); assert(this._units == aUnits, "Mismatched units"); @@ -767,13 +767,13 @@ DReport.prototype = { // the descriptions to differ seems reasonable.) }, - merge: function(aJr) { + merge(aJr) { this.assertCompatible(aJr.kind, aJr.units); this._amount += aJr.amount; this._nMerged++; }, - toJSON: function(aProcess, aPath, aAmount) { + toJSON(aProcess, aPath, aAmount) { return { process: aProcess, path: aPath, @@ -1126,7 +1126,7 @@ function TreeNode(aUnsafeName, aUnits, aIsDegenerate) } TreeNode.prototype = { - findKid: function(aUnsafeName) { + findKid(aUnsafeName) { if (this._kids) { for (let i = 0; i < this._kids.length; i++) { if (this._kids[i]._unsafeName === aUnsafeName) { @@ -1143,7 +1143,7 @@ TreeNode.prototype = { // things. So for a non-leaf node, instead of just looking at _amount, we // instead look at the maximum absolute value of the node and all of its // descendants. - maxAbsDescendant: function() { + maxAbsDescendant() { if (!this._kids) { // No kids? Just return the absolute value of the amount. return Math.abs(this._amount); @@ -1163,7 +1163,7 @@ TreeNode.prototype = { return max; }, - toString: function() { + toString() { switch (this._units) { case UNITS_BYTES: return formatBytes(this._amount); case UNITS_COUNT: diff --git a/toolkit/components/aboutperformance/content/aboutPerformance.js b/toolkit/components/aboutperformance/content/aboutPerformance.js index 862d3cf0e249..f1b04df719df 100644 --- a/toolkit/components/aboutperformance/content/aboutPerformance.js +++ b/toolkit/components/aboutperformance/content/aboutPerformance.js @@ -72,7 +72,7 @@ const MODE_GLOBAL = "global"; const MODE_RECENT = "recent"; let tabFinder = { - update: function() { + update() { this._map = new Map(); let windows = Services.wm.getEnumerator("navigator:browser"); while (windows.hasMoreElements()) { @@ -97,7 +97,7 @@ let tabFinder = { * @return {{tabbrowser: , tab: }} The * tabbrowser and tab if the latter could be found. */ - get: function(id) { + get(id) { let browser = this._map.get(id); if (!browser) { return null; @@ -106,7 +106,7 @@ let tabFinder = { return {tabbrowser, tab:tabbrowser.getTabForBrowser(browser)}; }, - getAny: function(ids) { + getAny(ids) { for (let id of ids) { let result = this.get(id); if (result) { @@ -258,7 +258,7 @@ Delta.prototype = { /** * Initialize, asynchronously. */ - promiseInit: function() { + promiseInit() { if (this.kind == "webpages") { return this._initWebpage(); } else if (this.kind == "addons") { @@ -266,7 +266,7 @@ Delta.prototype = { } throw new TypeError(); }, - _initWebpage: function() { + _initWebpage() { this._initialized = true; let found = tabFinder.getAny(this.diff.windowIds); if (!found || found.tab.linkedBrowser.contentTitle == null) { @@ -296,7 +296,7 @@ Delta.prototype = { this._show = found; this.fullName = this.diff.addonId; }), - toString: function() { + toString() { return `[Delta] ${this.diff.key} => ${this.readableName}, ${this.fullName}`; } }; @@ -444,14 +444,14 @@ var State = { /** * @return {Promise} */ - promiseDeltaSinceStartOfTime: function() { + promiseDeltaSinceStartOfTime() { return this._promiseDeltaSince(this._oldest); }, /** * @return {Promise} */ - promiseDeltaSinceStartOfBuffer: function() { + promiseDeltaSinceStartOfBuffer() { return this._promiseDeltaSince(this._buffer[0]); }, @@ -528,10 +528,10 @@ var View = { * @return {null} If the `deltaKey` doesn't have a component cached yet. * Otherwise, the value stored with `set`. */ - get: function(deltaKey) { + get(deltaKey) { return this._map.get(deltaKey); }, - set: function(deltaKey, value) { + set(deltaKey, value) { this._map.set(deltaKey, value); }, /** @@ -539,7 +539,7 @@ var View = { * * @param {Set} set a set of deltaKey. */ - trimTo: function(set) { + trimTo(set) { let remove = []; for (let key of this._map.keys()) { if (!set.has(key)) { @@ -560,7 +560,7 @@ var View = { * @param {string} nature The nature of the subset. One of "addons", "webpages" or "system". * @param {string} currentMode The current display mode. One of MODE_GLOBAL or MODE_RECENT. */ - updateCategory: function(subset, id, nature, currentMode) { + updateCategory(subset, id, nature, currentMode) { subset = subset.slice().sort(Delta.revCompare); let watcherAlerts = null; @@ -657,7 +657,7 @@ var View = { this._insertElements(toAdd, id); }, - _insertElements: function(elements, id) { + _insertElements(elements, id) { let eltContainer = document.getElementById(id); eltContainer.classList.remove("measuring"); eltContainer.eltVisibleContent.innerHTML = ""; @@ -681,7 +681,7 @@ var View = { eltContainer.textContent = "Nothing"; } }, - _setupStructure: function(id) { + _setupStructure(id) { let eltContainer = document.getElementById(id); if (!eltContainer.eltVisibleContent) { eltContainer.eltVisibleContent = document.createElement("ul"); @@ -712,7 +712,7 @@ var View = { return eltContainer; }, - _grabOrCreateElements: function(delta, nature) { + _grabOrCreateElements(delta, nature) { let cachedElements = this.DOMCache.get(delta.key); if (cachedElements) { if (cachedElements.eltRoot.parentElement) { @@ -857,7 +857,7 @@ var View = { }; var Control = { - init: function() { + init() { this._initAutorefresh(); this._initDisplayMode(); }, @@ -886,7 +886,7 @@ var Control = { // Inform watchers Services.obs.notifyObservers(null, UPDATE_COMPLETE_TOPIC, mode); }), - _setOptions: function(options) { + _setOptions(options) { dump(`about:performance _setOptions ${JSON.stringify(options)}\n`); let eltRefresh = document.getElementById("check-autorefresh"); if ((options.autoRefresh > 0) != eltRefresh.checked) { @@ -897,7 +897,7 @@ var Control = { eltCheckRecent.click(); } }, - _initAutorefresh: function() { + _initAutorefresh() { let onRefreshChange = (shouldUpdateNow = false) => { if (eltRefresh.checked == !!this._autoRefreshInterval) { // Nothing to change. @@ -920,7 +920,7 @@ var Control = { onRefreshChange(false); }, _autoRefreshInterval: null, - _initDisplayMode: function() { + _initDisplayMode() { let onModeChange = (shouldUpdateNow) => { if (eltCheckRecent.checked) { this._displayMode = MODE_RECENT; @@ -956,7 +956,7 @@ var SubprocessMonitor = { * Init will start the process of updating the table if the page is not hidden, * and set up an event listener for handling visibility changes. */ - init: function() { + init() { if (!document.hidden) { SubprocessMonitor.updateTable(); } @@ -967,7 +967,7 @@ var SubprocessMonitor = { * This function updates the table after an interval if the page is visible * and clears the interval otherwise. */ - handleVisibilityChange: function() { + handleVisibilityChange() { if (!document.hidden) { SubprocessMonitor.queueUpdate(); } else { @@ -980,7 +980,7 @@ var SubprocessMonitor = { * This function queues a timer to request the next summary using updateTable * after some delay. */ - queueUpdate: function() { + queueUpdate() { this._timeout = setTimeout(() => this.updateTable(), UPDATE_INTERVAL_MS); }, @@ -990,7 +990,7 @@ var SubprocessMonitor = { * @param {object} summaries The object with the updated RSS and USS values. * @param {string} pid The pid represented by the row for which we update. */ - updateRow: function(row, summaries, pid) { + updateRow(row, summaries, pid) { row.cells[0].textContent = pid; let RSSval = DownloadUtils.convertByteUnits(summaries[pid].rss); row.cells[1].textContent = RSSval.join(" "); @@ -1002,7 +1002,7 @@ var SubprocessMonitor = { * This function adds a row to the subprocess-performance table for every new pid * and populates and regularly updates it with RSS/USS measurements. */ - updateTable: function() { + updateTable() { if (!document.hidden) { Memory.summary().then((summaries) => { if (!(Object.keys(summaries).length)) { diff --git a/toolkit/components/addoncompat/CompatWarning.jsm b/toolkit/components/addoncompat/CompatWarning.jsm index b32409a46b6b..2e9fd5ad6be7 100644 --- a/toolkit/components/addoncompat/CompatWarning.jsm +++ b/toolkit/components/addoncompat/CompatWarning.jsm @@ -27,7 +27,7 @@ var CompatWarning = { // might only want to warn about it if the listener actually // fires. However, we want the warning to show a stack for the // registration site. - delayedWarning: function(msg, addon, warning) { + delayedWarning(msg, addon, warning) { function isShimLayer(filename) { return filename.indexOf("CompatWarning.jsm") != -1 || filename.indexOf("RemoteAddonsParent.jsm") != -1 || @@ -86,7 +86,7 @@ var CompatWarning = { }; }, - warn: function(msg, addon, warning) { + warn(msg, addon, warning) { let delayed = this.delayedWarning(msg, addon, warning); delayed(); }, diff --git a/toolkit/components/addoncompat/Prefetcher.jsm b/toolkit/components/addoncompat/Prefetcher.jsm index 2d836690cc23..3dd59e1f1609 100644 --- a/toolkit/components/addoncompat/Prefetcher.jsm +++ b/toolkit/components/addoncompat/Prefetcher.jsm @@ -314,7 +314,7 @@ function Database(trigger, addons) Database.prototype = { // Add an object to a table. - add: function(table, obj) { + add(table, obj) { if (!this.tables.has(table)) { this.tables.set(table, new Set()); } @@ -327,13 +327,13 @@ Database.prototype = { this.todo.push([table, obj]); }, - cache: function(...args) { + cache(...args) { this.cached.push(args); }, // Run a fixed-point iteration that adds objects to table based on // this.rules until there are no more objects to add. - process: function() { + process() { while (this.todo.length) { let [table, obj] = this.todo.pop(); let rules = this.rules.get(table); @@ -348,7 +348,7 @@ Database.prototype = { }; var Prefetcher = { - init: function() { + init() { // Give an index to each rule and store it in this.ruleMap based // on the index. The index is used to serialize and deserialize // data from content to chrome. @@ -368,7 +368,7 @@ var Prefetcher = { Services.obs.addObserver(this, "xpcom-shutdown", false); }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic == "xpcom-shutdown") { Services.prefs.removeObserver(PREF_PREFETCHING_ENABLED, this); Services.obs.removeObserver(this, "xpcom-shutdown"); @@ -381,7 +381,7 @@ var Prefetcher = { // described by the trigger string. |addons| is a list of addons // that have listeners installed for the event. |args| is // event-specific data (such as the event object). - prefetch: function(trigger, addons, args) { + prefetch(trigger, addons, args) { if (!this.prefetchingEnabled) { return [[], []]; } @@ -425,7 +425,7 @@ var Prefetcher = { // Generate a two-level mapping based on cached data received from // the content process. - generateCache: function(prefetched, cpows) { + generateCache(prefetched, cpows) { let cache = new Map(); for (let item of prefetched) { // Replace anything of the form {cpow: } with the actual @@ -446,7 +446,7 @@ var Prefetcher = { // Run |func|, using the prefetched data in |prefetched| and |cpows| // as a cache. - withPrefetching: function(prefetched, cpows, func) { + withPrefetching(prefetched, cpows, func) { if (!this.prefetchingEnabled) { return func(); } @@ -466,7 +466,7 @@ var Prefetcher = { // Called by shim code in the chrome process to check if target.prop // is cached. - lookupInCache: function(addon, target, prop) { + lookupInCache(addon, target, prop) { if (!this.cache || !Cu.isCrossProcessWrapper(target)) { return null; } diff --git a/toolkit/components/addoncompat/RemoteAddonsChild.jsm b/toolkit/components/addoncompat/RemoteAddonsChild.jsm index 1aacc7f7abf3..9e430a44e90e 100644 --- a/toolkit/components/addoncompat/RemoteAddonsChild.jsm +++ b/toolkit/components/addoncompat/RemoteAddonsChild.jsm @@ -45,7 +45,7 @@ function setDefault(dict, key, default_) // In the child, clients can watch for changes to all paths that start // with a given component. var NotificationTracker = { - init: function() { + init() { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); cpmm.addMessageListener("Addons:ChangeNotification", this); @@ -54,7 +54,7 @@ var NotificationTracker = { this._watchers = {}; }, - receiveMessage: function(msg) { + receiveMessage(msg) { let path = msg.data.path; let count = msg.data.count; @@ -72,7 +72,7 @@ var NotificationTracker = { } }, - runCallback: function(watcher, path, count) { + runCallback(watcher, path, count) { let pathString = path.join("/"); let registeredSet = this._registered.get(watcher); let registered = registeredSet.has(pathString); @@ -85,7 +85,7 @@ var NotificationTracker = { } }, - findPaths: function(prefix) { + findPaths(prefix) { if (!this._paths) { return []; } @@ -117,12 +117,12 @@ var NotificationTracker = { return result; }, - findSuffixes: function(prefix) { + findSuffixes(prefix) { let paths = this.findPaths(prefix); return paths.map(([path, count]) => path[path.length - 1]); }, - watch: function(component1, watcher) { + watch(component1, watcher) { setDefault(this._watchers, component1, []).push(watcher); this._registered.set(watcher, new Set()); @@ -132,7 +132,7 @@ var NotificationTracker = { } }, - unwatch: function(component1, watcher) { + unwatch(component1, watcher) { let watchers = this._watchers[component1]; let index = watchers.lastIndexOf(watcher); if (index > -1) { @@ -156,7 +156,7 @@ var ContentPolicyChild = { _classID: Components.ID("6e869130-635c-11e2-bcfd-0800200c9a66"), _contractID: "@mozilla.org/addon-child/policy;1", - init: function() { + init() { let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); registrar.registerFactory(this._classID, this._classDescription, this._contractID, this); @@ -167,7 +167,7 @@ var ContentPolicyChild = { Ci.nsIChannelEventSink, Ci.nsIFactory, Ci.nsISupportsWeakReference]), - track: function(path, register) { + track(path, register) { let catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager); if (register) { catMan.addCategoryEntry("content-policy", this._contractID, this._contractID, false, true); @@ -176,7 +176,7 @@ var ContentPolicyChild = { } }, - shouldLoad: function(contentType, contentLocation, requestOrigin, + shouldLoad(contentType, contentLocation, requestOrigin, node, mimeTypeGuess, extra, requestPrincipal) { let addons = NotificationTracker.findSuffixes(["content-policy"]); let [prefetched, cpows] = Prefetcher.prefetch("ContentPolicy.shouldLoad", @@ -186,12 +186,12 @@ var ContentPolicyChild = { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); let rval = cpmm.sendRpcMessage("Addons:ContentPolicy:Run", { - contentType: contentType, + contentType, contentLocation: contentLocation.spec, requestOrigin: requestOrigin ? requestOrigin.spec : null, - mimeTypeGuess: mimeTypeGuess, - requestPrincipal: requestPrincipal, - prefetched: prefetched, + mimeTypeGuess, + requestPrincipal, + prefetched, }, cpows); if (rval.length != 1) { return Ci.nsIContentPolicy.ACCEPT; @@ -200,11 +200,11 @@ var ContentPolicyChild = { return rval[0]; }, - shouldProcess: function(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) { + shouldProcess(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) { return Ci.nsIContentPolicy.ACCEPT; }, - createInstance: function(outer, iid) { + createInstance(outer, iid) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -235,7 +235,7 @@ AboutProtocolChannel.prototype = { name: null, status: Cr.NS_OK, - asyncOpen: function(listener, context) { + asyncOpen(listener, context) { // Ask the parent to synchronously read all the data from the channel. let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); @@ -277,33 +277,33 @@ AboutProtocolChannel.prototype = { Services.tm.currentThread.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL); }, - asyncOpen2: function(listener) { + asyncOpen2(listener) { // throws an error if security checks fail var outListener = contentSecManager.performSecurityCheck(this, listener); this.asyncOpen(outListener, null); }, - open: function() { + open() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - open2: function() { + open2() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - isPending: function() { + isPending() { return false; }, - cancel: function() { + cancel() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - suspend: function() { + suspend() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - resume: function() { + resume() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, @@ -318,7 +318,7 @@ function AboutProtocolInstance(contractID) } AboutProtocolInstance.prototype = { - createInstance: function(outer, iid) { + createInstance(outer, iid) { if (outer != null) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -326,7 +326,7 @@ AboutProtocolInstance.prototype = { return this.QueryInterface(iid); }, - getURIFlags: function(uri) { + getURIFlags(uri) { // Cache the result to avoid the extra IPC. if (this._uriFlags !== undefined) { return this._uriFlags; @@ -354,7 +354,7 @@ AboutProtocolInstance.prototype = { // available to CPOWs. Consequently, we return a shim channel that, // when opened, asks the parent to open the channel and read out all // the data. - newChannel: function(uri, loadInfo) { + newChannel(uri, loadInfo) { return new AboutProtocolChannel(uri, this._contractID, loadInfo); }, @@ -364,7 +364,7 @@ AboutProtocolInstance.prototype = { var AboutProtocolChild = { _classDescription: "Addon shim about: protocol handler", - init: function() { + init() { // Maps contractIDs to instances this._instances = new Map(); // Maps contractIDs to classIDs @@ -372,7 +372,7 @@ var AboutProtocolChild = { NotificationTracker.watch("about-protocol", this); }, - track: function(path, register) { + track(path, register) { let contractID = path[1]; let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); if (register) { @@ -397,11 +397,11 @@ var AboutProtocolChild = { // This code registers observers in the child whenever an add-on in // the parent asks for notifications on the given topic. var ObserverChild = { - init: function() { + init() { NotificationTracker.watch("observer", this); }, - track: function(path, register) { + track(path, register) { let topic = path[1]; if (register) { Services.obs.addObserver(this, topic, false); @@ -410,13 +410,13 @@ var ObserverChild = { } }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { let cpmm = Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsISyncMessageSender); cpmm.sendRpcMessage("Addons:Observer:Run", {}, { - topic: topic, - subject: subject, - data: data + topic, + subject, + data }); } }; @@ -433,11 +433,11 @@ function EventTargetChild(childGlobal) } EventTargetChild.prototype = { - uninit: function() { + uninit() { NotificationTracker.unwatch("event", this); }, - track: function(path, register) { + track(path, register) { let eventType = path[1]; let useCapture = path[2]; let listener = useCapture ? this.capturingHandler : this.nonCapturingHandler; @@ -448,7 +448,7 @@ EventTargetChild.prototype = { } }, - handleEvent: function(capturing, event) { + handleEvent(capturing, event) { let addons = NotificationTracker.findSuffixes(["event", event.type, capturing]); let [prefetched, cpows] = Prefetcher.prefetch("EventTarget.handleEvent", addons, @@ -459,9 +459,9 @@ EventTargetChild.prototype = { this._childGlobal.sendRpcMessage("Addons:Event:Run", {type: event.type, - capturing: capturing, + capturing, isTrusted: event.isTrusted, - prefetched: prefetched}, + prefetched}, cpows); } }; @@ -481,34 +481,34 @@ function SandboxChild(chromeGlobal) } SandboxChild.prototype = { - uninit: function() { + uninit() { this.clearSandboxes(); }, - addListener: function() { + addListener() { let webProgress = this.chromeGlobal.docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); webProgress.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION); }, - removeListener: function() { + removeListener() { let webProgress = this.chromeGlobal.docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); webProgress.removeProgressListener(this); }, - onLocationChange: function(webProgress, request, location, flags) { + onLocationChange(webProgress, request, location, flags) { this.clearSandboxes(); }, - addSandbox: function(sandbox) { + addSandbox(sandbox) { if (this.sandboxes.length == 0) { this.addListener(); } this.sandboxes.push(sandbox); }, - clearSandboxes: function() { + clearSandboxes() { if (this.sandboxes.length) { this.removeListener(); } @@ -522,7 +522,7 @@ SandboxChild.prototype = { var RemoteAddonsChild = { _ready: false, - makeReady: function() { + makeReady() { let shims = [ Prefetcher, NotificationTracker, @@ -540,7 +540,7 @@ var RemoteAddonsChild = { } }, - init: function(global) { + init(global) { if (!this._ready) { if (!Services.cpmm.initialProcessData.remoteAddonsParentInitted) { @@ -551,7 +551,7 @@ var RemoteAddonsChild = { this._ready = true; } - global.sendAsyncMessage("Addons:RegisterGlobal", {}, {global: global}); + global.sendAsyncMessage("Addons:RegisterGlobal", {}, {global}); let sandboxChild = new SandboxChild(global); global.addSandbox = sandboxChild.addSandbox.bind(sandboxChild); @@ -560,7 +560,7 @@ var RemoteAddonsChild = { return [new EventTargetChild(global), sandboxChild]; }, - uninit: function(perTabShims) { + uninit(perTabShims) { for (let shim of perTabShims) { try { shim.uninit(); diff --git a/toolkit/components/addoncompat/RemoteAddonsParent.jsm b/toolkit/components/addoncompat/RemoteAddonsParent.jsm index ec2d49758ccf..5f409a832896 100644 --- a/toolkit/components/addoncompat/RemoteAddonsParent.jsm +++ b/toolkit/components/addoncompat/RemoteAddonsParent.jsm @@ -50,13 +50,13 @@ var NotificationTracker = { // given path are present in _paths. _paths: {}, - init: function() { + init() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.initialProcessData.remoteAddonsNotificationPaths = this._paths; }, - add: function(path) { + add(path) { let tracked = this._paths; for (let component of path) { tracked = setDefault(tracked, component, {}); @@ -67,10 +67,10 @@ var NotificationTracker = { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); - ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path: path, count: count}); + ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path, count}); }, - remove: function(path) { + remove(path) { let tracked = this._paths; for (let component of path) { tracked = setDefault(tracked, component, {}); @@ -79,7 +79,7 @@ var NotificationTracker = { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); - ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path: path, count: tracked._count}); + ppmm.broadcastAsyncMessage("Addons:ChangeNotification", {path, count: tracked._count}); }, }; NotificationTracker.init(); @@ -106,7 +106,7 @@ function Interposition(name, base) // content policy is added or removed. It also runs all the registered // add-on content policies when the child asks it to do so. var ContentPolicyParent = { - init: function() { + init() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:ContentPolicy:Run", this); @@ -114,17 +114,17 @@ var ContentPolicyParent = { this._policies = new Map(); }, - addContentPolicy: function(addon, name, cid) { + addContentPolicy(addon, name, cid) { this._policies.set(name, cid); NotificationTracker.add(["content-policy", addon]); }, - removeContentPolicy: function(addon, name) { + removeContentPolicy(addon, name) { this._policies.delete(name); NotificationTracker.remove(["content-policy", addon]); }, - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { switch (aMessage.name) { case "Addons:ContentPolicy:Run": return this.shouldLoad(aMessage.data, aMessage.objects); @@ -132,7 +132,7 @@ var ContentPolicyParent = { return undefined; }, - shouldLoad: function(aData, aObjects) { + shouldLoad(aData, aObjects) { for (let policyCID of this._policies.values()) { let policy; try { @@ -196,7 +196,7 @@ CategoryManagerInterposition.methods.deleteCategoryEntry = // protocol handler in the parent and we want the child to be able to // use it. This code is pretty specific to Adblock's usage. var AboutProtocolParent = { - init: function() { + init() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:AboutProtocol:GetURIFlags", this); @@ -204,12 +204,12 @@ var AboutProtocolParent = { this._protocols = []; }, - registerFactory: function(addon, class_, className, contractID, factory) { - this._protocols.push({contractID: contractID, factory: factory}); + registerFactory(addon, class_, className, contractID, factory) { + this._protocols.push({contractID, factory}); NotificationTracker.add(["about-protocol", contractID, addon]); }, - unregisterFactory: function(addon, class_, factory) { + unregisterFactory(addon, class_, factory) { for (let i = 0; i < this._protocols.length; i++) { if (this._protocols[i].factory == factory) { NotificationTracker.remove(["about-protocol", this._protocols[i].contractID, addon]); @@ -219,7 +219,7 @@ var AboutProtocolParent = { } }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Addons:AboutProtocol:GetURIFlags": return this.getURIFlags(msg); @@ -229,7 +229,7 @@ var AboutProtocolParent = { return undefined; }, - getURIFlags: function(msg) { + getURIFlags(msg) { let uri = BrowserUtils.makeURI(msg.data.uri); let contractID = msg.data.contractID; let module = Cc[contractID].getService(Ci.nsIAboutModule); @@ -243,10 +243,10 @@ var AboutProtocolParent = { // We immediately read all the data out of the channel here and // return it to the child. - openChannel: function(msg) { + openChannel(msg) { function wrapGetInterface(cpow) { return { - getInterface: function(intf) { return cpow.getInterface(intf); } + getInterface(intf) { return cpow.getInterface(intf); } }; } @@ -292,7 +292,7 @@ var AboutProtocolParent = { let stream = channel.open2(); let data = NetUtil.readInputStreamToString(stream, stream.available(), {}); return { - data: data, + data, contentType: channel.contentType }; } catch (e) { @@ -334,23 +334,23 @@ ComponentRegistrarInterposition.methods.unregisterFactory = // in the parent because there might be non-add-on T observers that // won't expect to get notified in this case. var ObserverParent = { - init: function() { + init() { let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageBroadcaster); ppmm.addMessageListener("Addons:Observer:Run", this); }, - addObserver: function(addon, observer, topic, ownsWeak) { + addObserver(addon, observer, topic, ownsWeak) { Services.obs.addObserver(observer, "e10s-" + topic, ownsWeak); NotificationTracker.add(["observer", topic, addon]); }, - removeObserver: function(addon, observer, topic) { + removeObserver(addon, observer, topic) { Services.obs.removeObserver(observer, "e10s-" + topic); NotificationTracker.remove(["observer", topic, addon]); }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Addons:Observer:Run": this.notify(msg.objects.subject, msg.objects.topic, msg.objects.data); @@ -358,7 +358,7 @@ var ObserverParent = { } }, - notify: function(subject, topic, data) { + notify(subject, topic, data) { let e = Services.obs.enumerateObservers("e10s-" + topic); while (e.hasMoreElements()) { let obs = e.getNext().QueryInterface(Ci.nsIObserver); @@ -410,7 +410,7 @@ ObserverInterposition.methods.removeObserver = // This object is responsible for forwarding events from the child to // the parent. var EventTargetParent = { - init: function() { + init() { // The _listeners map goes from targets (either elements // or windows) to a dictionary from event types to listeners. this._listeners = new WeakMap(); @@ -426,7 +426,7 @@ var EventTargetParent = { // (the or elements), then we return the // . If it's some generic element, then we return the // window itself. - redirectEventTarget: function(target) { + redirectEventTarget(target) { if (Cu.isCrossProcessWrapper(target)) { return null; } @@ -456,12 +456,12 @@ var EventTargetParent = { // When a given event fires in the child, we fire it on the // element and the window since those are the two possible // results of redirectEventTarget. - getTargets: function(browser) { + getTargets(browser) { let window = browser.ownerDocument.defaultView; return [browser, window]; }, - addEventListener: function(addon, target, type, listener, useCapture, wantsUntrusted, delayedWarning) { + addEventListener(addon, target, type, listener, useCapture, wantsUntrusted, delayedWarning) { let newTarget = this.redirectEventTarget(target); if (!newTarget) { return; @@ -489,14 +489,14 @@ var EventTargetParent = { } } - forType.push({listener: listener, - target: target, - wantsUntrusted: wantsUntrusted, - useCapture: useCapture, - delayedWarning: delayedWarning}); + forType.push({listener, + target, + wantsUntrusted, + useCapture, + delayedWarning}); }, - removeEventListener: function(addon, target, type, listener, useCapture) { + removeEventListener(addon, target, type, listener, useCapture) { let newTarget = this.redirectEventTarget(target); if (!newTarget) { return; @@ -521,7 +521,7 @@ var EventTargetParent = { } }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Addons:Event:Run": this.dispatch(msg.target, msg.data.type, msg.data.capturing, @@ -530,7 +530,7 @@ var EventTargetParent = { } }, - dispatch: function(browser, type, capturing, isTrusted, prefetched, cpows) { + dispatch(browser, type, capturing, isTrusted, prefetched, cpows) { let event = cpows.event; let eventTarget = cpows.eventTarget; let targets = this.getTargets(browser); @@ -554,7 +554,7 @@ var EventTargetParent = { for (let [handler, target] of handlers) { let EventProxy = { - get: function(knownProps, name) { + get(knownProps, name) { if (knownProps.hasOwnProperty(name)) return knownProps[name]; return event[name]; @@ -563,8 +563,8 @@ var EventTargetParent = { let proxyEvent = new Proxy({ currentTarget: target, target: eventTarget, - type: type, - QueryInterface: function(iid) { + type, + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIDOMEventTarget)) return proxyEvent; @@ -698,7 +698,7 @@ function chromeGlobalForContentWindow(window) var SandboxParent = { componentsMap: new WeakMap(), - makeContentSandbox: function(addon, chromeGlobal, principals, ...rest) { + makeContentSandbox(addon, chromeGlobal, principals, ...rest) { CompatWarning.warn("This sandbox should be created from the child process.", addon, CompatWarning.warnings.sandboxes); if (rest.length) { @@ -733,7 +733,7 @@ var SandboxParent = { return sandbox; }, - evalInSandbox: function(code, sandbox, ...rest) { + evalInSandbox(code, sandbox, ...rest) { let cu = this.componentsMap.get(sandbox); return cu.evalInSandbox(code, sandbox, ...rest); } @@ -933,7 +933,7 @@ function wrapProgressListener(kind, listener) } let ListenerHandler = { - get: function(target, name) { + get(target, name) { if (name.startsWith("on")) { return function(...args) { listener[name].apply(listener, RemoteWebProgressManager.argumentsForAddonListener(kind, args)); @@ -1026,7 +1026,7 @@ RemoteWebNavigationInterposition.getters.sessionHistory = function(addon, target } var RemoteAddonsParent = { - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager); mm.addMessageListener("Addons:RegisterGlobal", this); @@ -1036,7 +1036,7 @@ var RemoteAddonsParent = { this.browserToGlobal = new WeakMap(); }, - getInterfaceInterpositions: function() { + getInterfaceInterpositions() { let result = {}; function register(intf, interp) { @@ -1052,7 +1052,7 @@ var RemoteAddonsParent = { return result; }, - getTaggedInterpositions: function() { + getTaggedInterpositions() { let result = {}; function register(tag, interp) { @@ -1069,7 +1069,7 @@ var RemoteAddonsParent = { return result; }, - receiveMessage: function(msg) { + receiveMessage(msg) { switch (msg.name) { case "Addons:RegisterGlobal": this.browserToGlobal.set(msg.target, msg.objects.global); diff --git a/toolkit/components/addoncompat/ShimWaiver.jsm b/toolkit/components/addoncompat/ShimWaiver.jsm index 402ab4c32247..67db8f60f5aa 100644 --- a/toolkit/components/addoncompat/ShimWaiver.jsm +++ b/toolkit/components/addoncompat/ShimWaiver.jsm @@ -5,7 +5,7 @@ this.EXPORTED_SYMBOLS = ["ShimWaiver"]; this.ShimWaiver = { - getProperty: function(obj, prop) { + getProperty(obj, prop) { let rv = obj[prop]; if (rv instanceof Function) { rv = rv.bind(obj); diff --git a/toolkit/components/addoncompat/defaultShims.js b/toolkit/components/addoncompat/defaultShims.js index a786efed7d39..c7675cad5135 100644 --- a/toolkit/components/addoncompat/defaultShims.js +++ b/toolkit/components/addoncompat/defaultShims.js @@ -22,15 +22,15 @@ DefaultInterpositionService.prototype = { classID: Components.ID("{50bc93ce-602a-4bef-bf3a-61fc749c4caf}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonInterposition, Ci.nsISupportsWeakReference]), - getWhitelist: function() { + getWhitelist() { return []; }, - interposeProperty: function(addon, target, iid, prop) { + interposeProperty(addon, target, iid, prop) { return null; }, - interposeCall: function(addonId, originalFunc, originalThis, args) { + interposeCall(addonId, originalFunc, originalThis, args) { args.splice(0, 0, addonId); return originalFunc.apply(originalThis, args); }, diff --git a/toolkit/components/addoncompat/multiprocessShims.js b/toolkit/components/addoncompat/multiprocessShims.js index 8b252a0c484a..1e5ea4f72752 100644 --- a/toolkit/components/addoncompat/multiprocessShims.js +++ b/toolkit/components/addoncompat/multiprocessShims.js @@ -102,13 +102,13 @@ AddonInterpositionService.prototype = { classID: Components.ID("{1363d5f0-d95e-11e3-9c1a-0800200c9a66}"), QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonInterposition, Ci.nsISupportsWeakReference]), - getWhitelist: function() { + getWhitelist() { return this._whitelist; }, // When the interface is not known for a method call, this code // determines the type of the target object. - getObjectTag: function(target) { + getObjectTag(target) { if (Cu.isCrossProcessWrapper(target)) { return Cu.getCrossProcessWrapperTag(target); } @@ -134,7 +134,7 @@ AddonInterpositionService.prototype = { return "generic"; }, - interposeProperty: function(addon, target, iid, prop) { + interposeProperty(addon, target, iid, prop) { let interp; if (iid) { interp = this._interfaceInterpositions[iid]; @@ -173,7 +173,7 @@ AddonInterpositionService.prototype = { return Prefetcher.lookupInCache(addon, target, prop); }, - interposeCall: function(addonId, originalFunc, originalThis, args) { + interposeCall(addonId, originalFunc, originalThis, args) { args.splice(0, 0, addonId); return originalFunc.apply(originalThis, args); }, diff --git a/toolkit/components/addoncompat/tests/addon/bootstrap.js b/toolkit/components/addoncompat/tests/addon/bootstrap.js index 5e69fee22cf9..1364346bfed7 100644 --- a/toolkit/components/addoncompat/tests/addon/bootstrap.js +++ b/toolkit/components/addoncompat/tests/addon/bootstrap.js @@ -283,7 +283,7 @@ function testAboutModuleRegistration() } TestChannel.prototype = { - asyncOpen: function(listener, context) { + asyncOpen(listener, context) { let stream = this.open(); let runnable = { run: () => { @@ -301,13 +301,13 @@ function testAboutModuleRegistration() Services.tm.currentThread.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL); }, - asyncOpen2: function(listener) { + asyncOpen2(listener) { // throws an error if security checks fail var outListener = contentSecManager.performSecurityCheck(this, listener); return this.asyncOpen(outListener, null); }, - open: function() { + open() { function getWindow(channel) { try { @@ -334,22 +334,22 @@ function testAboutModuleRegistration() return stream; }, - open2: function() { + open2() { // throws an error if security checks fail contentSecManager.performSecurityCheck(this, null); return this.open(); }, - isPending: function() { + isPending() { return false; }, - cancel: function() { + cancel() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - suspend: function() { + suspend() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, - resume: function() { + resume() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, @@ -391,7 +391,7 @@ function testAboutModuleRegistration() }; let factory = { - createInstance: function(outer, iid) { + createInstance(outer, iid) { if (outer) { throw Cr.NS_ERROR_NO_AGGREGATION; } @@ -519,7 +519,7 @@ function testProgressListener() let sawTabsLocChange = false; let globalListener = { - onLocationChange: function(webProgress, request, uri) { + onLocationChange(webProgress, request, uri) { if (uri.spec == url) { sawGlobalLocChange = true; ok(request instanceof Ci.nsIHttpChannel, "Global listener channel is an HTTP channel"); @@ -528,7 +528,7 @@ function testProgressListener() }; let tabsListener = { - onLocationChange: function(browser, webProgress, request, uri) { + onLocationChange(browser, webProgress, request, uri) { if (uri.spec == url) { sawTabsLocChange = true; ok(request instanceof Ci.nsIHttpChannel, "Tab listener channel is an HTTP channel"); diff --git a/toolkit/components/addoncompat/tests/browser/browser_addonShims.js b/toolkit/components/addoncompat/tests/browser/browser_addonShims.js index ca28782cd0c6..d2326ac16206 100644 --- a/toolkit/components/addoncompat/tests/browser/browser_addonShims.js +++ b/toolkit/components/addoncompat/tests/browser/browser_addonShims.js @@ -14,7 +14,7 @@ function addAddon(url) AddonManager.getInstallForURL(url, installer => { installer.install(); let listener = { - onInstallEnded: function(addon, addonInstall) { + onInstallEnded(addon, addonInstall) { installer.removeListener(listener); // Wait for add-on's startup scripts to execute. See bug 997408 @@ -36,7 +36,7 @@ function removeAddon(addon) return new Promise(function(resolve, reject) { let listener = { - onUninstalled: function(uninstalledAddon) { + onUninstalled(uninstalledAddon) { if (uninstalledAddon != addon) { return; } @@ -53,12 +53,12 @@ add_task(function* test_addon_shims() { yield SpecialPowers.pushPrefEnv({set: [["dom.ipc.shims.enabledWarnings", true]]}); let addon = yield addAddon(ADDON_URL); - yield window.runAddonShimTests({ok: ok, is: is, info: info}); + yield window.runAddonShimTests({ok, is, info}); yield removeAddon(addon); if (Services.appinfo.browserTabsRemoteAutostart) { addon = yield addAddon(COMPAT_ADDON_URL); - yield window.runAddonTests({ok: ok, is: is, info: info}); + yield window.runAddonTests({ok, is, info}); yield removeAddon(addon); } }); diff --git a/toolkit/components/asyncshutdown/AsyncShutdown.jsm b/toolkit/components/asyncshutdown/AsyncShutdown.jsm index 8a341edb1ba4..755cffbf1a01 100644 --- a/toolkit/components/asyncshutdown/AsyncShutdown.jsm +++ b/toolkit/components/asyncshutdown/AsyncShutdown.jsm @@ -53,7 +53,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task", XPCOMUtils.defineLazyServiceGetter(this, "gDebug", "@mozilla.org/xpcom/debug;1", "nsIDebug2"); Object.defineProperty(this, "gCrashReporter", { - get: function() { + get() { delete this.gCrashReporter; try { let reporter = Cc["@mozilla.org/xre/app-info;1"]. @@ -116,7 +116,7 @@ PromiseSet.prototype = { * @return {Promise} Resolved once all Promise have been resolved or removed, * or rejected after at least one Promise has rejected. */ - wait: function() { + wait() { // Pick an arbitrary element in the map, if any exists. let entry = this._indirections.entries().next(); if (entry.done) { @@ -139,7 +139,7 @@ PromiseSet.prototype = { * Calls to wait (including ongoing calls) will only return once * `key` has either resolved or been removed. */ - add: function(key) { + add(key) { this._ensurePromise(key); let indirection = PromiseUtils.defer(); key.then( @@ -163,7 +163,7 @@ PromiseSet.prototype = { * Calls to wait (including ongoing calls) will ignore this promise, * unless it is added again. */ - delete: function(key) { + delete(key) { this._ensurePromise(key); let value = this._indirections.get(key); if (!value) { @@ -174,7 +174,7 @@ PromiseSet.prototype = { return true; }, - _ensurePromise: function(key) { + _ensurePromise(key) { if (!key || typeof key != "object") { throw new Error("Expected an object"); } @@ -335,9 +335,9 @@ function getOrigin(topFrame, filename = null, lineNumber = null, stack = null) { } return { - filename: filename, - lineNumber: lineNumber, - stack: stack, + filename, + lineNumber, + stack, }; } catch (ex) { return { @@ -436,7 +436,7 @@ function getPhase(topic) { * // No specific guarantee about completion of profileBeforeChange * }); */ - addBlocker: function(name, condition, details = null) { + addBlocker(name, condition, details = null) { spinner.addBlocker(name, condition, details); }, /** @@ -451,7 +451,7 @@ function getPhase(topic) { * the blocker has never been installed or that the phase has * completed and the blocker has already been resolved. */ - removeBlocker: function(condition) { + removeBlocker(condition) { return spinner.removeBlocker(condition); }, @@ -499,7 +499,7 @@ Spinner.prototype = { * See the documentation of `addBlocker` in property `client` * of instances of `Barrier`. */ - addBlocker: function(name, condition, details) { + addBlocker(name, condition, details) { this._barrier.client.addBlocker(name, condition, details); }, /** @@ -513,7 +513,7 @@ Spinner.prototype = { * the blocker has never been installed or that the phase has * completed and the blocker has already been resolved. */ - removeBlocker: function(condition) { + removeBlocker(condition) { return this._barrier.client.removeBlocker(condition); }, @@ -522,7 +522,7 @@ Spinner.prototype = { }, // nsIObserver.observe - observe: function() { + observe() { let topic = this._topic; debug(`Starting phase ${ topic }`); Services.obs.removeObserver(this, topic); @@ -751,10 +751,10 @@ function Barrier(name) { } let blocker = { - trigger: trigger, - promise: promise, - name: name, - fetchState: fetchState, + trigger, + promise, + name, + fetchState, getOrigin: () => getOrigin(topFrame, filename, lineNumber, stack), }; @@ -810,11 +810,11 @@ Barrier.prototype = Object.freeze({ let {name, fetchState} = blocker; let {stack, filename, lineNumber} = blocker.getOrigin(); frozen.push({ - name: name, + name, state: safeGetState(fetchState), - filename: filename, - lineNumber: lineNumber, - stack: stack + filename, + lineNumber, + stack }); } return frozen; @@ -842,14 +842,14 @@ Barrier.prototype = Object.freeze({ * * @return {Promise} A promise satisfied once all blockers are complete. */ - wait: function(options = {}) { + wait(options = {}) { // This method only implements caching on top of _wait() if (this._promise) { return this._promise; } return this._promise = this._wait(options); }, - _wait: function(options) { + _wait(options) { // Sanity checks if (this._isStarted) { @@ -990,7 +990,7 @@ Barrier.prototype = Object.freeze({ return promise; }, - _removeBlocker: function(condition) { + _removeBlocker(condition) { if (!this._waitForMe || !this._promiseToBlocker || !this._conditionToPromise) { // We have already cleaned up everything. return false; diff --git a/toolkit/components/asyncshutdown/nsAsyncShutdown.js b/toolkit/components/asyncshutdown/nsAsyncShutdown.js index bd2c9a2fdf3a..349fd175d3a3 100644 --- a/toolkit/components/asyncshutdown/nsAsyncShutdown.js +++ b/toolkit/components/asyncshutdown/nsAsyncShutdown.js @@ -27,7 +27,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task", */ var PropertyBagConverter = { // From nsIPropertyBag to JS - toObject: function(bag) { + toObject(bag) { if (!(bag instanceof Ci.nsIPropertyBag)) { throw new TypeError("Not a property bag"); } @@ -40,7 +40,7 @@ var PropertyBagConverter = { } return result; }, - toValue: function(property) { + toValue(property) { if (typeof property != "object") { return property; } @@ -54,7 +54,7 @@ var PropertyBagConverter = { }, // From JS to nsIPropertyBag - fromObject: function(obj) { + fromObject(obj) { if (obj == null || typeof obj != "object") { throw new TypeError("Invalid object: " + obj); } @@ -66,7 +66,7 @@ var PropertyBagConverter = { } return bag; }, - fromValue: function(value) { + fromValue(value) { if (typeof value == "function") { return null; // Emulating the behavior of JSON.stringify with functions } @@ -100,7 +100,7 @@ function nsAsyncShutdownClient(moduleClient) { this._byName = new Map(); } nsAsyncShutdownClient.prototype = { - _getPromisified: function(xpcomBlocker) { + _getPromisified(xpcomBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate) { return null; @@ -110,7 +110,7 @@ nsAsyncShutdownClient.prototype = { } return null; }, - _setPromisified: function(xpcomBlocker, moduleBlocker) { + _setPromisified(xpcomBlocker, moduleBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate) { this._byName.set(xpcomBlocker.name, {xpcom: xpcomBlocker, @@ -122,7 +122,7 @@ nsAsyncShutdownClient.prototype = { } throw new Error("We have already registered a distinct blocker with the same name: " + xpcomBlocker.name); }, - _deletePromisified: function(xpcomBlocker) { + _deletePromisified(xpcomBlocker) { let candidate = this._byName.get(xpcomBlocker.name); if (!candidate || candidate.xpcom !== xpcomBlocker) { return false; @@ -136,7 +136,7 @@ nsAsyncShutdownClient.prototype = { get name() { return this._moduleClient.name; }, - addBlocker: function(/* nsIAsyncShutdownBlocker*/ xpcomBlocker, + addBlocker(/* nsIAsyncShutdownBlocker*/ xpcomBlocker, fileName, lineNumber, stack) { // We need a Promise-based function with the same behavior as // `xpcomBlocker`. Furthermore, to support `removeBlocker`, we @@ -171,12 +171,12 @@ nsAsyncShutdownClient.prototype = { return null; }, filename: fileName, - lineNumber: lineNumber, - stack: stack, + lineNumber, + stack, }); }, - removeBlocker: function(xpcomBlocker) { + removeBlocker(xpcomBlocker) { let moduleBlocker = this._getPromisified(xpcomBlocker); if (!moduleBlocker) { return false; @@ -210,7 +210,7 @@ nsAsyncShutdownBarrier.prototype = { get client() { return this._client; }, - wait: function(onReady) { + wait(onReady) { this._moduleBarrier.wait().then(() => { onReady.done(); }); @@ -242,7 +242,7 @@ function nsAsyncShutdownService() { let k = _k; Object.defineProperty(this, k, { configurable: true, - get: function() { + get() { delete this[k]; let wrapped = AsyncShutdown[k]; // May be undefined, if we're on the wrong process. let result = wrapped ? new nsAsyncShutdownClient(wrapped) : undefined; @@ -260,7 +260,7 @@ function nsAsyncShutdownService() { }; } nsAsyncShutdownService.prototype = { - makeBarrier: function(name) { + makeBarrier(name) { return new nsAsyncShutdownBarrier(new AsyncShutdown.Barrier(name)); }, diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/head.js b/toolkit/components/asyncshutdown/tests/xpcshell/head.js index 9de489808d91..735dea9fa5fc 100644 --- a/toolkit/components/asyncshutdown/tests/xpcshell/head.js +++ b/toolkit/components/asyncshutdown/tests/xpcshell/head.js @@ -37,13 +37,13 @@ function makeLock(kind) { let topic = "test-Phase-" + ++makeLock.counter; let phase = AsyncShutdown._getPhase(topic); return { - addBlocker: function(...args) { + addBlocker(...args) { return phase.addBlocker(...args); }, - removeBlocker: function(blocker) { + removeBlocker(blocker) { return phase.removeBlocker(blocker); }, - wait: function() { + wait() { Services.obs.notifyObservers(null, topic, null); return Promise.resolve(); } @@ -54,7 +54,7 @@ function makeLock(kind) { return { addBlocker: barrier.client.addBlocker, removeBlocker: barrier.client.removeBlocker, - wait: function() { + wait() { return barrier.wait(); } }; @@ -62,7 +62,7 @@ function makeLock(kind) { let name = "test-xpcom-Barrier-" + ++makeLock.counter; let barrier = asyncShutdownService.makeBarrier(name); return { - addBlocker: function(blockerName, condition, state) { + addBlocker(blockerName, condition, state) { if (condition == null) { // Slight trick as `null` or `undefined` cannot be used as keys // for `xpcomMap`. Note that this has no incidence on the result @@ -74,8 +74,8 @@ function makeLock(kind) { if (!blocker) { blocker = { name: blockerName, - state: state, - blockShutdown: function(aBarrierClient) { + state, + blockShutdown(aBarrierClient) { return Task.spawn(function*() { try { if (typeof condition == "function") { @@ -94,14 +94,14 @@ function makeLock(kind) { let {fileName, lineNumber, stack} = (new Error()); return barrier.client.addBlocker(blocker, fileName, lineNumber, stack); }, - removeBlocker: function(condition) { + removeBlocker(condition) { let blocker = makeLock.xpcomMap.get(condition); if (!blocker) { return; } barrier.client.removeBlocker(blocker); }, - wait: function() { + wait() { return new Promise(resolve => { barrier.wait(resolve); }); @@ -114,7 +114,7 @@ function makeLock(kind) { return { addBlocker: client.addBlocker, removeBlocker: client.removeBlocker, - wait: function() { + wait() { return new Promise(resolve => { barrier.wait(resolve); }); diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js index 33da1f53fbd4..9df2425ba26a 100644 --- a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js +++ b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js @@ -27,7 +27,7 @@ add_task(function* test_phase_simple_async() { throw new Error("State BOOM"); }], [function() { return { - toJSON: function() { + toJSON() { throw new Error("State.toJSON BOOM"); } }; diff --git a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js index 478f4d4d13f0..581ca77a8d81 100644 --- a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js +++ b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js @@ -37,7 +37,7 @@ AutoCompleteInputBase.prototype = { get selectionEnd() { return this._selEnd; }, - selectTextRange: function(aStart, aEnd) { + selectTextRange(aStart, aEnd) { this._selStart = aStart; this._selEnd = aEnd; }, @@ -46,12 +46,12 @@ AutoCompleteInputBase.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, @@ -89,31 +89,31 @@ AutoCompleteResultBase.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this._finalCompleteValues[aIndex] || this._values[aIndex]; }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteResult]) @@ -135,7 +135,7 @@ AutoCompleteSearchBase.prototype = { // AutoCompleteResult _result: null, - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) { @@ -145,14 +145,14 @@ AutoCompleteSearchBase.prototype = { aListener.onSearchResult(this, result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory, Ci.nsIAutoCompleteSearch]), // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_330578.js b/toolkit/components/autocomplete/tests/unit/test_330578.js index c422dbb6a0c8..29b368269aab 100644 --- a/toolkit/components/autocomplete/tests/unit/test_330578.js +++ b/toolkit/components/autocomplete/tests/unit/test_330578.js @@ -9,7 +9,7 @@ var gResultListener = { _lastValue: "", _lastRemoveFromDb: false, - onValueRemoved: function(aResult, aValue, aRemoveFromDb) { + onValueRemoved(aResult, aValue, aRemoveFromDb) { this._lastResult = aResult; this._lastValue = aValue; this._lastRemoveFromDb = aRemoveFromDb; diff --git a/toolkit/components/autocomplete/tests/unit/test_378079.js b/toolkit/components/autocomplete/tests/unit/test_378079.js index b8b734884187..b5ac52e0ac80 100644 --- a/toolkit/components/autocomplete/tests/unit/test_378079.js +++ b/toolkit/components/autocomplete/tests/unit/test_378079.js @@ -37,21 +37,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -61,7 +61,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -103,34 +103,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -162,7 +162,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_393191.js b/toolkit/components/autocomplete/tests/unit/test_393191.js index 750bcbd9abb4..ce32b4261787 100644 --- a/toolkit/components/autocomplete/tests/unit/test_393191.js +++ b/toolkit/components/autocomplete/tests/unit/test_393191.js @@ -36,21 +36,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -60,7 +60,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -102,34 +102,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -161,7 +161,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -169,10 +169,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -182,7 +182,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_440866.js b/toolkit/components/autocomplete/tests/unit/test_440866.js index e42dd8831c90..558ac78b7d29 100644 --- a/toolkit/components/autocomplete/tests/unit/test_440866.js +++ b/toolkit/components/autocomplete/tests/unit/test_440866.js @@ -35,21 +35,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -59,7 +59,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -101,34 +101,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -160,7 +160,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -168,10 +168,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -181,7 +181,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js index 15274140fcd4..6186df34d8f4 100644 --- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js +++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js @@ -30,21 +30,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -54,7 +54,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -90,34 +90,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -149,7 +149,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_previousResult.js b/toolkit/components/autocomplete/tests/unit/test_previousResult.js index a9c6da31a4b2..0367f782de14 100644 --- a/toolkit/components/autocomplete/tests/unit/test_previousResult.js +++ b/toolkit/components/autocomplete/tests/unit/test_previousResult.js @@ -36,21 +36,21 @@ AutoCompleteInput.prototype = { return this.searches.length; }, - getSearchAt: function(aIndex) { + getSearchAt(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, + onSearchBegin() {}, + onSearchComplete() {}, popupOpen: false, popup: { - setSelectedIndex: function(aIndex) {}, - invalidate: function() {}, + setSelectedIndex(aIndex) {}, + invalidate() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompletePopup)) return this; @@ -60,7 +60,7 @@ AutoCompleteInput.prototype = { }, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteInput)) return this; @@ -101,34 +101,34 @@ AutoCompleteResult.prototype = { return this._values.length; }, - getValueAt: function(aIndex) { + getValueAt(aIndex) { return this._values[aIndex]; }, - getLabelAt: function(aIndex) { + getLabelAt(aIndex) { return this.getValueAt(aIndex); }, - getCommentAt: function(aIndex) { + getCommentAt(aIndex) { return this._comments[aIndex]; }, - getStyleAt: function(aIndex) { + getStyleAt(aIndex) { return this._styles[aIndex]; }, - getImageAt: function(aIndex) { + getImageAt(aIndex) { return ""; }, - getFinalCompleteValueAt: function(aIndex) { + getFinalCompleteValueAt(aIndex) { return this.getValueAt(aIndex); }, - removeValueAt: function(aRowIndex, aRemoveFromDb) {}, + removeValueAt(aRowIndex, aRemoveFromDb) {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIAutoCompleteResult)) return this; @@ -161,7 +161,7 @@ AutoCompleteSearch.prototype = { /** * Return the same result set for every search */ - startSearch: function(aSearchString, + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) @@ -170,10 +170,10 @@ AutoCompleteSearch.prototype = { aListener.onSearchResult(this, this._result); }, - stopSearch: function() {}, + stopSearch() {}, // nsISupports implementation - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory) || iid.equals(Ci.nsIAutoCompleteSearch)) @@ -183,7 +183,7 @@ AutoCompleteSearch.prototype = { }, // nsIFactory implementation - createInstance: function(outer, iid) { + createInstance(outer, iid) { return this.QueryInterface(iid); } } diff --git a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js index 0972092bb63e..4ef0294b73bc 100644 --- a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js +++ b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js @@ -32,14 +32,14 @@ AutoCompleteInput.prototype = { set popupOpen(val) { return val; }, // ignore get popupOpen() { return false; }, get searchCount() { return this.searches.length; }, - getSearchAt: function(aIndex) { return this.searches[aIndex]; }, - onSearchBegin: function() {}, - onSearchComplete: function() {}, - onTextReverted: function() {}, - onTextEntered: function() {}, + getSearchAt(aIndex) { return this.searches[aIndex]; }, + onSearchBegin() {}, + onSearchComplete() {}, + onTextReverted() {}, + onTextEntered() {}, popup: { - selectBy: function() {}, - invalidate: function() {}, + selectBy() {}, + invalidate() {}, set selectedIndex(val) { return val; }, // ignore get selectedIndex() { return -1 }, QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup]) @@ -58,13 +58,13 @@ function AutoCompleteSearch(aName) AutoCompleteSearch.prototype = { constructor: AutoCompleteSearch, stopSearchInvoked: true, - startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener) + startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) { print("Check stop search has been called"); do_check_true(this.stopSearchInvoked); this.stopSearchInvoked = false; }, - stopSearch: function() + stopSearch() { this.stopSearchInvoked = true; }, @@ -72,7 +72,7 @@ AutoCompleteSearch.prototype = { Ci.nsIFactory , Ci.nsIAutoCompleteSearch ]), - createInstance: function(outer, iid) + createInstance(outer, iid) { return this.QueryInterface(iid); } diff --git a/toolkit/components/captivedetect/captivedetect.js b/toolkit/components/captivedetect/captivedetect.js index f347736b39aa..4362f8e790d7 100644 --- a/toolkit/components/captivedetect/captivedetect.js +++ b/toolkit/components/captivedetect/captivedetect.js @@ -66,9 +66,9 @@ function URLFetcher(url, timeout) { URLFetcher.prototype = { _isAborted: false, - ontimeout: function() {}, - onerror: function() {}, - abort: function() { + ontimeout() {}, + onerror() {}, + abort() { if (!this._isAborted) { this._isAborted = true; this._xhr.abort(); @@ -339,7 +339,7 @@ CaptivePortalDetector.prototype = { let id = this._allocateRequestId(); let details = { type: kOpenCaptivePortalLoginEvent, - id: id, + id, url: this._canonicalSiteURL, }; this._loginObserver.attach(); diff --git a/toolkit/components/contentprefs/ContentPrefService2.jsm b/toolkit/components/contentprefs/ContentPrefService2.jsm index 5d4287897024..69180fe13101 100644 --- a/toolkit/components/contentprefs/ContentPrefService2.jsm +++ b/toolkit/components/contentprefs/ContentPrefService2.jsm @@ -418,7 +418,7 @@ ContentPrefService2.prototype = { }, // Deletes settings and groups that are no longer used. - _settingsAndGroupsCleanupStmts: function() { + _settingsAndGroupsCleanupStmts() { // The NOTNULL term in the subquery of the second statment is needed because of // SQLite's weird IN behavior vis-a-vis NULLs. See http://sqlite.org/lang_expr.html. return [ diff --git a/toolkit/components/contentprefs/ContentPrefServiceChild.jsm b/toolkit/components/contentprefs/ContentPrefServiceChild.jsm index ea1f969dfd64..cad1c71caf67 100644 --- a/toolkit/components/contentprefs/ContentPrefServiceChild.jsm +++ b/toolkit/components/contentprefs/ContentPrefServiceChild.jsm @@ -31,18 +31,18 @@ function CallbackCaller(callback) { } CallbackCaller.prototype = { - handleResult: function(contentPref) { + handleResult(contentPref) { cbHandleResult(this._callback, new ContentPref(contentPref.domain, contentPref.name, contentPref.value)); }, - handleError: function(result) { + handleError(result) { cbHandleError(this._callback, result); }, - handleCompletion: function(reason) { + handleCompletion(reason) { cbHandleCompletion(this._callback, reason); }, }; @@ -56,7 +56,7 @@ var ContentPrefServiceChild = { _mm: Cc["@mozilla.org/childprocessmessagemanager;1"] .getService(Ci.nsIMessageSender), - _getRandomId: function() { + _getRandomId() { return Cc["@mozilla.org/uuid-generator;1"] .getService(Ci.nsIUUIDGenerator).generateUUID().toString(); }, @@ -64,13 +64,13 @@ var ContentPrefServiceChild = { // Map from random ID string -> CallbackCaller, per request _requests: new Map(), - init: function() { + init() { this._mm.addMessageListener("ContentPrefs:HandleResult", this); this._mm.addMessageListener("ContentPrefs:HandleError", this); this._mm.addMessageListener("ContentPrefs:HandleCompletion", this); }, - receiveMessage: function(msg) { + receiveMessage(msg) { let data = msg.data; let callback; switch (msg.name) { @@ -104,34 +104,34 @@ var ContentPrefServiceChild = { } }, - _callFunction: function(call, args, callback) { + _callFunction(call, args, callback) { let requestId = this._getRandomId(); - let data = { call: call, args: args, requestId: requestId }; + let data = { call, args, requestId }; this._mm.sendAsyncMessage("ContentPrefs:FunctionCall", data); this._requests.set(requestId, new CallbackCaller(callback)); }, - getByName: function(name, context, callback) { + getByName(name, context, callback) { return this._callFunction("getByName", [ name, contextArg(context) ], callback); }, - getByDomainAndName: function(domain, name, context, callback) { + getByDomainAndName(domain, name, context, callback) { return this._callFunction("getByDomainAndName", [ domain, name, contextArg(context) ], callback); }, - getBySubdomainAndName: function(domain, name, context, callback) { + getBySubdomainAndName(domain, name, context, callback) { return this._callFunction("getBySubdomainAndName", [ domain, name, contextArg(context) ], callback); }, - getGlobal: function(name, context, callback) { + getGlobal(name, context, callback) { return this._callFunction("getGlobal", [ name, contextArg(context) ], callback); @@ -141,59 +141,59 @@ var ContentPrefServiceChild = { getCachedBySubdomainAndName: NYI, getCachedGlobal: NYI, - set: function(domain, name, value, context, callback) { + set(domain, name, value, context, callback) { this._callFunction("set", [ domain, name, value, contextArg(context) ], callback); }, - setGlobal: function(name, value, context, callback) { + setGlobal(name, value, context, callback) { this._callFunction("setGlobal", [ name, value, contextArg(context) ], callback); }, - removeByDomainAndName: function(domain, name, context, callback) { + removeByDomainAndName(domain, name, context, callback) { this._callFunction("removeByDomainAndName", [ domain, name, contextArg(context) ], callback); }, - removeBySubdomainAndName: function(domain, name, context, callback) { + removeBySubdomainAndName(domain, name, context, callback) { this._callFunction("removeBySubdomainAndName", [ domain, name, contextArg(context) ], callback); }, - removeGlobal: function(name, context, callback) { + removeGlobal(name, context, callback) { this._callFunction("removeGlobal", [ name, contextArg(context) ], callback); }, - removeByDomain: function(domain, context, callback) { + removeByDomain(domain, context, callback) { this._callFunction("removeByDomain", [ domain, contextArg(context) ], callback); }, - removeBySubdomain: function(domain, context, callback) { + removeBySubdomain(domain, context, callback) { this._callFunction("removeBySubdomain", [ domain, contextArg(context) ], callback); }, - removeByName: function(name, context, callback) { + removeByName(name, context, callback) { this._callFunction("removeByName", [ name, value, contextArg(context) ], callback); }, - removeAllDomains: function(context, callback) { + removeAllDomains(context, callback) { this._callFunction("removeAllDomains", [ contextArg(context) ], callback); }, - removeAllGlobals: function(context, callback) { + removeAllGlobals(context, callback) { this._callFunction("removeAllGlobals", [ contextArg(context) ], callback); }, - addObserverForName: function(name, observer) { + addObserverForName(name, observer) { let set = this._observers.get(name); if (!set) { set = new Set(); @@ -204,14 +204,14 @@ var ContentPrefServiceChild = { // This is the first observer for this name. Start listening for changes // to it. - this._mm.sendAsyncMessage("ContentPrefs:AddObserverForName", { name: name }); + this._mm.sendAsyncMessage("ContentPrefs:AddObserverForName", { name }); this._observers.set(name, set); } set.add(observer); }, - removeObserverForName: function(name, observer) { + removeObserverForName(name, observer) { let set = this._observers.get(name); if (!set) return; @@ -219,7 +219,7 @@ var ContentPrefServiceChild = { set.delete(observer); if (set.size === 0) { // This was the last observer for this name. Stop listening for changes. - this._mm.sendAsyncMessage("ContentPrefs:RemoveObserverForName", { name: name }); + this._mm.sendAsyncMessage("ContentPrefs:RemoveObserverForName", { name }); this._observers.delete(name); if (this._observers.size === 0) { diff --git a/toolkit/components/contentprefs/ContentPrefServiceParent.jsm b/toolkit/components/contentprefs/ContentPrefServiceParent.jsm index f4b02f018ace..e0cb15e58491 100644 --- a/toolkit/components/contentprefs/ContentPrefServiceParent.jsm +++ b/toolkit/components/contentprefs/ContentPrefServiceParent.jsm @@ -14,7 +14,7 @@ const Cu = Components.utils; var ContentPrefServiceParent = { _cps2: null, - init: function() { + init() { let globalMM = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIMessageListenerManager); @@ -32,7 +32,7 @@ var ContentPrefServiceParent = { // Map from message manager -> content pref observer. _observers: new Map(), - handleObserverChange: function(msg) { + handleObserverChange(msg) { let observer = this._observers.get(msg.target); if (msg.name === "child-process-shutdown") { // If we didn't have any observers for this child process, don't do @@ -54,15 +54,15 @@ var ContentPrefServiceParent = { // observers for the same name. if (!observer) { observer = { - onContentPrefSet: function(group, name, value, isPrivate) { + onContentPrefSet(group, name, value, isPrivate) { msg.target.sendAsyncMessage("ContentPrefs:NotifyObservers", - { name: name, callback: "onContentPrefSet", + { name, callback: "onContentPrefSet", args: [ group, name, value, isPrivate ] }); }, - onContentPrefRemoved: function(group, name, isPrivate) { + onContentPrefRemoved(group, name, isPrivate) { msg.target.sendAsyncMessage("ContentPrefs:NotifyObservers", - { name: name, callback: "onContentPrefRemoved", + { name, callback: "onContentPrefRemoved", args: [ group, name, isPrivate ] }); }, @@ -92,16 +92,16 @@ var ContentPrefServiceParent = { } }, - receiveMessage: function(msg) { + receiveMessage(msg) { let data = msg.data; let args = data.args; let requestId = data.requestId; let listener = { - handleResult: function(pref) { + handleResult(pref) { msg.target.sendAsyncMessage("ContentPrefs:HandleResult", - { requestId: requestId, + { requestId, contentPref: { domain: pref.domain, name: pref.name, @@ -110,15 +110,15 @@ var ContentPrefServiceParent = { }); }, - handleError: function(error) { + handleError(error) { msg.target.sendAsyncMessage("ContentPrefs:HandleError", - { requestId: requestId, - error: error }); + { requestId, + error }); }, - handleCompletion: function(reason) { + handleCompletion(reason) { msg.target.sendAsyncMessage("ContentPrefs:HandleCompletion", - { requestId: requestId, - reason: reason }); + { requestId, + reason }); } }; diff --git a/toolkit/components/contentprefs/nsContentPrefService.js b/toolkit/components/contentprefs/nsContentPrefService.js index 4f5726e6ea44..8e92432e9f2c 100644 --- a/toolkit/components/contentprefs/nsContentPrefService.js +++ b/toolkit/components/contentprefs/nsContentPrefService.js @@ -580,7 +580,7 @@ ContentPrefService.prototype = { return this.__stmtSelectPref; }, - _scheduleCallback: function(func) { + _scheduleCallback(func) { let tm = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager); tm.mainThread.dispatch(func, Ci.nsIThread.DISPATCH_NORMAL); }, @@ -602,7 +602,7 @@ ContentPrefService.prototype = { if (aCallback) { let cache = this._cache; - new AsyncStatement(this._stmtSelectPref).execute({onResult: function(aResult) { + new AsyncStatement(this._stmtSelectPref).execute({onResult(aResult) { cache.set(aGroup, aSetting, aResult); aCallback.onResult(aResult); }}); @@ -651,7 +651,7 @@ ContentPrefService.prototype = { if (aCallback) { let cache = this._cache; - new AsyncStatement(this._stmtSelectGlobalPref).execute({onResult: function(aResult) { + new AsyncStatement(this._stmtSelectGlobalPref).execute({onResult(aResult) { cache.set(null, aName, aResult); aCallback.onResult(aResult); }}); @@ -1309,19 +1309,19 @@ AsyncStatement.prototype = { stmt.executeAsync({ _callback: aCallback, _hadResult: false, - handleResult: function(aResult) { + handleResult(aResult) { this._hadResult = true; if (this._callback) { let row = aResult.getNextRow(); this._callback.onResult(row.getResultByName("value")); } }, - handleCompletion: function(aReason) { + handleCompletion(aReason) { if (!this._hadResult && this._callback && aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) this._callback.onResult(undefined); }, - handleError: function(aError) {} + handleError(aError) {} }); } }; diff --git a/toolkit/components/contentprefs/tests/unit/test_bug679784.js b/toolkit/components/contentprefs/tests/unit/test_bug679784.js index 97251d87ba9c..123c8712acb7 100644 --- a/toolkit/components/contentprefs/tests/unit/test_bug679784.js +++ b/toolkit/components/contentprefs/tests/unit/test_bug679784.js @@ -5,11 +5,11 @@ var prefObserver = { setCalledNum: 0, - onContentPrefSet: function(aGroup, aName, aValue) { + onContentPrefSet(aGroup, aName, aValue) { this.setCalledNum++; }, removedCalledNum: 0, - onContentPrefRemoved: function(aGroup, aName) { + onContentPrefRemoved(aGroup, aName) { this.removedCalledNum++; } }; diff --git a/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js b/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js index 27d239f793f5..826619ed740d 100644 --- a/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js +++ b/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js @@ -18,7 +18,7 @@ function run_test() { function testCallbackObj() { cps.getPref(uri, "asynctest", { - onResult: function(aValue) { + onResult(aValue) { do_check_eq(aValue, "pie"); cps.removePref(uri, "asynctest"); testNoResult(); diff --git a/toolkit/components/contentprefs/tests/unit_cps2/head.js b/toolkit/components/contentprefs/tests/unit_cps2/head.js index 6ce75d997753..50cc9ae37622 100644 --- a/toolkit/components/contentprefs/tests/unit_cps2/head.js +++ b/toolkit/components/contentprefs/tests/unit_cps2/head.js @@ -25,7 +25,7 @@ function runAsyncTests(tests, dontResetBefore = false) { Cu.import("resource://test/AsyncRunner.jsm", s); asyncRunner = new s.AsyncRunner({ done: do_test_finished, - error: function(err) { + error(err) { // xpcshell test functions like equal throw NS_ERROR_ABORT on // failure. Ignore those and catch only uncaught exceptions. if (err !== Cr.NS_ERROR_ABORT) { @@ -36,7 +36,7 @@ function runAsyncTests(tests, dontResetBefore = false) { do_throw(err); } }, - consoleError: function(scriptErr) { + consoleError(scriptErr) { // Previously, this code checked for console errors related to the test, // and treated them as failures. This was problematic, because our current // very-broken exception reporting machinery in XPCWrappedJSClass reports @@ -138,10 +138,10 @@ function setWithDate(group, name, val, timestamp, context) { stmt.params.group = group; stmt.executeAsync({ - handleCompletion: function(reason) { + handleCompletion(reason) { next(); }, - handleError: function(err) { + handleError(err) { do_throw(err); } }); @@ -164,14 +164,14 @@ function getDate(group, name, context) { let res; stmt.executeAsync({ - handleResult: function(results) { + handleResult(results) { let row = results.getNextRow(); res = row.getResultByName("timestamp"); }, - handleCompletion: function(reason) { + handleCompletion(reason) { next(res * 1000); }, - handleError: function(err) { + handleError(err) { do_throw(err); } }); @@ -336,17 +336,17 @@ function dbOK(expectedRows) { let cols = ["grp", "name", "value"]; db.executeAsync([stmt], 1, { - handleCompletion: function(reason) { + handleCompletion(reason) { arraysOfArraysOK(actualRows, expectedRows); next(); }, - handleResult: function(results) { + handleResult(results) { let row = null; while (row = results.getNextRow()) { actualRows.push(cols.map(c => row.getResultByName(c))); } }, - handleError: function(err) { + handleError(err) { do_throw(err); } }); @@ -355,7 +355,7 @@ function dbOK(expectedRows) { function on(event, names, dontRemove) { let args = { - reset: function() { + reset() { for (let prop in this) { if (Array.isArray(this[prop])) this[prop].splice(0, this[prop].length); diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js b/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js index 0fdc3b7adf32..546ff0b2bd2b 100644 --- a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js +++ b/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js @@ -143,7 +143,7 @@ var tests = [ // (3) Set the pref to a new value but don't wait for it to finish. cps.set("a.com", "foo", 2, null, { - handleCompletion: function() { + handleCompletion() { // (6) The pref should be cached after setting it. getCachedOK(["a.com", "foo"], true, 2); }, @@ -155,10 +155,10 @@ var tests = [ // (5) Call getByDomainAndName. var fetchedPref; cps.getByDomainAndName("a.com", "foo", null, { - handleResult: function(pref) { + handleResult(pref) { fetchedPref = pref; }, - handleCompletion: function() { + handleCompletion() { // (7) Finally, this callback should be called after set's above. do_check_true(!!fetchedPref); do_check_eq(fetchedPref.value, 2); diff --git a/toolkit/components/crashes/CrashManager.jsm b/toolkit/components/crashes/CrashManager.jsm index 1df8ed739db9..65216391c8d8 100644 --- a/toolkit/components/crashes/CrashManager.jsm +++ b/toolkit/components/crashes/CrashManager.jsm @@ -262,7 +262,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return Promise */ - pendingDumps: function() { + pendingDumps() { return this._getDirectoryEntries(this._pendingDumpsDir, this.DUMP_REGEX); }, @@ -286,7 +286,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return Promise */ - submittedDumps: function() { + submittedDumps() { return this._getDirectoryEntries(this._submittedDumpsDir, this.SUBMITTED_REGEX); }, @@ -306,7 +306,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return promise The number of event files that were examined. */ - aggregateEventsFiles: function() { + aggregateEventsFiles() { if (this._aggregatePromise) { return this._aggregatePromise; } @@ -389,7 +389,7 @@ this.CrashManager.prototype = Object.freeze({ * (Date) The cutoff point for pruning. Crashes without data newer * than this will be pruned. */ - pruneOldCrashes: function(date) { + pruneOldCrashes(date) { return Task.spawn(function* () { let store = yield this._getStore(); store.pruneOldCrashes(date); @@ -400,7 +400,7 @@ this.CrashManager.prototype = Object.freeze({ /** * Run tasks that should be periodically performed. */ - runMaintenanceTasks: function() { + runMaintenanceTasks() { return Task.spawn(function* () { yield this.aggregateEventsFiles(); @@ -415,7 +415,7 @@ this.CrashManager.prototype = Object.freeze({ * @param delay * (integer) Delay in milliseconds when maintenance should occur. */ - scheduleMaintenance: function(delay) { + scheduleMaintenance(delay) { let deferred = PromiseUtils.defer(); setTimeout(() => { @@ -439,7 +439,7 @@ this.CrashManager.prototype = Object.freeze({ * * @return promise Resolved when the store has been saved. */ - addCrash: function(processType, crashType, id, date, metadata) { + addCrash(processType, crashType, id, date, metadata) { let promise = Task.spawn(function* () { let store = yield this._getStore(); if (store.addCrash(processType, crashType, id, date, metadata)) { @@ -561,7 +561,7 @@ this.CrashManager.prototype = Object.freeze({ * * The promise-resolved array is sorted by file mtime, oldest to newest. */ - _getUnprocessedEventsFiles: function() { + _getUnprocessedEventsFiles() { return Task.spawn(function* () { let entries = []; @@ -578,7 +578,7 @@ this.CrashManager.prototype = Object.freeze({ }, // See docs/crash-events.rst for the file format specification. - _processEventFile: function(entry) { + _processEventFile(entry) { return Task.spawn(function* () { let data = yield OS.File.read(entry.path); let store = yield this._getStore(); @@ -617,7 +617,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - _filterAnnotations: function(annotations) { + _filterAnnotations(annotations) { let filteredAnnotations = {}; for (let line in annotations) { @@ -629,7 +629,7 @@ this.CrashManager.prototype = Object.freeze({ return filteredAnnotations; }, - _sendCrashPing: function(crashId, type, date, metadata = {}) { + _sendCrashPing(crashId, type, date, metadata = {}) { // If we have a saved environment, use it. Otherwise report // the current environment. let reportMeta = Cu.cloneInto(metadata, myScope); @@ -646,10 +646,10 @@ this.CrashManager.prototype = Object.freeze({ { version: 1, crashDate: date.toISOString().slice(0, 10), // YYYY-MM-DD - sessionId: sessionId, - crashId: crashId, + sessionId, + crashId, processType: type, - stackTraces: stackTraces, + stackTraces, metadata: reportMeta, hasCrashEnvironment: (crashEnvironment !== null), }, @@ -662,7 +662,7 @@ this.CrashManager.prototype = Object.freeze({ ); }, - _handleEventFilePayload: function(store, entry, type, date, payload) { + _handleEventFilePayload(store, entry, type, date, payload) { // The payload types and formats are documented in docs/crash-events.rst. // Do not change the format of an existing type. Instead, invent a new // type. @@ -720,7 +720,7 @@ this.CrashManager.prototype = Object.freeze({ * id -- regexp.match()[1] (likely the crash ID) * date -- Date mtime of the file */ - _getDirectoryEntries: function(path, re) { + _getDirectoryEntries(path, re) { return Task.spawn(function* () { try { yield OS.File.stat(path); @@ -763,7 +763,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - _getStore: function() { + _getStore() { if (this._getStoreTask) { return this._getStoreTask; } @@ -823,7 +823,7 @@ this.CrashManager.prototype = Object.freeze({ * * Returns an array of CrashRecord instances. Instances are read-only. */ - getCrashes: function() { + getCrashes() { return Task.spawn(function* () { let store = yield this._getStore(); @@ -831,7 +831,7 @@ this.CrashManager.prototype = Object.freeze({ }.bind(this)); }, - getCrashCountsByDay: function() { + getCrashCountsByDay() { return Task.spawn(function* () { let store = yield this._getStore(); @@ -908,7 +908,7 @@ CrashStore.prototype = Object.freeze({ * * @return Promise */ - load: function() { + load() { return Task.spawn(function* () { // Loading replaces data. this.reset(); @@ -1008,7 +1008,7 @@ CrashStore.prototype = Object.freeze({ * * @return Promise */ - save: function() { + save() { return Task.spawn(function* () { if (!this._data) { return; @@ -1078,7 +1078,7 @@ CrashStore.prototype = Object.freeze({ * We convert these to milliseconds since epoch on output and back to * Date on input. */ - _normalize: function(o) { + _normalize(o) { let normalized = {}; for (let k in o) { @@ -1096,7 +1096,7 @@ CrashStore.prototype = Object.freeze({ /** * Convert a serialized object back to its native form. */ - _denormalize: function(o) { + _denormalize(o) { let n = {}; for (let k in o) { @@ -1122,7 +1122,7 @@ CrashStore.prototype = Object.freeze({ * (Date) The cutoff at which data will be pruned. If an entry * doesn't have data newer than this, it will be pruned. */ - pruneOldCrashes: function(date) { + pruneOldCrashes(date) { for (let crash of this.crashes) { let newest = crash.newestDate; if (!newest || newest.getTime() < date.getTime()) { @@ -1167,7 +1167,7 @@ CrashStore.prototype = Object.freeze({ * A CrashRecord will be returned if the crash exists. null will be returned * if the crash is unknown. */ - getCrash: function(id) { + getCrash(id) { for (let crash of this.crashes) { if (crash.id == id) { return crash; @@ -1177,7 +1177,7 @@ CrashStore.prototype = Object.freeze({ return null; }, - _ensureCountsForDay: function(day) { + _ensureCountsForDay(day) { if (!this._countsByDay.has(day)) { this._countsByDay.set(day, new Map()); } @@ -1202,7 +1202,7 @@ CrashStore.prototype = Object.freeze({ * * @return null | object crash record */ - _ensureCrashRecord: function(processType, crashType, id, date, metadata) { + _ensureCrashRecord(processType, crashType, id, date, metadata) { if (!id) { // Crashes are keyed on ID, so it's not really helpful to store crashes // without IDs. @@ -1232,13 +1232,13 @@ CrashStore.prototype = Object.freeze({ } this._data.crashes.set(id, { - id: id, + id, remoteID: null, - type: type, + type, crashDate: date, submissions: new Map(), classifications: [], - metadata: metadata, + metadata, }); } @@ -1260,14 +1260,14 @@ CrashStore.prototype = Object.freeze({ * * @return boolean True if the crash was recorded and false if not. */ - addCrash: function(processType, crashType, id, date, metadata) { + addCrash(processType, crashType, id, date, metadata) { return !!this._ensureCrashRecord(processType, crashType, id, date, metadata); }, /** * @return boolean True if the remote ID was recorded and false if not. */ - setRemoteCrashID: function(crashID, remoteID) { + setRemoteCrashID(crashID, remoteID) { let crash = this._data.crashes.get(crashID); if (!crash || !remoteID) { return false; @@ -1277,7 +1277,7 @@ CrashStore.prototype = Object.freeze({ return true; }, - getCrashesOfType: function(processType, crashType) { + getCrashesOfType(processType, crashType) { let crashes = []; for (let crash of this.crashes) { if (crash.isOfType(processType, crashType)) { @@ -1292,7 +1292,7 @@ CrashStore.prototype = Object.freeze({ * Ensure the submission record is present in storage. * @returns [submission, crash] */ - _ensureSubmissionRecord: function(crashID, submissionID) { + _ensureSubmissionRecord(crashID, submissionID) { let crash = this._data.crashes.get(crashID); if (!crash || !submissionID) { return null; @@ -1312,7 +1312,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the attempt was recorded. */ - addSubmissionAttempt: function(crashID, submissionID, date) { + addSubmissionAttempt(crashID, submissionID, date) { let [submission, crash] = this._ensureSubmissionRecord(crashID, submissionID); if (!submission) { @@ -1328,7 +1328,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the response was recorded. */ - addSubmissionResult: function(crashID, submissionID, date, result) { + addSubmissionResult(crashID, submissionID, date, result) { let crash = this._data.crashes.get(crashID); if (!crash || !submissionID) { return false; @@ -1348,7 +1348,7 @@ CrashStore.prototype = Object.freeze({ /** * @return boolean True if the classifications were set. */ - setCrashClassifications: function(crashID, classifications) { + setCrashClassifications(crashID, classifications) { let crash = this._data.crashes.get(crashID); if (!crash) { return false; @@ -1407,7 +1407,7 @@ CrashRecord.prototype = Object.freeze({ return this._o.type; }, - isOfType: function(processType, crashType) { + isOfType(processType, crashType) { return processType + "-" + crashType == this.type; }, diff --git a/toolkit/components/crashes/CrashManagerTest.jsm b/toolkit/components/crashes/CrashManagerTest.jsm index e55da45468fd..f7fa11d8e0cf 100644 --- a/toolkit/components/crashes/CrashManagerTest.jsm +++ b/toolkit/components/crashes/CrashManagerTest.jsm @@ -57,7 +57,7 @@ this.TestingCrashManager = function(options) { this.TestingCrashManager.prototype = { __proto__: CrashManager.prototype, - createDummyDump: function(submitted = false, date = new Date(), hr = false) { + createDummyDump(submitted = false, date = new Date(), hr = false) { let uuid = Cc["@mozilla.org/uuid-generator;1"] .getService(Ci.nsIUUIDGenerator) .generateUUID() @@ -89,7 +89,7 @@ this.TestingCrashManager.prototype = { }); }, - createIgnoredDumpFile: function(filename, submitted = false) { + createIgnoredDumpFile(filename, submitted = false) { let path; if (submitted) { path = OS.Path.join(this._submittedDumpsDir, filename); @@ -104,7 +104,7 @@ this.TestingCrashManager.prototype = { }); }, - createEventsFile: function(filename, type, date, content, index = 0) { + createEventsFile(filename, type, date, content, index = 0) { let path = OS.Path.join(this._eventsDirs[index], filename); let data = type + "\n" + @@ -124,7 +124,7 @@ this.TestingCrashManager.prototype = { * * We can probably delete this once we have actual events defined. */ - _handleEventFilePayload: function(store, entry, type, date, payload) { + _handleEventFilePayload(store, entry, type, date, payload) { if (type == "test.1") { if (payload == "malformed") { return this.EVENT_FILE_ERROR_MALFORMED; diff --git a/toolkit/components/crashes/CrashService.js b/toolkit/components/crashes/CrashService.js index 72f804fc079d..76713524b81b 100644 --- a/toolkit/components/crashes/CrashService.js +++ b/toolkit/components/crashes/CrashService.js @@ -57,7 +57,7 @@ CrashService.prototype = Object.freeze({ Ci.nsIObserver, ]), - addCrash: function(processType, crashType, id) { + addCrash(processType, crashType, id) { switch (processType) { case Ci.nsICrashService.PROCESS_TYPE_MAIN: processType = Services.crashmanager.PROCESS_TYPE_MAIN; @@ -98,7 +98,7 @@ CrashService.prototype = Object.freeze({ ); }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "profile-after-change": // Side-effect is the singleton is instantiated. diff --git a/toolkit/components/crashmonitor/CrashMonitor.jsm b/toolkit/components/crashmonitor/CrashMonitor.jsm index 6540d516fc2b..2ee173527507 100644 --- a/toolkit/components/crashmonitor/CrashMonitor.jsm +++ b/toolkit/components/crashmonitor/CrashMonitor.jsm @@ -93,7 +93,7 @@ var CrashMonitorInternal = { * * @return {Promise} A promise that resolves/rejects once loading is complete */ - loadPreviousCheckpoints: function() { + loadPreviousCheckpoints() { this.previousCheckpoints = Task.spawn(function*() { let data; try { @@ -155,7 +155,7 @@ this.CrashMonitor = { * * @return {Promise} */ - init: function() { + init() { if (CrashMonitorInternal.initialized) { throw new Error("CrashMonitor.init() must only be called once!"); } @@ -185,7 +185,7 @@ this.CrashMonitor = { * * Update checkpoint file for every new notification received. */ - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { if (!(aTopic in CrashMonitorInternal.checkpoints)) { // If this is the first time this notification is received, // remember it and write it to file diff --git a/toolkit/components/crashmonitor/nsCrashMonitor.js b/toolkit/components/crashmonitor/nsCrashMonitor.js index fe29a9c8eaea..d53fecd6d067 100644 --- a/toolkit/components/crashmonitor/nsCrashMonitor.js +++ b/toolkit/components/crashmonitor/nsCrashMonitor.js @@ -18,7 +18,7 @@ CrashMonitor.prototype = { QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]), - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { switch (aTopic) { case "profile-after-change": MonitorAPI.init(); diff --git a/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js b/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js index eec85025b5c5..7163e2755415 100644 --- a/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js +++ b/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js @@ -13,7 +13,7 @@ var Components = { caller: null }, utils: { - import: function() { } + import() { } } }; @@ -72,7 +72,7 @@ FileFaker.prototype = { this._path = this._path.substring(0, lastSlash); return this; }, - append: function(leaf) { + append(leaf) { this._path = this._path + "/" + leaf; } }; diff --git a/toolkit/components/ctypes/tests/unit/head.js b/toolkit/components/ctypes/tests/unit/head.js index 4e51b22a2ab5..e2c2ea4683c0 100644 --- a/toolkit/components/ctypes/tests/unit/head.js +++ b/toolkit/components/ctypes/tests/unit/head.js @@ -44,7 +44,7 @@ function ResourceTester(start, stop) { this._stop = stop; } ResourceTester.prototype = { - launch: function(size, test, args) { + launch(size, test, args) { trigger_gc(); let cleaner = new ResourceCleaner(); this._start(size); diff --git a/toolkit/components/ctypes/tests/unit/test_finalizer.js b/toolkit/components/ctypes/tests/unit/test_finalizer.js index d50437da6eb5..d19c82eed1fc 100644 --- a/toolkit/components/ctypes/tests/unit/test_finalizer.js +++ b/toolkit/components/ctypes/tests/unit/test_finalizer.js @@ -34,8 +34,8 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status: status, - released: released + status, + released }); samples.push( { @@ -53,8 +53,8 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status: status, - released: released + status, + released }); samples.push( { @@ -72,8 +72,8 @@ function run_test() ctypes.bool, ctypes.int32_t, ctypes.int32_t), - status: status, - released: released + status, + released } ); samples.push( @@ -92,8 +92,8 @@ function run_test() ctypes.bool, ctypes.int64_t, ctypes.int64_t), - status: status, - released: released + status, + released } ); samples.push( @@ -112,8 +112,8 @@ function run_test() ctypes.bool, ctypes.void_t.ptr, ctypes.void_t.ptr), - status: status, - released: released + status, + released } ); samples.push( @@ -132,8 +132,8 @@ function run_test() ctypes.bool, ctypes.char.ptr, ctypes.char.ptr), - status: status, - released: released + status, + released } ); const rect_t = new ctypes.StructType("myRECT", @@ -157,8 +157,8 @@ function run_test() ctypes.bool, rect_t, rect_t), - status: status, - released: released + status, + released } ); samples.push( @@ -177,7 +177,7 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status: status, + status, released: function released_eq(i, witness) { return i == witness; } @@ -199,7 +199,7 @@ function run_test() ctypes.bool, ctypes.size_t, ctypes.size_t), - status: status, + status, released: function released_rect_eq(i, witness) { return witness.top == i && witness.bottom == i @@ -228,7 +228,7 @@ function run_test() ctypes.bool, ctypes.void_t.ptr, ctypes.void_t.ptr), - released: released + released } ); @@ -397,8 +397,8 @@ function test_executing_forget(size, tc, cleanup) let finalizer = ctypes.CDataFinalizer(original, tc.release); ref.push( { - original: original, - finalizer: finalizer + original, + finalizer } ); cleanup.add(finalizer); diff --git a/toolkit/components/ctypes/tests/unit/test_jsctypes.js b/toolkit/components/ctypes/tests/unit/test_jsctypes.js index 18861a185c3c..f91f40992d24 100644 --- a/toolkit/components/ctypes/tests/unit/test_jsctypes.js +++ b/toolkit/components/ctypes/tests/unit/test_jsctypes.js @@ -413,8 +413,8 @@ function run_Int64_tests() { ctypes.UInt64("0x8000000000000000"), Infinity, -Infinity, NaN, 0.1, 5.68e21, null, undefined, "", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { ctypes.Int64(vals[i]); }, TypeError); @@ -563,8 +563,8 @@ function run_UInt64_tests() { let vals = [-1, 0x10000000000000000, "-1", "-0x1", ctypes.Int64("-1"), Infinity, -Infinity, NaN, 0.1, 5.68e21, null, undefined, "", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { ctypes.UInt64(vals[i]); }, TypeError); @@ -778,8 +778,8 @@ function run_bool_tests(library) { let vals = [-1, 2, Infinity, -Infinity, NaN, 0.1, ctypes.Int64(0), ctypes.UInt64(0), null, undefined, "", "0", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -858,8 +858,8 @@ function run_integer_tests(library, t, name, size, signed, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "0", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -945,8 +945,8 @@ function run_float_tests(library, t, name, size) { // don't convert anything else let vals = [true, false, null, undefined, "", "0", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1045,8 +1045,8 @@ function run_wrapped_integer_tests(library, t, name, size, signed, w, wname, lim // don't convert anything else let vals = [limits[2], limits[3], Infinity, -Infinity, NaN, 0.1, null, undefined, "", "0", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1128,8 +1128,8 @@ function run_char_tests(library, t, name, size, signed, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "aa", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -1220,8 +1220,8 @@ function run_char16_tests(library, t, name, limits) { // don't convert anything else let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1, null, undefined, "", "aa", {}, [], new Number(16), - {toString: function() { return 7; }}, - {valueOf: function() { return 7; }}]; + {toString() { return 7; }}, + {valueOf() { return 7; }}]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { d.value = vals[i]; }, TypeError); @@ -2223,7 +2223,7 @@ function run_string_tests(library) { do_check_eq(test_ansi_len("hello world"), 11); // don't convert anything else to a string - let vals = [true, 0, 1 / 3, undefined, {}, {toString: function() { return "bad"; }}, []]; + let vals = [true, 0, 1 / 3, undefined, {}, {toString() { return "bad"; }}, []]; for (let i = 0; i < vals.length; i++) do_check_throws(function() { test_ansi_len(vals[i]); }, TypeError); diff --git a/toolkit/components/downloads/test/unit/test_app_rep_windows.js b/toolkit/components/downloads/test/unit/test_app_rep_windows.js index 49d89751bc83..44fd26999830 100644 --- a/toolkit/components/downloads/test/unit/test_app_rep_windows.js +++ b/toolkit/components/downloads/test/unit/test_app_rep_windows.js @@ -119,8 +119,8 @@ function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) { copier.init(inputStream, aSaverOutputStream, null, false, true, 0x8000, true, aCloseWhenDone); copier.asyncCopy({ - onStartRequest: function() { }, - onStopRequest: function(aRequest, aContext, aStatusCode) + onStartRequest() { }, + onStopRequest(aRequest, aContext, aStatusCode) { if (Components.isSuccessCode(aStatusCode)) { deferred.resolve(); diff --git a/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js b/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js index 7e9c715f69a1..f1f32995fa5f 100644 --- a/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js +++ b/toolkit/components/extensions/test/xpcshell/test_ext_storage_sync.js @@ -513,7 +513,6 @@ add_task(function* ensureKeysFor_posts_new_keys() { const newBody = yield assertPostedEncryptedKeys(newPost); ok(newBody.keys.collections[extensionId], `keys object should have a key for ${extensionId}`); ok(newBody.keys.collections[extensionId2], `keys object should have a key for ${extensionId2}`); - }); }); }); diff --git a/toolkit/components/exthelper/extApplication.js b/toolkit/components/exthelper/extApplication.js index ff17f37e5234..b592e8cdc782 100644 --- a/toolkit/components/exthelper/extApplication.js +++ b/toolkit/components/exthelper/extApplication.js @@ -663,7 +663,7 @@ extApplication.prototype = { return this.prefs; }, - getExtensions: function(callback) { + getExtensions(callback) { AddonManager.getAddonsByTypes(["extension"], function(addons) { callback.callback(new Extensions(addons)); }); diff --git a/toolkit/components/feeds/test/test_xml.js b/toolkit/components/feeds/test/test_xml.js index 5bc0d759d12a..5a6f350ef011 100644 --- a/toolkit/components/feeds/test/test_xml.js +++ b/toolkit/components/feeds/test/test_xml.js @@ -32,7 +32,7 @@ function FeedListener(testcase) { } FeedListener.prototype = { - handleResult: function(result) { + handleResult(result) { var feed = result.doc; try { do_print("Testing feed " + this.testcase.file.path); diff --git a/toolkit/components/filepicker/content/filepicker.js b/toolkit/components/filepicker/content/filepicker.js index 7dc0a936e616..1069a7b2cfa4 100644 --- a/toolkit/components/filepicker/content/filepicker.js +++ b/toolkit/components/filepicker/content/filepicker.js @@ -368,11 +368,11 @@ var gFilesEnumerator = { mFiles: null, mIndex: 0, - hasMoreElements: function() + hasMoreElements() { return (this.mIndex < this.mFiles.length); }, - getNext: function() + getNext() { if (this.mIndex >= this.mFiles.length) throw Components.results.NS_ERROR_FAILURE; diff --git a/toolkit/components/filepicker/nsFilePicker.js b/toolkit/components/filepicker/nsFilePicker.js index 97bb78e7631f..f40b0562765d 100644 --- a/toolkit/components/filepicker/nsFilePicker.js +++ b/toolkit/components/filepicker/nsFilePicker.js @@ -68,7 +68,7 @@ function nsFilePicker() nsFilePicker.prototype = { classID: Components.ID("{54ae32f8-1dd2-11b2-a209-df7c505370f8}"), - QueryInterface: function(iid) { + QueryInterface(iid) { if (iid.equals(nsIFilePicker) || iid.equals(nsISupports)) return this; @@ -113,11 +113,11 @@ nsFilePicker.prototype = { mFiles: [], mIndex: 0, - hasMoreElements: function() { + hasMoreElements() { return (this.mIndex < this.mFiles.length); }, - getNext: function() { + getNext() { if (this.mIndex >= this.mFiles.length) { throw Components.results.NS_ERROR_FAILURE; } @@ -176,13 +176,13 @@ nsFilePicker.prototype = { mParentWindow: null, /* methods */ - init: function(parent, title, mode) { + init(parent, title, mode) { this.mParentWindow = parent; this.mTitle = title; this.mMode = mode; }, - appendFilters: function(filterMask) { + appendFilters(filterMask) { if (filterMask & nsIFilePicker.filterHTML) { this.appendFilter(titleBundle.GetStringFromName("htmlTitle"), filterBundle.GetStringFromName("htmlFilter")); @@ -223,12 +223,12 @@ nsFilePicker.prototype = { } }, - appendFilter: function(title, extensions) { + appendFilter(title, extensions) { this.mFilterTitles.push(title); this.mFilters.push(extensions); }, - open: function(aFilePickerShownCallback) { + open(aFilePickerShownCallback) { var tm = Components.classes["@mozilla.org/thread-manager;1"] .getService(Components.interfaces.nsIThreadManager); tm.mainThread.dispatch(function() { @@ -243,7 +243,7 @@ nsFilePicker.prototype = { }.bind(this), Components.interfaces.nsIThread.DISPATCH_NORMAL); }, - show: function() { + show() { var o = {}; o.title = this.mTitle; o.mode = this.mMode; diff --git a/toolkit/components/filepicker/test/unit/test_filecomplete.js b/toolkit/components/filepicker/test/unit/test_filecomplete.js index d1e18d533748..8e15f4ac2bbf 100644 --- a/toolkit/components/filepicker/test/unit/test_filecomplete.js +++ b/toolkit/components/filepicker/test/unit/test_filecomplete.js @@ -19,7 +19,7 @@ dir.append("test_dir"); dir.create(dir.DIRECTORY_TYPE, -1); var gListener = { - onSearchResult: function(aSearch, aResult) { + onSearchResult(aSearch, aResult) { // Check that we got same search string back. do_check_eq(aResult.searchString, "test"); // Check that the search succeeded. diff --git a/toolkit/components/formautofill/FormAutofillContentService.js b/toolkit/components/formautofill/FormAutofillContentService.js index 2b64e19663a3..1de839f54d63 100644 --- a/toolkit/components/formautofill/FormAutofillContentService.js +++ b/toolkit/components/formautofill/FormAutofillContentService.js @@ -76,7 +76,7 @@ FormHandler.prototype = { ? new this.window.Event("autocomplete", { bubbles: true }) : new this.window.AutocompleteErrorEvent("autocompleteerror", { bubbles: true, - reason: reason }); + reason }); yield this.waitForTick(); this.form.dispatchEvent(event); }), @@ -143,7 +143,7 @@ FormHandler.prototype = { * interface, or null if the operation failed because the constraints * on the allowed fields were not honored. */ - collectFormFields: function() { + collectFormFields() { let autofillData = { sections: [], }; @@ -173,7 +173,7 @@ FormHandler.prototype = { addressType: info.addressType, contactType: info.contactType, fieldName: info.fieldName, - element: element, + element, }); // The first level is the custom section. @@ -225,7 +225,7 @@ FormHandler.prototype = { * ], * } */ - autofillFormFields: function(aAutofillResult) { + autofillFormFields(aAutofillResult) { for (let field of aAutofillResult.fields) { // Get the field details, if it was processed by the user interface. let fieldDetail = this.fieldDetails @@ -244,7 +244,7 @@ FormHandler.prototype = { /** * Waits for one tick of the event loop before resolving the returned promise. */ - waitForTick: function() { + waitForTick() { return new Promise(function(resolve) { Services.tm.currentThread.dispatch(resolve, Ci.nsIThread.DISPATCH_NORMAL); }); @@ -263,7 +263,7 @@ FormAutofillContentService.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIFormAutofillContentService]), // nsIFormAutofillContentService - requestAutocomplete: function(aForm, aWindow) { + requestAutocomplete(aForm, aWindow) { new FormHandler(aForm, aWindow).handleRequestAutocomplete() .catch(Cu.reportError); }, diff --git a/toolkit/components/formautofill/FormAutofillStartup.js b/toolkit/components/formautofill/FormAutofillStartup.js index a2c3b125774f..b459bc67fa61 100644 --- a/toolkit/components/formautofill/FormAutofillStartup.js +++ b/toolkit/components/formautofill/FormAutofillStartup.js @@ -31,7 +31,7 @@ FormAutofillStartup.prototype = { ]), // nsIObserver - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { // This method is called by the "profile-after-change" category on startup, // which is called before any web page loads. At this time, we need to // register a global message listener in the parent process preemptively, @@ -44,7 +44,7 @@ FormAutofillStartup.prototype = { }, // nsIFrameMessageListener - receiveMessage: function(aMessage) { + receiveMessage(aMessage) { // Process the "FormAutofill:RequestAutocomplete" message. Any exception // raised in the parent process is caught and serialized into the reply // message that is sent to the requesting child process. diff --git a/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm b/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm index f2f2ddded104..23743f49e056 100644 --- a/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm +++ b/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm @@ -40,7 +40,7 @@ this.RequestAutocompleteUI.prototype = { // Wrap the callback function so that it survives XPCOM. let args = { - resolveFn: resolveFn, + resolveFn, autofillData: this._autofillData, }; args.wrappedJSObject = args; diff --git a/toolkit/components/formautofill/content/requestAutocomplete.js b/toolkit/components/formautofill/content/requestAutocomplete.js index 5dbbdc9c182d..269018d8ffb9 100644 --- a/toolkit/components/formautofill/content/requestAutocomplete.js +++ b/toolkit/components/formautofill/content/requestAutocomplete.js @@ -22,7 +22,7 @@ const RequestAutocompleteDialog = { resolveFn: null, autofillData: null, - onLoad: function() { + onLoad() { Task.spawn(function* () { let args = window.arguments[0].wrappedJSObject; this.resolveFn = args.resolveFn; @@ -35,7 +35,7 @@ const RequestAutocompleteDialog = { }.bind(this)).catch(Cu.reportError); }, - onAccept: function() { + onAccept() { // TODO: Replace with autofill storage module (bug 1018304). const dummyDB = { "": { @@ -65,7 +65,7 @@ const RequestAutocompleteDialog = { result.fields.push({ section: section.name, - addressType: addressType, + addressType, contactType: field.contactType, fieldName: field.fieldName, value: dummyDB[addressType][fieldName], @@ -78,7 +78,7 @@ const RequestAutocompleteDialog = { this.resolveFn(result); }, - onCancel: function() { + onCancel() { window.close(); this.resolveFn({ canceled: true }); }, diff --git a/toolkit/components/formautofill/test/chrome/loader.js b/toolkit/components/formautofill/test/chrome/loader.js index 556211e3df30..4cdc3cd6ed59 100644 --- a/toolkit/components/formautofill/test/chrome/loader.js +++ b/toolkit/components/formautofill/test/chrome/loader.js @@ -33,7 +33,7 @@ var testUrl = location.href.replace(/\.\w+$/, ".js"); var promiseParentInitFinished = new Promise(function(resolve) { parentScript.addMessageListener("finish_load_in_parent", resolve); }); -parentScript.sendAsyncMessage("start_load_in_parent", { testUrl: testUrl }); +parentScript.sendAsyncMessage("start_load_in_parent", { testUrl }); // Define output functions so they look the same across all frameworks. var Output = { diff --git a/toolkit/components/formautofill/test/head_common.js b/toolkit/components/formautofill/test/head_common.js index f3fec4293929..87a23f0756a1 100644 --- a/toolkit/components/formautofill/test/head_common.js +++ b/toolkit/components/formautofill/test/head_common.js @@ -42,7 +42,7 @@ var TestUtils = { * @resolves When pending events have been processed. * @rejects Never. */ - waitForTick: function() { + waitForTick() { return new Promise(resolve => executeSoon(resolve)); }, @@ -58,7 +58,7 @@ var TestUtils = { * @resolves When the specified time has passed. * @rejects Never. */ - waitMs: function(aTimeMs) { + waitMs(aTimeMs) { return new Promise(resolve => setTimeout(resolve, aTimeMs)); }, @@ -72,7 +72,7 @@ var TestUtils = { * @resolves The array [aSubject, aData] from the observed notification. * @rejects Never. */ - waitForNotification: function(aTopic) { + waitForNotification(aTopic) { Output.print("Waiting for notification: '" + aTopic + "'."); return new Promise(resolve => Services.obs.addObserver( @@ -96,7 +96,7 @@ var TestUtils = { * @resolves The arguments from the observed event. * @rejects Never. */ - waitForEvent: function(aTarget, aEventName, aUseCapture = false) { + waitForEvent(aTarget, aEventName, aUseCapture = false) { Output.print("Waiting for event: '" + aEventName + "' on " + aTarget + "."); return new Promise(resolve => aTarget.addEventListener(aEventName, @@ -183,7 +183,7 @@ var FormAutofillTest = { // The window is the subject of the observer notification. return { uiWindow: (yield promiseUIWindow)[0], - promiseResult: promiseResult, + promiseResult, }; }), }; diff --git a/toolkit/components/formautofill/test/loader_common.js b/toolkit/components/formautofill/test/loader_common.js index 3f5fae5b2f49..33a838b4a31b 100644 --- a/toolkit/components/formautofill/test/loader_common.js +++ b/toolkit/components/formautofill/test/loader_common.js @@ -104,12 +104,12 @@ function getTaskId(stackFrame) { // This is a shared helper for mochitest-chrome and mochitest-browser. var _mochitestAssert = { - ok: function(actual) { + ok(actual) { let stack = Components.stack.caller; ok(actual, "[" + stack.name + " : " + stack.lineNumber + "] " + actual + " == true"); }, - equal: function(actual, expected) { + equal(actual, expected) { let stack = Components.stack.caller; is(actual, expected, "[" + stack.name + " : " + stack.lineNumber + "] " + actual + " == " + expected); diff --git a/toolkit/components/gfx/SanityTest.js b/toolkit/components/gfx/SanityTest.js index f600d2bd4e56..3f43202cd163 100644 --- a/toolkit/components/gfx/SanityTest.js +++ b/toolkit/components/gfx/SanityTest.js @@ -153,7 +153,7 @@ var listener = { "gfxSanity:ContentLoaded", ], - scheduleTest: function(win) { + scheduleTest(win) { this.win = win; this.win.onload = this.onWindowLoaded.bind(this); this.utils = this.win.QueryInterface(Ci.nsIInterfaceRequestor) @@ -166,7 +166,7 @@ var listener = { }); }, - runSanityTest: function() { + runSanityTest() { this.canvas = this.win.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); this.canvas.setAttribute("width", PAGE_WIDTH); this.canvas.setAttribute("height", PAGE_HEIGHT); @@ -187,7 +187,7 @@ var listener = { } }, - onWindowLoaded: function() { + onWindowLoaded() { let browser = this.win.document.createElementNS(XUL_NS, "browser"); browser.setAttribute("type", "content"); @@ -208,7 +208,7 @@ var listener = { this.mm.loadFrameScript(FRAME_SCRIPT_URL, false); }, - endTest: function() { + endTest() { if (!this.win) { return; } @@ -240,7 +240,7 @@ SanityTest.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - shouldRunTest: function() { + shouldRunTest() { // Only test gfx features if firefox has updated, or if the user has a new // gpu or drivers. var buildId = Services.appinfo.platformBuildID; @@ -286,7 +286,7 @@ SanityTest.prototype = { return true; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic != "profile-after-change") return; // profile-after-change fires only at startup, so we won't need diff --git a/toolkit/components/gfx/content/gfxFrameScript.js b/toolkit/components/gfx/content/gfxFrameScript.js index 4b48dc11ac7e..eaac257ceff7 100644 --- a/toolkit/components/gfx/content/gfxFrameScript.js +++ b/toolkit/components/gfx/content/gfxFrameScript.js @@ -3,7 +3,7 @@ var { classes: Cc, interfaces: Ci, utils: Cu } = Components; const gfxFrameScript = { domUtils: null, - init: function() { + init() { let webNav = docShell.QueryInterface(Ci.nsIWebNavigation); let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebProgress); @@ -18,7 +18,7 @@ const gfxFrameScript = { }, - handleEvent: function(aEvent) { + handleEvent(aEvent) { switch (aEvent.type) { case "MozAfterPaint": sendAsyncMessage('gfxSanity:ContentLoaded'); @@ -27,7 +27,7 @@ const gfxFrameScript = { } }, - isSanityTest: function(aUri) { + isSanityTest(aUri) { if (!aUri) { return false; } @@ -35,7 +35,7 @@ const gfxFrameScript = { return aUri.endsWith("/sanitytest.html"); }, - onStateChange: function(webProgress, req, flags, status) { + onStateChange(webProgress, req, flags, status) { if (webProgress.isTopLevel && (flags & Ci.nsIWebProgressListener.STATE_STOP) && this.isSanityTest(req.name)) { diff --git a/toolkit/components/jsdownloads/src/DownloadCore.jsm b/toolkit/components/jsdownloads/src/DownloadCore.jsm index 043f20cc18e9..ef10dec742b9 100644 --- a/toolkit/components/jsdownloads/src/DownloadCore.jsm +++ b/toolkit/components/jsdownloads/src/DownloadCore.jsm @@ -622,7 +622,7 @@ this.Download.prototype = { * @resolves When the Download has been unblocked and succeeded. * @rejects JavaScript exception if any of the operations failed. */ - unblock: function() { + unblock() { if (this._promiseUnblock) { return this._promiseUnblock; } @@ -666,7 +666,7 @@ this.Download.prototype = { * @resolves When the Download's data has been removed. * @rejects JavaScript exception if any of the operations failed. */ - confirmBlock: function() { + confirmBlock() { if (this._promiseConfirmBlock) { return this._promiseConfirmBlock; } @@ -711,7 +711,7 @@ this.Download.prototype = { * @rejects JavaScript exception if there was an error trying to launch * the file. */ - launch: function() { + launch() { if (!this.succeeded) { return Promise.reject( new Error("launch can only be called if the download succeeded") @@ -845,7 +845,7 @@ this.Download.prototype = { * @resolves When the partial data has been successfully removed. * @rejects JavaScript exception if the operation could not be completed. */ - removePartialData: function() + removePartialData() { if (!this.canceled && !this.error) { return Promise.resolve(); @@ -920,7 +920,7 @@ this.Download.prototype = { * @resolves When the operation has completed. * @rejects Never. */ - refresh: function() + refresh() { return Task.spawn(function* () { if (!this.stopped || this._finalized) { @@ -999,7 +999,7 @@ this.Download.prototype = { * @rejects JavaScript exception if an error occurred while removing the * partially downloaded data. */ - finalize: function(aRemovePartialData) + finalize(aRemovePartialData) { // Prevents the download from starting again after having been stopped. this._finalized = true; @@ -1096,7 +1096,7 @@ this.Download.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { let serializable = { source: this.source.toSerializable(), @@ -1148,7 +1148,7 @@ this.Download.prototype = { * * @return String representing the relevant download state. */ - getSerializationHash: function() + getSerializationHash() { // The "succeeded", "canceled", "error", and startTime properties are not // taken into account because they all change before the "stopped" property @@ -1296,7 +1296,7 @@ this.DownloadSource.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { if (this.adjustChannel) { // If the callback was used, we can't reproduce this across sessions. @@ -1452,7 +1452,7 @@ this.DownloadTarget.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { // Simplify the representation if we don't have other details. if (!this.partFilePath && !this._unknownProperties) { @@ -1654,7 +1654,7 @@ this.DownloadError.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { let serializable = { result: this.result, @@ -1769,7 +1769,7 @@ this.DownloadSaver.prototype = { * started, to add it to the browsing history. This method has no effect if * the download is private. */ - addToHistory: function() + addToHistory() { if (this.download.source.isPrivate) { return; @@ -1806,7 +1806,7 @@ this.DownloadSaver.prototype = { * * @return A JavaScript object that can be serialized to JSON. */ - toSerializable: function() + toSerializable() { throw new Error("Not implemented."); }, @@ -1814,12 +1814,12 @@ this.DownloadSaver.prototype = { /** * Returns the SHA-256 hash of the downloaded file, if it exists. */ - getSha256Hash: function() + getSha256Hash() { throw new Error("Not implemented."); }, - getSignatureInfo: function() + getSignatureInfo() { throw new Error("Not implemented."); }, @@ -1968,7 +1968,7 @@ this.DownloadCopySaver.prototype = { // When the operation completes, reflect the status in the promise // returned by this download execution function. backgroundFileSaver.observer = { - onTargetChange: function() { }, + onTargetChange() { }, onSaveComplete: (aSaver, aStatus) => { // Send notifications now that we can restart if needed. if (Components.isSuccessCode(aStatus)) { @@ -2033,7 +2033,7 @@ this.DownloadCopySaver.prototype = { aSetProgressBytesFn(currentBytes, totalBytes, aProgress > 0 && partFilePath && keepPartialData); }, - onStatus: function() { }, + onStatus() { }, }; // If the callback was set, handle it now before opening the channel. @@ -2257,7 +2257,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.removePartialData". */ - removePartialData: function() + removePartialData() { return Task.spawn(function* task_DCS_removePartialData() { if (this.download.target.partFilePath) { @@ -2275,7 +2275,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable: function() + toSerializable() { // Simplify the representation if we don't have other details. if (!this.entityID && !this._unknownProperties) { @@ -2291,7 +2291,7 @@ this.DownloadCopySaver.prototype = { /** * Implements "DownloadSaver.getSha256Hash" */ - getSha256Hash: function() + getSha256Hash() { return this._sha256Hash; }, @@ -2299,7 +2299,7 @@ this.DownloadCopySaver.prototype = { /* * Implements DownloadSaver.getSignatureInfo. */ - getSignatureInfo: function() + getSignatureInfo() { return this._signatureInfo; }, @@ -2307,7 +2307,7 @@ this.DownloadCopySaver.prototype = { /* * Implements DownloadSaver.getRedirects. */ - getRedirects: function() + getRedirects() { return this._redirects; } @@ -2440,7 +2440,7 @@ this.DownloadLegacySaver.prototype = { * download is added to the browsing history here. Private downloads * are never added to history even if this parameter is false. */ - onTransferStarted: function(aRequest, aAlreadyAddedToHistory) + onTransferStarted(aRequest, aAlreadyAddedToHistory) { // Store the entity ID to use for resuming if required. if (this.download.tryToKeepPartialData && @@ -2603,7 +2603,7 @@ this.DownloadLegacySaver.prototype = { }.bind(this)); }, - _checkReputationAndMove: function() { + _checkReputationAndMove() { return DownloadCopySaver.prototype._checkReputationAndMove .apply(this, arguments); }, @@ -2629,7 +2629,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.removePartialData". */ - removePartialData: function() + removePartialData() { // DownloadCopySaver and DownloadLeagcySaver use the same logic for removing // partially downloaded data, though this implementation isn't shared by @@ -2640,7 +2640,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable: function() + toSerializable() { // This object depends on legacy components that are created externally, // thus it cannot be rebuilt during deserialization. To support resuming @@ -2652,7 +2652,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getSha256Hash". */ - getSha256Hash: function() + getSha256Hash() { if (this.copySaver) { return this.copySaver.getSha256Hash(); @@ -2663,7 +2663,7 @@ this.DownloadLegacySaver.prototype = { /** * Called by the nsITransfer implementation when the hash is available. */ - setSha256Hash: function(hash) + setSha256Hash(hash) { this._sha256Hash = hash; }, @@ -2671,7 +2671,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getSignatureInfo". */ - getSignatureInfo: function() + getSignatureInfo() { if (this.copySaver) { return this.copySaver.getSignatureInfo(); @@ -2682,7 +2682,7 @@ this.DownloadLegacySaver.prototype = { /** * Called by the nsITransfer implementation when the hash is available. */ - setSignatureInfo: function(signatureInfo) + setSignatureInfo(signatureInfo) { this._signatureInfo = signatureInfo; }, @@ -2690,7 +2690,7 @@ this.DownloadLegacySaver.prototype = { /** * Implements "DownloadSaver.getRedirects". */ - getRedirects: function() + getRedirects() { if (this.copySaver) { return this.copySaver.getRedirects(); @@ -2702,7 +2702,7 @@ this.DownloadLegacySaver.prototype = { * Called by the nsITransfer implementation when the redirect chain is * available. */ - setRedirects: function(redirects) + setRedirects(redirects) { this._redirects = redirects; }, @@ -2746,7 +2746,7 @@ this.DownloadPDFSaver.prototype = { /** * Implements "DownloadSaver.execute". */ - execute: function(aSetProgressBytesFn, aSetPropertiesFn) + execute(aSetProgressBytesFn, aSetPropertiesFn) { return Task.spawn(function* task_DCS_execute() { if (!this.download.source.windowRef) { @@ -2801,7 +2801,7 @@ this.DownloadPDFSaver.prototype = { try { yield new Promise((resolve, reject) => { this._webBrowserPrint.print(printSettings, { - onStateChange: function(webProgress, request, stateFlags, status) { + onStateChange(webProgress, request, stateFlags, status) { if (stateFlags & Ci.nsIWebProgressListener.STATE_STOP) { if (!Components.isSuccessCode(status)) { reject(new DownloadError({ result: status, @@ -2811,14 +2811,14 @@ this.DownloadPDFSaver.prototype = { } } }, - onProgressChange: function(webProgress, request, curSelfProgress, + onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) { aSetProgressBytesFn(curTotalProgress, maxTotalProgress, false); }, - onLocationChange: function() {}, - onStatusChange: function() {}, - onSecurityChange: function() {}, + onLocationChange() {}, + onStatusChange() {}, + onSecurityChange() {}, }); }); } finally { @@ -2845,7 +2845,7 @@ this.DownloadPDFSaver.prototype = { /** * Implements "DownloadSaver.toSerializable". */ - toSerializable: function() + toSerializable() { if (this.download.succeeded) { return DownloadCopySaver.prototype.toSerializable.call(this); diff --git a/toolkit/components/jsdownloads/src/DownloadImport.jsm b/toolkit/components/jsdownloads/src/DownloadImport.jsm index c1c81cc6e617..fec2348fe499 100644 --- a/toolkit/components/jsdownloads/src/DownloadImport.jsm +++ b/toolkit/components/jsdownloads/src/DownloadImport.jsm @@ -68,7 +68,7 @@ this.DownloadImport.prototype = { * from the previous database has been read and added to * the DownloadList) */ - import: function() { + import() { return Task.spawn(function* task_DI_import() { let connection = yield Sqlite.openConnection({ path: this.path }); @@ -142,7 +142,7 @@ this.DownloadImport.prototype = { let downloadOptions = { source: { url: source, - referrer: referrer + referrer }, target: { path: targetPath, @@ -150,13 +150,13 @@ this.DownloadImport.prototype = { }, saver: { type: "copy", - entityID: entityID + entityID }, startTime: new Date(startTime / 1000), totalBytes: maxBytes, hasPartialData: !!tempPath, tryToKeepPartialData: true, - launchWhenSucceeded: launchWhenSucceeded, + launchWhenSucceeded, contentType: mimeType, launcherPath: preferredApplication }; diff --git a/toolkit/components/jsdownloads/src/DownloadLegacy.js b/toolkit/components/jsdownloads/src/DownloadLegacy.js index c9bcbdd82e15..368215524eaf 100644 --- a/toolkit/components/jsdownloads/src/DownloadLegacy.js +++ b/toolkit/components/jsdownloads/src/DownloadLegacy.js @@ -166,7 +166,7 @@ DownloadLegacyTransfer.prototype = { aMaxTotalProgress); }, - onLocationChange: function() { }, + onLocationChange() { }, onStatusChange: function DLT_onStatusChange(aWebProgress, aRequest, aStatus, aMessage) @@ -184,7 +184,7 @@ DownloadLegacyTransfer.prototype = { } }, - onSecurityChange: function() { }, + onSecurityChange() { }, // nsIWebProgressListener2 @@ -237,9 +237,9 @@ DownloadLegacyTransfer.prototype = { target: { path: aTarget.QueryInterface(Ci.nsIFileURL).file.path, partFilePath: aTempFile && aTempFile.path }, saver: "legacy", - launchWhenSucceeded: launchWhenSucceeded, - contentType: contentType, - launcherPath: launcherPath + launchWhenSucceeded, + contentType, + launcherPath }).then(function DLT_I_onDownload(aDownload) { // Legacy components keep partial data when they use a ".part" file. if (aTempFile) { @@ -257,17 +257,17 @@ DownloadLegacyTransfer.prototype = { }.bind(this)).then(null, Cu.reportError); }, - setSha256Hash: function(hash) + setSha256Hash(hash) { this._sha256Hash = hash; }, - setSignatureInfo: function(signatureInfo) + setSignatureInfo(signatureInfo) { this._signatureInfo = signatureInfo; }, - setRedirects: function(redirects) + setRedirects(redirects) { this._redirects = redirects; }, diff --git a/toolkit/components/jsdownloads/src/DownloadList.jsm b/toolkit/components/jsdownloads/src/DownloadList.jsm index 4ab42e18648a..32fbfe5966bf 100644 --- a/toolkit/components/jsdownloads/src/DownloadList.jsm +++ b/toolkit/components/jsdownloads/src/DownloadList.jsm @@ -204,7 +204,7 @@ this.DownloadList.prototype = { * @param aDownload * The Download object that changed. */ - _notifyAllViews: function(aMethodName, aDownload) { + _notifyAllViews(aMethodName, aDownload) { for (let view of this._views) { try { if (aMethodName in view) { @@ -305,7 +305,7 @@ this.DownloadCombinedList.prototype = { * @resolves When the download has been added. * @rejects JavaScript exception. */ - add: function(aDownload) + add(aDownload) { if (aDownload.source.isPrivate) { return this._privateList.add(aDownload); @@ -329,7 +329,7 @@ this.DownloadCombinedList.prototype = { * @resolves When the download has been removed. * @rejects JavaScript exception. */ - remove: function(aDownload) + remove(aDownload) { if (aDownload.source.isPrivate) { return this._privateList.remove(aDownload); @@ -339,18 +339,18 @@ this.DownloadCombinedList.prototype = { // DownloadList view - onDownloadAdded: function(aDownload) + onDownloadAdded(aDownload) { this._downloads.push(aDownload); this._notifyAllViews("onDownloadAdded", aDownload); }, - onDownloadChanged: function(aDownload) + onDownloadChanged(aDownload) { this._notifyAllViews("onDownloadChanged", aDownload); }, - onDownloadRemoved: function(aDownload) + onDownloadRemoved(aDownload) { let index = this._downloads.indexOf(aDownload); if (index != -1) { @@ -396,7 +396,7 @@ this.DownloadSummary.prototype = { * @resolves When the view on the underlying list has been registered. * @rejects JavaScript exception. */ - bindToList: function(aList) + bindToList(aList) { if (this._list) { throw new Error("bindToList may be called only once."); @@ -432,7 +432,7 @@ this.DownloadSummary.prototype = { * notification has been sent. * @rejects JavaScript exception. */ - addView: function(aView) + addView(aView) { this._views.add(aView); @@ -458,7 +458,7 @@ this.DownloadSummary.prototype = { * will not receive any more notifications. * @rejects JavaScript exception. */ - removeView: function(aView) + removeView(aView) { this._views.delete(aView); @@ -494,7 +494,7 @@ this.DownloadSummary.prototype = { * and will recalculate the summary and notify the views in case the * aggregated properties are different. */ - _onListChanged: function() { + _onListChanged() { let allHaveStopped = true; let progressTotalBytes = 0; let progressCurrentBytes = 0; @@ -535,7 +535,7 @@ this.DownloadSummary.prototype = { // DownloadList view - onDownloadAdded: function(aDownload) + onDownloadAdded(aDownload) { this._downloads.push(aDownload); if (this._list) { @@ -543,12 +543,12 @@ this.DownloadSummary.prototype = { } }, - onDownloadChanged: function(aDownload) + onDownloadChanged(aDownload) { this._onListChanged(); }, - onDownloadRemoved: function(aDownload) + onDownloadRemoved(aDownload) { let index = this._downloads.indexOf(aDownload); if (index != -1) { diff --git a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm index 6e85d0b04b25..9eb05dd6367d 100644 --- a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm +++ b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm @@ -63,7 +63,7 @@ this.DownloadUIHelper = { * * @return A DownloadPrompter object. */ - getPrompter: function(aParent) + getPrompter(aParent) { return new DownloadPrompter(aParent || null); }, @@ -139,7 +139,7 @@ this.DownloadPrompter.prototype = { * @resolves Boolean indicating whether the launch operation can continue. * @rejects JavaScript exception. */ - confirmLaunchExecutable: function(aPath) + confirmLaunchExecutable(aPath) { const kPrefAlertOnEXEOpen = "browser.download.manager.alertOnEXEOpen"; diff --git a/toolkit/components/jsdownloads/src/Downloads.jsm b/toolkit/components/jsdownloads/src/Downloads.jsm index 174f807a5977..cbbb79a6309b 100644 --- a/toolkit/components/jsdownloads/src/Downloads.jsm +++ b/toolkit/components/jsdownloads/src/Downloads.jsm @@ -139,7 +139,7 @@ this.Downloads = { * @resolves When the download has finished successfully. * @rejects JavaScript exception if the download failed. */ - fetch: function(aSource, aTarget, aOptions) { + fetch(aSource, aTarget, aOptions) { return this.createDownload({ source: aSource, target: aTarget, @@ -170,7 +170,7 @@ this.Downloads = { * @resolves The requested DownloadList or DownloadCombinedList object. * @rejects JavaScript exception. */ - getList: function(aType) + getList(aType) { if (!this._promiseListsInitialized) { this._promiseListsInitialized = Task.spawn(function* () { @@ -232,7 +232,7 @@ this.Downloads = { * @resolves The requested DownloadList or DownloadCombinedList object. * @rejects JavaScript exception. */ - getSummary: function(aType) + getSummary(aType) { if (aType != Downloads.PUBLIC && aType != Downloads.PRIVATE && aType != Downloads.ALL) { diff --git a/toolkit/components/jsdownloads/test/unit/common_test_Download.js b/toolkit/components/jsdownloads/test/unit/common_test_Download.js index 3310eef05a19..1b0ad82c32c0 100644 --- a/toolkit/components/jsdownloads/test/unit/common_test_Download.js +++ b/toolkit/components/jsdownloads/test/unit/common_test_Download.js @@ -200,7 +200,7 @@ add_task(function* test_basic() // When testing DownloadLegacySaver, the download is already started when it // is created, thus we must check its basic properties while in progress. download = yield promiseStartLegacyDownload(null, - { targetFile: targetFile }); + { targetFile }); do_check_eq(download.source.url, httpUrl("source.txt")); do_check_eq(download.target.path, targetFile.path); @@ -1391,7 +1391,7 @@ add_task(function* test_error_target() // the "error" property checked by promiseDownloadStopped. This happens // because we don't have control over when the download is started. download = yield promiseStartLegacyDownload(null, - { targetFile: targetFile }); + { targetFile }); yield promiseDownloadStopped(download); } do_throw("The download should have failed."); @@ -1438,7 +1438,7 @@ add_task(function* test_error_restart() download.start().catch(() => {}); } else { download = yield promiseStartLegacyDownload(null, - { targetFile: targetFile }); + { targetFile }); } yield promiseDownloadStopped(download); do_throw("The download should have failed."); @@ -2167,7 +2167,7 @@ add_task(function* test_launch() { download = yield Downloads.createDownload({ source: httpUrl("source.txt"), target: getTempFile(TEST_TARGET_FILE_NAME).path, - launcherPath: launcherPath, + launcherPath, launchWhenSucceeded: true }); @@ -2185,7 +2185,7 @@ add_task(function* test_launch() { // it is created, thus we don't test calling "launch" before starting. download = yield promiseStartLegacyDownload( httpUrl("source.txt"), - { launcherPath: launcherPath, + { launcherPath, launchWhenSucceeded: true }); yield promiseDownloadStopped(download); } @@ -2266,13 +2266,13 @@ add_task(function* test_launchWhenSucceeded() { source: httpUrl("source.txt"), target: getTempFile(TEST_TARGET_FILE_NAME).path, launchWhenSucceeded: true, - launcherPath: launcherPath, + launcherPath, }); yield download.start(); } else { let download = yield promiseStartLegacyDownload( httpUrl("source.txt"), - { launcherPath: launcherPath, + { launcherPath, launchWhenSucceeded: true }); yield promiseDownloadStopped(download); } @@ -2338,7 +2338,7 @@ add_task(function* test_platform_integration() } let downloadWatcherNotified = false; let observer = { - observe: function(subject, topic, data) { + observe(subject, topic, data) { do_check_eq(topic, "download-watcher-notify"); do_check_eq(data, "modified"); downloadWatcherNotified = true; diff --git a/toolkit/components/jsdownloads/test/unit/head.js b/toolkit/components/jsdownloads/test/unit/head.js index 42fa2bb96f87..866392c79ebd 100644 --- a/toolkit/components/jsdownloads/test/unit/head.js +++ b/toolkit/components/jsdownloads/test/unit/head.js @@ -203,20 +203,20 @@ function promiseWaitForVisit(aUrl) PlacesUtils.history.addObserver({ QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver]), - onBeginUpdateBatch: function() {}, - onEndUpdateBatch: function() {}, - onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID, + onBeginUpdateBatch() {}, + onEndUpdateBatch() {}, + onVisit(aURI, aVisitID, aTime, aSessionID, aReferringID, aTransitionType, aGUID, aHidden) { if (aURI.equals(uri)) { PlacesUtils.history.removeObserver(this); deferred.resolve([aTime, aTransitionType]); } }, - onTitleChanged: function() {}, - onDeleteURI: function() {}, - onClearHistory: function() {}, - onPageChanged: function() {}, - onDeleteVisits: function() {}, + onTitleChanged() {}, + onDeleteURI() {}, + onClearHistory() {}, + onPageChanged() {}, + onDeleteVisits() {}, }, false); return deferred.promise; @@ -342,7 +342,7 @@ function promiseStartLegacyDownload(aSourceUrl, aOptions) { // Temporarily register a view that will get notified when the download we // are controlling becomes visible in the list of downloads. aList.addView({ - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { aList.removeView(this).then(null, do_report_unexpected_exception); // Remove the download to keep the list empty for the next test. This @@ -395,7 +395,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { // Temporarily register a view that will get notified when the download we // are controlling becomes visible in the list of downloads. aList.addView({ - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { aList.removeView(this).then(null, do_report_unexpected_exception); // Remove the download to keep the list empty for the next test. This @@ -417,7 +417,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { channel.asyncOpen2({ contentListener: null, - onStartRequest: function(aRequest, aContext) + onStartRequest(aRequest, aContext) { let requestChannel = aRequest.QueryInterface(Ci.nsIChannel); this.contentListener = gExternalHelperAppService.doContent( @@ -425,12 +425,12 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { this.contentListener.onStartRequest(aRequest, aContext); }, - onStopRequest: function(aRequest, aContext, aStatusCode) + onStopRequest(aRequest, aContext, aStatusCode) { this.contentListener.onStopRequest(aRequest, aContext, aStatusCode); }, - onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, + onDataAvailable(aRequest, aContext, aInputStream, aOffset, aCount) { this.contentListener.onDataAvailable(aRequest, aContext, aInputStream, @@ -577,10 +577,10 @@ function startFakeServer() { let serverSocket = new ServerSocket(-1, true, -1); serverSocket.asyncListen({ - onSocketAccepted: function(aServ, aTransport) { + onSocketAccepted(aServ, aTransport) { aTransport.close(Cr.NS_BINDING_ABORTED); }, - onStopListening: function() { }, + onStopListening() { }, }); return serverSocket; } diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js b/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js index cce155716fd6..d470d33da908 100644 --- a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js +++ b/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js @@ -169,14 +169,14 @@ function promiseEntityID(aUrl) { }); channel.asyncOpen2({ - onStartRequest: function(aRequest) { + onStartRequest(aRequest) { if (aRequest instanceof Ci.nsIResumableChannel) { entityID = aRequest.entityID; } aRequest.cancel(Cr.NS_BINDING_ABORTED); }, - onStopRequest: function(aRequest, aContext, aStatusCode) { + onStopRequest(aRequest, aContext, aStatusCode) { if (aStatusCode == Cr.NS_BINDING_ABORTED) { deferred.resolve(entityID); } else { @@ -184,7 +184,7 @@ function promiseEntityID(aUrl) { } }, - onDataAvailable: function() {} + onDataAvailable() {} }); return deferred.promise; diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js b/toolkit/components/jsdownloads/test/unit/test_DownloadList.js index b3e24b0dba67..42cd77e784ee 100644 --- a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js +++ b/toolkit/components/jsdownloads/test/unit/test_DownloadList.js @@ -56,7 +56,7 @@ function promiseExpirableDownloadVisit(aSourceUrl) aResultCode); deferred.reject(ex); }, - handleResult: function() {}, + handleResult() {}, handleCompletion: function handleCompletion() { deferred.resolve(); } @@ -192,7 +192,7 @@ add_task(function* test_notifications_add_remove() // Check that we receive add notifications for existing elements. let addNotifications = 0; let viewOne = { - onDownloadAdded: function(aDownload) { + onDownloadAdded(aDownload) { // The first download to be notified should be the first that was added. if (addNotifications == 0) { do_check_eq(aDownload, downloadOne); @@ -212,7 +212,7 @@ add_task(function* test_notifications_add_remove() // Check that we receive remove notifications. let removeNotifications = 0; let viewTwo = { - onDownloadRemoved: function(aDownload) { + onDownloadRemoved(aDownload) { do_check_eq(aDownload, downloadOne); removeNotifications++; }, @@ -257,7 +257,7 @@ add_task(function* test_notifications_change() // Check that we receive change notifications. let receivedOnDownloadChanged = false; yield list.addView({ - onDownloadChanged: function(aDownload) { + onDownloadChanged(aDownload) { do_check_eq(aDownload, downloadOne); receivedOnDownloadChanged = true; }, @@ -285,18 +285,18 @@ add_task(function* test_notifications_this() let receivedOnDownloadChanged = false; let receivedOnDownloadRemoved = false; let view = { - onDownloadAdded: function() { + onDownloadAdded() { do_check_eq(this, view); receivedOnDownloadAdded = true; }, - onDownloadChanged: function() { + onDownloadChanged() { // Only do this check once. if (!receivedOnDownloadChanged) { do_check_eq(this, view); receivedOnDownloadChanged = true; } }, - onDownloadRemoved: function() { + onDownloadRemoved() { do_check_eq(this, view); receivedOnDownloadRemoved = true; }, @@ -336,7 +336,7 @@ add_task(function* test_history_expiration() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved: function(aDownload) { + onDownloadRemoved(aDownload) { if (++removeNotifications == 2) { deferred.resolve(); } @@ -383,7 +383,7 @@ add_task(function* test_history_clear() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved: function(aDownload) { + onDownloadRemoved(aDownload) { if (++removeNotifications == 2) { deferred.resolve(); } @@ -419,7 +419,7 @@ add_task(function* test_removeFinished() let deferred = Promise.defer(); let removeNotifications = 0; let downloadView = { - onDownloadRemoved: function(aDownload) { + onDownloadRemoved(aDownload) { do_check_true(aDownload == downloadOne || aDownload == downloadTwo || aDownload == downloadThree); @@ -555,7 +555,7 @@ add_task(function* test_DownloadSummary_notifications() // Check that we receive change notifications. let receivedOnSummaryChanged = false; yield summary.addView({ - onSummaryChanged: function() { + onSummaryChanged() { receivedOnSummaryChanged = true; }, }); diff --git a/toolkit/components/lz4/lz4.js b/toolkit/components/lz4/lz4.js index 8d4ffcf8e58e..70dd758e8537 100644 --- a/toolkit/components/lz4/lz4.js +++ b/toolkit/components/lz4/lz4.js @@ -150,7 +150,7 @@ exports.decompressFileContent = decompressFileContent; if (typeof Components != "undefined") { this.Lz4 = { - compressFileContent: compressFileContent, - decompressFileContent: decompressFileContent + compressFileContent, + decompressFileContent }; } diff --git a/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js b/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js index b26d554a8e6a..745f44dd81cd 100644 --- a/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js +++ b/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js @@ -45,12 +45,12 @@ const tests = [ // A basic listener that reads checks the if we sniffed properly. var listener = { - onStartRequest: function(request, context) { + onStartRequest(request, context) { do_check_eq(request.QueryInterface(Ci.nsIChannel).contentType, tests[testRan].expectedContentType); }, - onDataAvailable: function(request, context, stream, offset, count) { + onDataAvailable(request, context, stream, offset, count) { try { var bis = Components.classes["@mozilla.org/binaryinputstream;1"] .createInstance(Components.interfaces.nsIBinaryInputStream); @@ -61,7 +61,7 @@ var listener = { } }, - onStopRequest: function(request, context, status) { + onStopRequest(request, context, status) { testRan++; runNext(); } @@ -72,7 +72,7 @@ function setupChannel(url, flags) let uri = "http://localhost:" + httpserver.identity.primaryPort + url; var chan = NetUtil.newChannel({ - uri: uri, + uri, loadUsingSystemPrincipal: true, contentPolicyType: Ci.nsIContentPolicy.TYPE_MEDIA }); diff --git a/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js b/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js index ce30a5c1ba18..78cb68c038a3 100644 --- a/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js +++ b/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js @@ -46,12 +46,12 @@ const tests = [ // A basic listener that reads checks the if we sniffed properly. var listener = { - onStartRequest: function(request, context) { + onStartRequest(request, context) { do_print("Sniffing " + tests[testRan].path); do_check_eq(request.QueryInterface(Ci.nsIChannel).contentType, tests[testRan].expected); }, - onDataAvailable: function(request, context, stream, offset, count) { + onDataAvailable(request, context, stream, offset, count) { try { var bis = Components.classes["@mozilla.org/binaryinputstream;1"] .createInstance(Components.interfaces.nsIBinaryInputStream); @@ -62,7 +62,7 @@ var listener = { } }, - onStopRequest: function(request, context, status) { + onStopRequest(request, context, status) { testRan++; runNext(); } diff --git a/toolkit/components/microformats/microformat-shiv.js b/toolkit/components/microformats/microformat-shiv.js index f12d5208ad48..47651bbb88f8 100644 --- a/toolkit/components/microformats/microformat-shiv.js +++ b/toolkit/components/microformats/microformat-shiv.js @@ -43,7 +43,7 @@ var Microformats; // jshint ignore:line modules.Parser.prototype = { - init: function() { + init() { this.rootNode = null; this.document = null; this.options = { @@ -67,7 +67,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Object} */ - get: function(options) { + get(options) { var out = this.formatEmpty(), data = [], rels; @@ -126,7 +126,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Object} */ - getParent: function(node, options) { + getParent(node, options) { this.init(); options = (options) ? options : {}; @@ -144,7 +144,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} rootNode * @return {Int} */ - count: function( options ) { + count( options ) { var out = {}, items, classItems, @@ -194,7 +194,7 @@ var Microformats; // jshint ignore:line * @param {Objecte} options * @return {Boolean} */ - isMicroformat: function( node, options ) { + isMicroformat( node, options ) { var classes, i; @@ -227,7 +227,7 @@ var Microformats; // jshint ignore:line * @param {Objecte} options * @return {Boolean} */ - hasMicroformats: function( node, options ) { + hasMicroformats( node, options ) { var items, i; @@ -258,7 +258,7 @@ var Microformats; // jshint ignore:line * * @param {Array} maps */ - add: function( maps ) { + add( maps ) { maps.forEach(function(map) { if (map && map.root && map.name && map.properties) { modules.maps[map.name] = JSON.parse(JSON.stringify(map)); @@ -275,7 +275,7 @@ var Microformats; // jshint ignore:line * @param {Int} recursive * @return {Object} */ - getParentTreeWalk: function(node, options, recursive) { + getParentTreeWalk(node, options, recursive) { options = (options) ? options : {}; // recursive calls @@ -303,7 +303,7 @@ var Microformats; // jshint ignore:line * * @param {Object} options */ - getDOMContext: function( options ) { + getDOMContext( options ) { var nodes = modules.domUtils.getDOMContext( options ); this.rootNode = nodes.rootNode; this.document = nodes.document; @@ -316,7 +316,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {Boolean} */ - prepareDOM: function( options ) { + prepareDOM( options ) { var baseTag, href; @@ -370,7 +370,7 @@ var Microformats; // jshint ignore:line * * @return {Object} */ - formatError: function() { + formatError() { var out = this.formatEmpty(); out.errors = this.errors; return out; @@ -382,7 +382,7 @@ var Microformats; // jshint ignore:line * * @return {Object} */ - formatEmpty: function() { + formatEmpty() { return { 'items': [], 'rels': {}, @@ -392,7 +392,7 @@ var Microformats; // jshint ignore:line // find microformats of a given type and return node structures - findFilterNodes: function(rootNode, filters) { + findFilterNodes(rootNode, filters) { if (modules.utils.isString(filters)) { filters = [filters]; } @@ -438,7 +438,7 @@ var Microformats; // jshint ignore:line * @param {Int} count * @param {Object} */ - appendCount: function(name, count, out) { + appendCount(name, count, out) { if (out[name]) { out[name] = out[name] + count; } else { @@ -454,7 +454,7 @@ var Microformats; // jshint ignore:line * @param {Array} filters * @return {Boolean} */ - shouldInclude: function(uf, filters) { + shouldInclude(uf, filters) { var i; if (modules.utils.isArray(filters) && filters.length > 0) { @@ -477,7 +477,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} includeRoot * @return {Array} */ - findRootNodes: function(rootNode, includeRoot) { + findRootNodes(rootNode, includeRoot) { var arr = null, out = [], classList = [], @@ -538,7 +538,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - walkRoot: function(node) { + walkRoot(node) { var context = this, children = [], child, @@ -577,7 +577,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - walkTree: function(node) { + walkTree(node) { var classes, out = [], obj, @@ -612,7 +612,7 @@ var Microformats; // jshint ignore:line * @param {Int} rootID * @param {Object} parentClasses */ - walkChildren: function(node, out, ufName, rootID, parentClasses) { + walkChildren(node, out, ufName, rootID, parentClasses) { var context = this, children = [], rootItem, @@ -777,7 +777,7 @@ var Microformats; // jshint ignore:line * @param {Object} uf * @return {String || Object} */ - getValue: function(node, className, uf) { + getValue(node, className, uf) { var value = ''; if (modules.utils.startWith(className, 'p-')) { @@ -806,7 +806,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getPValue: function(node, valueParse) { + getPValue(node, valueParse) { var out = ''; if (valueParse) { out = this.getValueClass(node, 'p'); @@ -846,7 +846,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Object} */ - getEValue: function(node) { + getEValue(node) { var out = {value: '', html: ''}; @@ -867,7 +867,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getUValue: function(node, valueParse) { + getUValue(node, valueParse) { var out = ''; if (valueParse) { out = this.getValueClass(node, 'u'); @@ -919,7 +919,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} valueParse * @return {String} */ - getDTValue: function(node, className, uf, valueParse) { + getDTValue(node, className, uf, valueParse) { var out = ''; if (valueParse) { @@ -974,7 +974,7 @@ var Microformats; // jshint ignore:line * @param {String} id * @param {String} propertyName */ - appendRootID: function(node, id, propertyName) { + appendRootID(node, id, propertyName) { if (this.hasRootID(node, id, propertyName) === false) { var rootids = []; if (modules.domUtils.hasAttribute(node, 'rootids')) { @@ -994,7 +994,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyName * @return {Boolean} */ - hasRootID: function(node, id, propertyName) { + hasRootID(node, id, propertyName) { var rootids = []; if (!modules.domUtils.hasAttribute(node, 'rootids')) { return false; @@ -1012,7 +1012,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyName * @return {String || null} */ - getValueClass: function(node, propertyType) { + getValueClass(node, propertyType) { var context = this, children = [], out = [], @@ -1068,7 +1068,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - getValueTitle: function(node) { + getValueTitle(node) { var out = [], items, i, @@ -1093,7 +1093,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Boolean} */ - hasHClass: function(node) { + hasHClass(node) { var classes = this.getUfClassNames(node); if (classes.root && classes.root.length > 0) { return true; @@ -1109,7 +1109,7 @@ var Microformats; // jshint ignore:line * @param {Array} ufNameArr * @return {Object} */ - getUfClassNames: function(node, ufNameArr) { + getUfClassNames(node, ufNameArr) { var context = this, out = { 'root': [], @@ -1258,7 +1258,7 @@ var Microformats; // jshint ignore:line * @param {String} name * @return {Object || null} */ - getMapping: function(name) { + getMapping(name) { var key; for (key in modules.maps) { if (modules.maps[key].root === name || key === name) { @@ -1275,7 +1275,7 @@ var Microformats; // jshint ignore:line * @param {String} name * @return {String || null} */ - getV2RootName: function(name) { + getV2RootName(name) { var key; for (key in modules.maps) { if (modules.maps[key].root === name) { @@ -1293,7 +1293,7 @@ var Microformats; // jshint ignore:line * @param {String} propertyVersion * @return {Boolean} */ - isAllowedPropertyVersion: function(typeVersion, propertyVersion) { + isAllowedPropertyVersion(typeVersion, propertyVersion) { if (this.options.overlappingVersions === true) { return true; } @@ -1308,7 +1308,7 @@ var Microformats; // jshint ignore:line * @param {String} value * @return {Object} */ - createUfObject: function(names, typeVersion, value) { + createUfObject(names, typeVersion, value) { var out = {}; // is more than just whitespace @@ -1337,7 +1337,7 @@ var Microformats; // jshint ignore:line * * @param {Object} microformat */ - cleanUfObject: function( microformat ) { + cleanUfObject( microformat ) { delete microformat.times; delete microformat.dates; delete microformat.typeVersion; @@ -1353,7 +1353,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - removePropPrefix: function(text) { + removePropPrefix(text) { var i; i = this.propertyPrefixes.length; @@ -1374,7 +1374,7 @@ var Microformats; // jshint ignore:line * @param {String} attrName * @param {String} baseUrl */ - expandURLs: function(node, attrName, baseUrl) { + expandURLs(node, attrName, baseUrl) { var i, nodes, attr; @@ -1403,7 +1403,7 @@ var Microformats; // jshint ignore:line * * @param {Object} options */ - mergeOptions: function(options) { + mergeOptions(options) { var key; for (key in options) { if (options.hasOwnProperty(key)) { @@ -1418,7 +1418,7 @@ var Microformats; // jshint ignore:line * * @param {DOM Node} rootNode */ - removeRootIds: function(rootNode) { + removeRootIds(rootNode) { var arr, i; @@ -1435,7 +1435,7 @@ var Microformats; // jshint ignore:line * * @param {DOM Node} rootNode */ - clearUpDom: function(rootNode) { + clearUpDom(rootNode) { if (this.removeIncludes) { this.removeIncludes(rootNode); } @@ -1751,15 +1751,15 @@ var Microformats; // jshint ignore:line if (uf.value && !uf.altValue) { // first p-name of the h-* child if (modules.utils.startWith(parentPropertyName, 'p-') && propertyName === 'p-name') { - uf.altValue = {name: propertyName, value: value}; + uf.altValue = {name: propertyName, value}; } // if it's an e-* property element if (modules.utils.startWith(parentPropertyName, 'e-') && modules.utils.startWith(propertyName, 'e-')) { - uf.altValue = {name: propertyName, value: value}; + uf.altValue = {name: propertyName, value}; } // if it's an u-* property element if (modules.utils.startWith(parentPropertyName, 'u-') && propertyName === 'u-url') { - uf.altValue = {name: propertyName, value: value}; + uf.altValue = {name: propertyName, value}; } } return uf; @@ -2205,7 +2205,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isString: function( obj ) { + isString( obj ) { return typeof( obj ) === 'string'; }, @@ -2215,7 +2215,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isNumber: function( obj ) { + isNumber( obj ) { return !isNaN(parseFloat( obj )) && isFinite( obj ); }, @@ -2226,7 +2226,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isArray: function( obj ) { + isArray( obj ) { return obj && !( obj.propertyIsEnumerable( 'length' ) ) && typeof obj === 'object' && typeof obj.length === 'number'; }, @@ -2237,7 +2237,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - isFunction: function(obj) { + isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }, @@ -2249,7 +2249,7 @@ var Microformats; // jshint ignore:line * @param {String} test * @return {Boolean} */ - startWith: function( text, test ) { + startWith( text, test ) { return (text.indexOf(test) === 0); }, @@ -2260,7 +2260,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - trim: function( text ) { + trim( text ) { if (text && this.isString(text)) { return (text.trim()) ? text.trim() : text.replace(/^\s+|\s+$/g, ''); } @@ -2276,7 +2276,7 @@ var Microformats; // jshint ignore:line * @param {String} character * @return {String} */ - replaceCharAt: function( text, index, character ) { + replaceCharAt( text, index, character ) { if (text && text.length > index) { return text.substr(0, index) + character + text.substr(index + character.length); } @@ -2290,7 +2290,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - trimWhitespace: function( text ) { + trimWhitespace( text ) { if (text && text.length) { var i = text.length, x = 0; @@ -2325,7 +2325,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isOnlyWhiteSpace: function( text ) { + isOnlyWhiteSpace( text ) { return !(/[^\t\n\r ]/.test( text )); }, @@ -2336,7 +2336,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Sring} */ - collapseWhiteSpace: function( text ) { + collapseWhiteSpace( text ) { return text.replace(/[\t\n\r ]+/g, ' '); }, @@ -2347,7 +2347,7 @@ var Microformats; // jshint ignore:line * @param {Object} obj * @return {Boolean} */ - hasProperties: function( obj ) { + hasProperties( obj ) { var key; for (key in obj) { if ( obj.hasOwnProperty( key ) ) { @@ -2365,7 +2365,7 @@ var Microformats; // jshint ignore:line * @param {Boolean} reverse * @return {Int} */ - sortObjects: function(property, reverse) { + sortObjects(property, reverse) { reverse = (reverse) ? -1 : 1; return function(a, b) { a = a[property]; @@ -2395,7 +2395,7 @@ var Microformats; // jshint ignore:line * * @return {Object || undefined} */ - getDOMParser: function() { + getDOMParser() { if (typeof DOMParser === "undefined") { try { return Components.classes["@mozilla.org/xmlextras/domparser;1"] @@ -2415,7 +2415,7 @@ var Microformats; // jshint ignore:line * @param {Object} options * @return {DOM Node} node */ - getDOMContext: function( options ) { + getDOMContext( options ) { // if a node is passed if (options.node) { @@ -2465,7 +2465,7 @@ var Microformats; // jshint ignore:line * @param {Dom Document} * @return {DOM Node} node */ - getTopMostNode: function( node ) { + getTopMostNode( node ) { // var doc = this.ownerDocument(node); // if(doc && doc.nodeType && doc.nodeType === 9 && doc.documentElement){ // return doc.documentElement; @@ -2481,7 +2481,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Dom Document} */ - ownerDocument: function(node) { + ownerDocument(node) { return node.ownerDocument; }, @@ -2492,7 +2492,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - textContent: function(node) { + textContent(node) { if (node.textContent) { return node.textContent; } else if (node.innerText) { @@ -2508,7 +2508,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - innerHTML: function(node) { + innerHTML(node) { return node.innerHTML; }, @@ -2520,7 +2520,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {Boolean} */ - hasAttribute: function(node, attributeName) { + hasAttribute(node, attributeName) { return node.hasAttribute(attributeName); }, @@ -2533,7 +2533,7 @@ var Microformats; // jshint ignore:line * @param {String} value * @return {Boolean} */ - hasAttributeValue: function(node, attributeName, value) { + hasAttributeValue(node, attributeName, value) { return (this.getAttributeList(node, attributeName).indexOf(value) > -1); }, @@ -2545,7 +2545,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {String || null} */ - getAttribute: function(node, attributeName) { + getAttribute(node, attributeName) { return node.getAttribute(attributeName); }, @@ -2557,7 +2557,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @param {String} attributeValue */ - setAttribute: function(node, attributeName, attributeValue) { + setAttribute(node, attributeName, attributeValue) { node.setAttribute(attributeName, attributeValue); }, @@ -2568,7 +2568,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @param {String} attributeName */ - removeAttribute: function(node, attributeName) { + removeAttribute(node, attributeName) { node.removeAttribute(attributeName); }, @@ -2580,7 +2580,7 @@ var Microformats; // jshint ignore:line * @param {String} id * @return {DOM Node} */ - getElementById: function(docNode, id) { + getElementById(docNode, id) { return docNode.querySelector( '#' + id ); }, @@ -2592,7 +2592,7 @@ var Microformats; // jshint ignore:line * @param {String} selector * @return {DOM Node} */ - querySelector: function(docNode, selector) { + querySelector(docNode, selector) { return docNode.querySelector( selector ); }, @@ -2604,7 +2604,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {Array} */ - getAttributeList: function(node, attributeName) { + getAttributeList(node, attributeName) { var out = [], attList; @@ -2627,7 +2627,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {NodeList} */ - getNodesByAttribute: function(node, attributeName) { + getNodesByAttribute(node, attributeName) { var selector = '[' + attributeName + ']'; return node.querySelectorAll(selector); }, @@ -2640,7 +2640,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {DOM NodeList} */ - getNodesByAttributeValue: function(rootNode, name, value) { + getNodesByAttributeValue(rootNode, name, value) { var arr = [], x = 0, i, @@ -2667,7 +2667,7 @@ var Microformats; // jshint ignore:line * @param {String} attributeName * @return {String || null} */ - getAttrValFromTagList: function(node, tagNames, attributeName) { + getAttrValFromTagList(node, tagNames, attributeName) { var i = tagNames.length; while (i--) { @@ -2689,7 +2689,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getSingleDescendant: function(node) { + getSingleDescendant(node) { return this.getDescendant( node, null, false ); }, @@ -2701,7 +2701,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getSingleDescendantOfType: function(node, tagNames) { + getSingleDescendantOfType(node, tagNames) { return this.getDescendant( node, tagNames, true ); }, @@ -2713,7 +2713,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {DOM Node || null} */ - getDescendant: function( node, tagNames, onlyOfType ) { + getDescendant( node, tagNames, onlyOfType ) { var i = node.children.length, countAll = 0, countOfType = 0, @@ -2750,7 +2750,7 @@ var Microformats; // jshint ignore:line * @param {Array} tagNames * @return {Boolean} */ - hasTagName: function(node, tagNames) { + hasTagName(node, tagNames) { var i = tagNames.length; while (i--) { if (node.tagName.toLowerCase() === tagNames[i]) { @@ -2768,7 +2768,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} childNode * @return {DOM Node} */ - appendChild: function(node, childNode) { + appendChild(node, childNode) { return node.appendChild(childNode); }, @@ -2779,7 +2779,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} childNode * @return {DOM Node || null} */ - removeChild: function(childNode) { + removeChild(childNode) { if (childNode.parentNode) { return childNode.parentNode.removeChild(childNode); } @@ -2793,7 +2793,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {DOM Node} */ - clone: function(node) { + clone(node) { var newNode = node.cloneNode(true); newNode.removeAttribute('id'); return newNode; @@ -2806,7 +2806,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - getElementText: function( node ) { + getElementText( node ) { if (node && node.data) { return node.data; } @@ -2820,7 +2820,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - getOrderedAttributes: function( node ) { + getOrderedAttributes( node ) { var nodeStr = node.outerHTML, attrs = []; @@ -2841,7 +2841,7 @@ var Microformats; // jshint ignore:line * @param String} text * @return {String} */ - decodeEntities: function( doc, text ) { + decodeEntities( doc, text ) { // return text; return doc.createTextNode( text ).nodeValue; }, @@ -2853,7 +2853,7 @@ var Microformats; // jshint ignore:line * @param {DOM Document} document * @return {DOM Document} */ - cloneDocument: function( document ) { + cloneDocument( document ) { var newNode, newDocument = null; @@ -2872,7 +2872,7 @@ var Microformats; // jshint ignore:line * @param {DOM Document} document * @return {Boolean} */ - canCloneDocument: function( document ) { + canCloneDocument( document ) { return (document && document.importNode && document.implementation && document.implementation.createHTMLDocument); }, @@ -2883,7 +2883,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Int} */ - getChildIndex: function(node) { + getChildIndex(node) { var parent = node.parentNode, i = -1, child; @@ -2902,7 +2902,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {Array} */ - getNodePath: function(node) { + getNodePath(node) { var parent = node.parentNode, path = [], index = this.getChildIndex(node); @@ -2923,7 +2923,7 @@ var Microformats; // jshint ignore:line * @param {Array} path * @return {DOM Node} */ - getNodeByPath: function(document, path) { + getNodeByPath(document, path) { var node = document.documentElement, i = 0, index; @@ -2940,7 +2940,7 @@ var Microformats; // jshint ignore:line * @param {DOM node} node * @return {Array} */ - getChildren: function( node ) { + getChildren( node ) { return node.children; }, @@ -2951,7 +2951,7 @@ var Microformats; // jshint ignore:line * @param {String} tagName * @return {DOM node} */ - createNode: function( tagName ) { + createNode( tagName ) { return this.document.createElement(tagName); }, @@ -2963,7 +2963,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {DOM node} */ - createNodeWithText: function( tagName, text ) { + createNodeWithText( tagName, text ) { var node = this.document.createElement(tagName); node.innerHTML = text; return node; @@ -2980,7 +2980,7 @@ var Microformats; // jshint ignore:line /** * creates DOM objects needed to resolve URLs */ - init: function() { + init() { // this._domParser = new DOMParser(); this._domParser = modules.domUtils.getDOMParser(); // do not use a head tag it does not work with IE9 @@ -2998,7 +2998,7 @@ var Microformats; // jshint ignore:line * @param {String} baseUrl * @return {String} */ - resolve: function(url, baseUrl) { + resolve(url, baseUrl) { // use modern URL web API where we can if (modules.utils.isString(url) && modules.utils.isString(baseUrl) && url.indexOf('://') === -1) { // this try catch is required as IE has an URL object but no constuctor support @@ -3062,7 +3062,7 @@ var Microformats; // jshint ignore:line * clear all states * */ - clear: function() { + clear() { this.clearDate(); this.clearTime(); this.clearTimeZone(); @@ -3074,7 +3074,7 @@ var Microformats; // jshint ignore:line * clear date states * */ - clearDate: function() { + clearDate() { this.dY = -1; this.dM = -1; this.dD = -1; @@ -3086,7 +3086,7 @@ var Microformats; // jshint ignore:line * clear time states * */ - clearTime: function() { + clearTime() { this.tH = -1; this.tM = -1; this.tS = -1; @@ -3098,7 +3098,7 @@ var Microformats; // jshint ignore:line * clear timezone states * */ - clearTimeZone: function() { + clearTimeZone() { this.tzH = -1; this.tzM = -1; this.tzPN = '+'; @@ -3110,7 +3110,7 @@ var Microformats; // jshint ignore:line * resets the auto profile state * */ - setAutoProfileState: function() { + setAutoProfileState() { this.autoProfile = { sep: 'T', dsep: '-', @@ -3128,7 +3128,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parse: function( dateString, format ) { + parse( dateString, format ) { this.clear(); var parts = [], @@ -3218,7 +3218,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseDate: function( dateString, format ) { + parseDate( dateString, format ) { this.clearDate(); var parts = []; @@ -3263,7 +3263,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseTime: function( timeString, format ) { + parseTime( timeString, format ) { this.clearTime(); var parts = []; @@ -3297,7 +3297,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - parseTimeZone: function( timeString, format ) { + parseTimeZone( timeString, format ) { this.clearTimeZone(); var parts = []; @@ -3337,7 +3337,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - toString: function( format ) { + toString( format ) { var output = ''; if (format) { @@ -3374,7 +3374,7 @@ var Microformats; // jshint ignore:line * @param {String} format * @return {String} */ - toTimeString: function( format ) { + toTimeString( format ) { var out = ''; if (format) { @@ -3417,7 +3417,7 @@ var Microformats; // jshint ignore:line * set the current profile to W3C Note, RFC 3339, HTML5, or auto profile * */ - setFormatSep: function() { + setFormatSep() { switch ( this.format.toLowerCase() ) { case 'rfc3339': this.sep = 'T'; @@ -3456,7 +3456,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasFullDate: function() { + hasFullDate() { return (this.dY !== -1 && this.dM !== -1 && this.dD !== -1); }, @@ -3466,7 +3466,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasDate: function() { + hasDate() { return (this.dY !== -1); }, @@ -3476,7 +3476,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasTime: function() { + hasTime() { return (this.tH !== -1); }, @@ -3485,7 +3485,7 @@ var Microformats; // jshint ignore:line * * @return {Boolean} */ - hasTimeZone: function() { + hasTimeZone() { return (this.tzH !== -1); } @@ -3503,7 +3503,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - hasAM: function( text ) { + hasAM( text ) { text = text.toLowerCase(); return (text.indexOf('am') > -1 || text.indexOf('a.m.') > -1); }, @@ -3515,7 +3515,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - hasPM: function( text ) { + hasPM( text ) { text = text.toLowerCase(); return (text.indexOf('pm') > -1 || text.indexOf('p.m.') > -1); }, @@ -3527,7 +3527,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - removeAMPM: function( text ) { + removeAMPM( text ) { return text.replace('pm', '').replace('p.m.', '').replace('am', '').replace('a.m.', ''); }, @@ -3538,7 +3538,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isDuration: function( text ) { + isDuration( text ) { if (modules.utils.isString( text )) { text = text.toLowerCase(); if (modules.utils.startWith(text, 'p') ) { @@ -3556,7 +3556,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Boolean} */ - isTime: function( text ) { + isTime( text ) { if (modules.utils.isString(text)) { text = text.toLowerCase(); text = modules.utils.trim( text ); @@ -3592,7 +3592,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - parseAmPmTime: function( text ) { + parseAmPmTime( text ) { var out = text, times = []; @@ -3643,7 +3643,7 @@ var Microformats; // jshint ignore:line * @param {String} format ( Modules.ISODate profile format ) * @return {Object} Modules.ISODate */ - dateTimeUnion: function(date, time, format) { + dateTimeUnion(date, time, format) { var isodate = new modules.ISODate(date, format), isotime = new modules.ISODate(); @@ -3670,7 +3670,7 @@ var Microformats; // jshint ignore:line * @param {String} format ( Modules.ISODate profile format ) * @return {Object} Modules.ISODate */ - concatFragments: function(arr, format) { + concatFragments(arr, format) { var out = new modules.ISODate(), i = 0, value = ''; @@ -3721,7 +3721,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {Array} Modules.ISODate */ - splitTimeAndZone: function( text ) { + splitTimeAndZone( text ) { var out = [text], chars = ['-', '+', 'z', 'Z'], i = chars.length; @@ -3762,7 +3762,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - parse: function(doc, node, textFormat) { + parse(doc, node, textFormat) { var out; this.textFormat = (textFormat) ? textFormat : this.textFormat; if (this.textFormat === 'normalised') { @@ -3784,7 +3784,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - parseText: function( doc, text, textFormat ) { + parseText( doc, text, textFormat ) { var node = modules.domUtils.createNodeWithText( 'div', text ); return this.parse( doc, node, textFormat ); }, @@ -3797,7 +3797,7 @@ var Microformats; // jshint ignore:line * @param {String} textFormat * @return {String} */ - formatText: function( doc, text, textFormat ) { + formatText( doc, text, textFormat ) { this.textFormat = (textFormat) ? textFormat : this.textFormat; if (text) { var out = '', @@ -3821,7 +3821,7 @@ var Microformats; // jshint ignore:line * @param {String} text * @return {String} */ - normalise: function( doc, text ) { + normalise( doc, text ) { text = text.replace( / /g, ' ') ; // exchanges html entity for space into space char text = modules.utils.collapseWhiteSpace( text ); // removes linefeeds, tabs and addtional spaces text = modules.domUtils.decodeEntities( doc, text ); // decode HTML entities @@ -3836,7 +3836,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - walkTreeForText: function( node ) { + walkTreeForText( node ) { var out = '', j = 0; @@ -3882,7 +3882,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - parse: function( node ) { + parse( node ) { var out = '', j = 0; @@ -3907,7 +3907,7 @@ var Microformats; // jshint ignore:line * @param {DOM Node} node * @return {String} */ - walkTreeForHtml: function( node ) { + walkTreeForHtml( node ) { var out = '', j = 0; diff --git a/toolkit/components/narrate/NarrateControls.jsm b/toolkit/components/narrate/NarrateControls.jsm index bfee9dd96ff5..3ad889d82cc2 100644 --- a/toolkit/components/narrate/NarrateControls.jsm +++ b/toolkit/components/narrate/NarrateControls.jsm @@ -137,7 +137,7 @@ function NarrateControls(mm, win, languagePromise) { } NarrateControls.prototype = { - handleEvent: function(evt) { + handleEvent(evt) { switch (evt.type) { case "change": if (evt.target.id == "narrate-rate-input") { @@ -163,7 +163,7 @@ NarrateControls.prototype = { /** * Returns true if synth voices are available. */ - _setupVoices: function() { + _setupVoices() { return this._languagePromise.then(language => { this.voiceSelect.clear(); let win = this._win; @@ -211,7 +211,7 @@ NarrateControls.prototype = { }); }, - _getVoicePref: function() { + _getVoicePref() { let voicePref = Services.prefs.getCharPref("narrate.voice"); try { return JSON.parse(voicePref); @@ -220,12 +220,12 @@ NarrateControls.prototype = { } }, - _onRateInput: function(evt) { + _onRateInput(evt) { AsyncPrefs.set("narrate.rate", parseInt(evt.target.value, 10)); this.narrator.setRate(this._convertRate(evt.target.value)); }, - _onVoiceChange: function() { + _onVoiceChange() { let voice = this.voice; this.narrator.setVoice(voice); this._languagePromise.then(language => { @@ -237,7 +237,7 @@ NarrateControls.prototype = { }); }, - _onButtonClick: function(evt) { + _onButtonClick(evt) { switch (evt.target.id) { case "narrate-skip-previous": this.narrator.skipPrevious(); @@ -262,7 +262,7 @@ NarrateControls.prototype = { } }, - _updateSpeechControls: function(speaking) { + _updateSpeechControls(speaking) { let dropdown = this._doc.getElementById("narrate-dropdown"); dropdown.classList.toggle("keep-open", speaking); dropdown.classList.toggle("speaking", speaking); @@ -281,7 +281,7 @@ NarrateControls.prototype = { } }, - _createVoiceLabel: function(voice) { + _createVoiceLabel(voice) { // This is a highly imperfect method of making human-readable labels // for system voices. Because each platform has a different naming scheme // for voices, we use a different method for each platform. @@ -304,7 +304,7 @@ NarrateControls.prototype = { } }, - _getLanguageName: function(lang) { + _getLanguageName(lang) { if (!this._langStrings) { this._langStrings = Services.strings.createBundle( "chrome://global/locale/languageNames.properties "); @@ -318,7 +318,7 @@ NarrateControls.prototype = { } }, - _convertRate: function(rate) { + _convertRate(rate) { // We need to convert a relative percentage value to a fraction rate value. // eg. -100 is half the speed, 100 is twice the speed in percentage, // 0.5 is half the speed and 2 is twice the speed in fractions. diff --git a/toolkit/components/narrate/Narrator.jsm b/toolkit/components/narrate/Narrator.jsm index 4af9c7eed604..03bec2500cf0 100644 --- a/toolkit/components/narrate/Narrator.jsm +++ b/toolkit/components/narrate/Narrator.jsm @@ -53,7 +53,7 @@ Narrator.prototype = { // For example, paragraphs. But nested anchors and other elements // are not interesting since their text already appears in their // parent's textContent. - acceptNode: function(node) { + acceptNode(node) { if (this._matches.has(node.parentNode)) { // Reject sub-trees of accepted nodes. return nf.FILTER_REJECT; @@ -106,7 +106,7 @@ Narrator.prototype = { this._win.speechSynthesis.pending; }, - _getVoice: function(voiceURI) { + _getVoice(voiceURI) { if (!this._voiceMap || !this._voiceMap.has(voiceURI)) { this._voiceMap = new Map( this._win.speechSynthesis.getVoices().map(v => [v.voiceURI, v])); @@ -115,7 +115,7 @@ Narrator.prototype = { return this._voiceMap.get(voiceURI); }, - _isParagraphInView: function(paragraph) { + _isParagraphInView(paragraph) { if (!paragraph) { return false; } @@ -124,13 +124,13 @@ Narrator.prototype = { return bb.top >= 0 && bb.top < this._win.innerHeight; }, - _sendTestEvent: function(eventType, detail) { + _sendTestEvent(eventType, detail) { let win = this._win; win.dispatchEvent(new win.CustomEvent(eventType, { detail: Cu.cloneInto(detail, win.document) })); }, - _speakInner: function() { + _speakInner() { this._win.speechSynthesis.cancel(); let tw = this._treeWalker; let paragraph = tw.currentNode; @@ -235,7 +235,7 @@ Narrator.prototype = { }); }, - start: function(speechOptions) { + start(speechOptions) { this._speechOptions = { rate: speechOptions.rate, voice: this._getVoice(speechOptions.voice) @@ -264,32 +264,32 @@ Narrator.prototype = { }); }, - stop: function() { + stop() { this._stopped = true; this._win.speechSynthesis.cancel(); }, - skipNext: function() { + skipNext() { this._win.speechSynthesis.cancel(); }, - skipPrevious: function() { + skipPrevious() { this._goBackParagraphs(this._timeIntoParagraph < PREV_THRESHOLD ? 2 : 1); }, - setRate: function(rate) { + setRate(rate) { this._speechOptions.rate = rate; /* repeat current paragraph */ this._goBackParagraphs(1); }, - setVoice: function(voice) { + setVoice(voice) { this._speechOptions.voice = this._getVoice(voice); /* repeat current paragraph */ this._goBackParagraphs(1); }, - _goBackParagraphs: function(count) { + _goBackParagraphs(count) { let tw = this._treeWalker; for (let i = 0; i < count; i++) { if (!tw.previousNode()) { @@ -316,7 +316,7 @@ Highlighter.prototype = { * @param {Number} startOffset the start offset * @param {Number} length the length in characters of the range */ - highlight: function(startOffset, length) { + highlight(startOffset, length) { let containerRect = this.container.getBoundingClientRect(); let range = this._getRange(startOffset, startOffset + length); let rangeRects = range.getClientRects(); @@ -362,7 +362,7 @@ Highlighter.prototype = { /** * Releases reference to container and removes all highlight nodes. */ - remove: function() { + remove() { for (let node of this._nodes) { node.remove(); } @@ -376,7 +376,7 @@ Highlighter.prototype = { * * @param {Number} count number of nodes needed */ - _getFreshHighlightNodes: function(count) { + _getFreshHighlightNodes(count) { let doc = this.container.ownerDocument; let nodes = Array.from(this._nodes); @@ -403,7 +403,7 @@ Highlighter.prototype = { * @param {Number} startOffset the start offset * @param {Number} endOffset the end offset */ - _getRange: function(startOffset, endOffset) { + _getRange(startOffset, endOffset) { let doc = this.container.ownerDocument; let i = 0; let treeWalker = doc.createTreeWalker( diff --git a/toolkit/components/narrate/VoiceSelect.jsm b/toolkit/components/narrate/VoiceSelect.jsm index b283a06b39f4..4d3ff82b9e24 100644 --- a/toolkit/components/narrate/VoiceSelect.jsm +++ b/toolkit/components/narrate/VoiceSelect.jsm @@ -37,7 +37,7 @@ function VoiceSelect(win, label) { } VoiceSelect.prototype = { - add: function(label, value) { + add(label, value) { let option = this._doc.createElement("button"); option.dataset.value = value; option.classList.add("option"); @@ -48,7 +48,7 @@ VoiceSelect.prototype = { return option; }, - addOptions: function(options) { + addOptions(options) { let selected = null; for (let option of options) { if (option.selected) { @@ -61,11 +61,11 @@ VoiceSelect.prototype = { this._select(selected || this.options[0], true); }, - clear: function() { + clear() { this.listbox.innerHTML = ""; }, - toggleList: function(force, focus = true) { + toggleList(force, focus = true) { if (this.element.classList.toggle("open", force)) { if (focus) { (this.selected || this.options[0]).focus(); @@ -84,7 +84,7 @@ VoiceSelect.prototype = { } }, - handleEvent: function(evt) { + handleEvent(evt) { let target = evt.target; switch (evt.type) { @@ -131,7 +131,7 @@ VoiceSelect.prototype = { } }, - _getPagedOption: function(option, up) { + _getPagedOption(option, up) { let height = elem => elem.getBoundingClientRect().height; let listboxHeight = height(this.listbox); @@ -148,7 +148,7 @@ VoiceSelect.prototype = { return next; }, - _keyPressedButton: function(evt) { + _keyPressedButton(evt) { if (evt.altKey && (evt.key === "ArrowUp" || evt.key === "ArrowUp")) { this.toggleList(true); return; @@ -178,7 +178,7 @@ VoiceSelect.prototype = { } }, - _keyPressedInBox: function(evt) { + _keyPressedInBox(evt) { let toFocus; let cur = this._doc.activeElement; @@ -212,7 +212,7 @@ VoiceSelect.prototype = { } }, - _select: function(option, suppressEvent = false) { + _select(option, suppressEvent = false) { let oldSelected = this.selected; if (oldSelected) { oldSelected.removeAttribute("aria-selected"); @@ -233,7 +233,7 @@ VoiceSelect.prototype = { } }, - _updateDropdownHeight: function(now) { + _updateDropdownHeight(now) { let updateInner = () => { let winHeight = this._win.innerHeight; let listbox = this.listbox; @@ -252,7 +252,7 @@ VoiceSelect.prototype = { } }, - _getOptionFromValue: function(value) { + _getOptionFromValue(value) { return Array.from(this.options).find(o => o.dataset.value === value); }, diff --git a/toolkit/components/narrate/test/NarrateTestUtils.jsm b/toolkit/components/narrate/test/NarrateTestUtils.jsm index 302e5c9928b8..227a7cf2b100 100644 --- a/toolkit/components/narrate/test/NarrateTestUtils.jsm +++ b/toolkit/components/narrate/test/NarrateTestUtils.jsm @@ -24,7 +24,7 @@ this.NarrateTestUtils = { BACK: "#narrate-skip-previous", FORWARD: "#narrate-skip-next", - isVisible: function(element) { + isVisible(element) { let style = element.ownerDocument.defaultView.getComputedStyle(element, ""); if (style.display == "none") { return false; @@ -42,7 +42,7 @@ this.NarrateTestUtils = { return true; }, - isStoppedState: function(window, ok) { + isStoppedState(window, ok) { let $ = window.document.querySelector.bind(window.document); ok($(this.BACK).disabled, "back button is disabled"); ok($(this.FORWARD).disabled, "forward button is disabled"); @@ -52,7 +52,7 @@ this.NarrateTestUtils = { ok($(this.START).title == "Start", "Button tooltip is correct"); }, - isStartedState: function(window, ok) { + isStartedState(window, ok) { let $ = window.document.querySelector.bind(window.document); ok(!$(this.BACK).disabled, "back button is enabled"); ok(!$(this.FORWARD).disabled, "forward button is enabled"); @@ -62,7 +62,7 @@ this.NarrateTestUtils = { ok($(this.STOP).title == "Stop", "Button tooltip is correct"); }, - selectVoice: function(window, voiceUri) { + selectVoice(window, voiceUri) { if (!this.isVisible(window.document.querySelector(this.VOICE_OPTIONS))) { window.document.querySelector(this.VOICE_SELECT).click(); } @@ -76,11 +76,11 @@ this.NarrateTestUtils = { return voiceOption.classList.contains("selected"); }, - getEventUtils: function(window) { + getEventUtils(window) { let eventUtils = { "_EU_Ci": Components.interfaces, "_EU_Cc": Components.classes, - window: window, + window, parent: window, navigator: window.navigator, KeyboardEvent: window.KeyboardEvent, @@ -91,7 +91,7 @@ this.NarrateTestUtils = { return eventUtils; }, - getReaderReadyPromise: function(window) { + getReaderReadyPromise(window) { return new Promise(resolve => { function observeReady(subject, topic) { if (subject == window) { @@ -108,13 +108,13 @@ this.NarrateTestUtils = { }); }, - waitForNarrateToggle: function(window) { + waitForNarrateToggle(window) { let toggle = window.document.querySelector(this.TOGGLE); return ContentTaskUtils.waitForCondition( () => !toggle.hidden, ""); }, - waitForPrefChange: function(pref) { + waitForPrefChange(pref) { return new Promise(resolve => { function observeChange() { Services.prefs.removeObserver(pref, observeChange); @@ -125,18 +125,18 @@ this.NarrateTestUtils = { }); }, - sendBoundaryEvent: function(window, name, charIndex, charLength) { + sendBoundaryEvent(window, name, charIndex, charLength) { let detail = { type: "boundary", args: { name, charIndex, charLength } }; window.dispatchEvent(new window.CustomEvent("testsynthevent", - { detail: detail })); + { detail })); }, - isWordHighlightGone: function(window, ok) { + isWordHighlightGone(window, ok) { let $ = window.document.querySelector.bind(window.document); ok(!$(".narrate-word-highlight"), "No more word highlights exist"); }, - getWordHighlights: function(window) { + getWordHighlights(window) { let $$ = window.document.querySelectorAll.bind(window.document); let nodes = Array.from($$(".narrate-word-highlight")); return nodes.map(node => { diff --git a/toolkit/components/passwordmgr/LoginHelper.jsm b/toolkit/components/passwordmgr/LoginHelper.jsm index f63832762138..be0fc32aac73 100644 --- a/toolkit/components/passwordmgr/LoginHelper.jsm +++ b/toolkit/components/passwordmgr/LoginHelper.jsm @@ -517,7 +517,7 @@ this.LoginHelper = { } else { window.openDialog("chrome://passwordmgr/content/passwordManager.xul", "Toolkit:PasswordManager", "", - {filterString : filterString}); + {filterString}); } }, diff --git a/toolkit/components/passwordmgr/LoginImport.jsm b/toolkit/components/passwordmgr/LoginImport.jsm index 8f4ce246b087..9d620dd43ade 100644 --- a/toolkit/components/passwordmgr/LoginImport.jsm +++ b/toolkit/components/passwordmgr/LoginImport.jsm @@ -137,19 +137,19 @@ this.LoginImport.prototype = { this.store.data.logins.push({ id: this.store.data.nextId++, - hostname: hostname, - httpRealm: httpRealm, - formSubmitURL: formSubmitURL, - usernameField: usernameField, - passwordField: passwordField, - encryptedUsername: encryptedUsername, - encryptedPassword: encryptedPassword, - guid: guid, - encType: encType, - timeCreated: timeCreated, - timeLastUsed: timeLastUsed, - timePasswordChanged: timePasswordChanged, - timesUsed: timesUsed, + hostname, + httpRealm, + formSubmitURL, + usernameField, + passwordField, + encryptedUsername, + encryptedPassword, + guid, + encType, + timeCreated, + timeLastUsed, + timePasswordChanged, + timesUsed, }); } catch (ex) { Cu.reportError("Error importing login: " + ex); diff --git a/toolkit/components/passwordmgr/LoginManagerContent.jsm b/toolkit/components/passwordmgr/LoginManagerContent.jsm index c6926f2a713c..998b6c991181 100644 --- a/toolkit/components/passwordmgr/LoginManagerContent.jsm +++ b/toolkit/components/passwordmgr/LoginManagerContent.jsm @@ -235,7 +235,7 @@ var LoginManagerContent = { let loginsFound = LoginHelper.vanillaObjectsToLogins(msg.data.logins); request.promise.resolve({ form: request.form, - loginsFound: loginsFound, + loginsFound, recipes: msg.data.recipes, }); break; @@ -276,10 +276,10 @@ var LoginManagerContent = { let messageManager = messageManagerFromWindow(win); // XXX Weak?? - let requestData = { form: form }; - let messageData = { formOrigin: formOrigin, - actionOrigin: actionOrigin, - options: options }; + let requestData = { form }; + let messageData = { formOrigin, + actionOrigin, + options }; return this._sendRequest(messageManager, requestData, "RemoteLogins:findLogins", @@ -306,14 +306,14 @@ var LoginManagerContent = { null; let requestData = {}; - let messageData = { formOrigin: formOrigin, - actionOrigin: actionOrigin, + let messageData = { formOrigin, + actionOrigin, searchString: aSearchString, - previousResult: previousResult, + previousResult, rect: aRect, isSecure: InsecurePasswordUtils.isFormSecure(form), isPasswordField: aElement.type == "password", - remote: remote }; + remote }; return this._sendRequest(messageManager, requestData, "RemoteLogins:autoCompleteLogins", @@ -608,7 +608,7 @@ var LoginManagerContent = { pwFields[pwFields.length] = { index : i, - element : element + element }; } @@ -881,8 +881,8 @@ var LoginManagerContent = { let openerTopWindow = win.opener ? win.opener.top : null; messageManager.sendAsyncMessage("RemoteLogins:onFormSubmit", - { hostname: hostname, - formSubmitURL: formSubmitURL, + { hostname, + formSubmitURL, usernameField: mockUsername, newPasswordField: mockPassword, oldPasswordField: mockOldPassword }, diff --git a/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm b/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm index c5671a56905d..74a9bd8ca1a4 100644 --- a/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm +++ b/toolkit/components/passwordmgr/LoginManagerContextMenu.jsm @@ -164,10 +164,10 @@ var LoginManagerContextMenu = { */ _fillTargetField(login, inputElement, browser, documentURI) { LoginManagerParent.fillForm({ - browser: browser, + browser, loginFormOrigin: documentURI.prePath, - login: login, - inputElement: inputElement, + login, + inputElement, }).catch(Cu.reportError); }, diff --git a/toolkit/components/passwordmgr/LoginManagerParent.jsm b/toolkit/components/passwordmgr/LoginManagerParent.jsm index ec951344c971..52ce73f239eb 100644 --- a/toolkit/components/passwordmgr/LoginManagerParent.jsm +++ b/toolkit/components/passwordmgr/LoginManagerParent.jsm @@ -38,7 +38,7 @@ var LoginManagerParent = { */ _recipeManager: null, - init: function() { + init() { let mm = Cc["@mozilla.org/globalmessagemanager;1"] .getService(Ci.nsIMessageListenerManager); mm.addMessageListener("RemoteLogins:findLogins", this); @@ -57,7 +57,7 @@ var LoginManagerParent = { }); }, - receiveMessage: function(msg) { + receiveMessage(msg) { let data = msg.data; switch (msg.name) { case "RemoteLogins:findLogins": { @@ -156,7 +156,7 @@ var LoginManagerParent = { if (!showMasterPassword && !Services.logins.isLoggedIn) { try { target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId: requestId, + requestId, logins: [], recipes, }); @@ -175,14 +175,14 @@ var LoginManagerParent = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - observe: function(subject, topic, data) { + observe(subject, topic, data) { log("Got deferred sendLoginDataToChild notification:", topic); // Only run observer once. Services.obs.removeObserver(this, "passwordmgr-crypto-login"); Services.obs.removeObserver(this, "passwordmgr-crypto-loginCanceled"); if (topic == "passwordmgr-crypto-loginCanceled") { target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId: requestId, + requestId, logins: [], recipes, }); @@ -219,13 +219,13 @@ var LoginManagerParent = { // doesn't support structured cloning. var jsLogins = LoginHelper.loginsToVanillaObjects(logins); target.sendAsyncMessage("RemoteLogins:loginsFound", { - requestId: requestId, + requestId, logins: jsLogins, recipes, }); }), - doAutocompleteSearch: function({ formOrigin, actionOrigin, + doAutocompleteSearch({ formOrigin, actionOrigin, searchString, previousResult, rect, requestId, isSecure, isPasswordField, remote }, target) { @@ -283,12 +283,12 @@ var LoginManagerParent = { // doesn't support structured cloning. var jsLogins = LoginHelper.loginsToVanillaObjects(matchingLogins); target.messageManager.sendAsyncMessage("RemoteLogins:loginsAutoCompleted", { - requestId: requestId, + requestId, logins: jsLogins, }); }, - onFormSubmit: function(hostname, formSubmitURL, + onFormSubmit(hostname, formSubmitURL, usernameField, newPasswordField, oldPasswordField, openerTopWindow, target) { diff --git a/toolkit/components/passwordmgr/content/passwordManager.js b/toolkit/components/passwordmgr/content/passwordManager.js index 3dbb499cc3ab..941fe8bdf390 100644 --- a/toolkit/components/passwordmgr/content/passwordManager.js +++ b/toolkit/components/passwordmgr/content/passwordManager.js @@ -35,7 +35,7 @@ let removeAllButton; let signonsTree; let signonReloadDisplay = { - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic == "passwordmgr-storage-changed") { switch (data) { case "addLogin": diff --git a/toolkit/components/passwordmgr/crypto-SDR.js b/toolkit/components/passwordmgr/crypto-SDR.js index 82797bb0d844..d88e87d91140 100644 --- a/toolkit/components/passwordmgr/crypto-SDR.js +++ b/toolkit/components/passwordmgr/crypto-SDR.js @@ -37,14 +37,14 @@ LoginManagerCrypto_SDR.prototype = { return this.__utfConverter; }, - _utfConverterReset : function() { + _utfConverterReset() { this.__utfConverter = null; }, _uiBusy : false, - init : function() { + init() { // Check to see if the internal PKCS#11 token has been initialized. // If not, set a blank password. let tokenDB = Cc["@mozilla.org/security/pk11tokendb;1"]. @@ -66,7 +66,7 @@ LoginManagerCrypto_SDR.prototype = { * Returns the encrypted string, or throws an exception if there was a * problem. */ - encrypt : function(plainText) { + encrypt(plainText) { let cipherText = null; let wasLoggedIn = this.isLoggedIn; @@ -107,7 +107,7 @@ LoginManagerCrypto_SDR.prototype = { * Returns the decrypted string, or throws an exception if there was a * problem. */ - decrypt : function(cipherText) { + decrypt(cipherText) { let plainText = null; let wasLoggedIn = this.isLoggedIn; @@ -178,7 +178,7 @@ LoginManagerCrypto_SDR.prototype = { /* * _notifyObservers */ - _notifyObservers : function(topic) { + _notifyObservers(topic) { this.log("Prompted for a master password, notifying for " + topic); Services.obs.notifyObservers(null, topic, null); }, diff --git a/toolkit/components/passwordmgr/nsLoginInfo.js b/toolkit/components/passwordmgr/nsLoginInfo.js index 3baed81145ce..79ed276ce1e4 100644 --- a/toolkit/components/passwordmgr/nsLoginInfo.js +++ b/toolkit/components/passwordmgr/nsLoginInfo.js @@ -29,7 +29,7 @@ nsLoginInfo.prototype = { usernameField : null, passwordField : null, - init : function(aHostname, aFormSubmitURL, aHttpRealm, + init(aHostname, aFormSubmitURL, aHttpRealm, aUsername, aPassword, aUsernameField, aPasswordField) { this.hostname = aHostname; @@ -47,7 +47,7 @@ nsLoginInfo.prototype = { }); }, - equals : function(aLogin) { + equals(aLogin) { if (this.hostname != aLogin.hostname || this.formSubmitURL != aLogin.formSubmitURL || this.httpRealm != aLogin.httpRealm || @@ -60,7 +60,7 @@ nsLoginInfo.prototype = { return true; }, - clone : function() { + clone() { let clone = Cc["@mozilla.org/login-manager/loginInfo;1"]. createInstance(Ci.nsILoginInfo); clone.init(this.hostname, this.formSubmitURL, this.httpRealm, diff --git a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js index 54c6f53d8c7d..971ff0afbef4 100644 --- a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js +++ b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js @@ -46,7 +46,7 @@ LoginManagerPromptFactory.prototype = { _asyncPrompts : {}, _asyncPromptInProgress : false, - observe : function(subject, topic, data) { + observe(subject, topic, data) { this.log("Observed: " + topic); if (topic == "quit-application-granted") { this._cancelPendingPrompts(); @@ -60,13 +60,13 @@ LoginManagerPromptFactory.prototype = { } }, - getPrompt : function(aWindow, aIID) { + getPrompt(aWindow, aIID) { var prompt = new LoginManagerPrompter().QueryInterface(aIID); prompt.init(aWindow, this); return prompt; }, - _doAsyncPrompt : function() { + _doAsyncPrompt() { if (this._asyncPromptInProgress) { this.log("_doAsyncPrompt bypassed, already in progress"); return; @@ -115,7 +115,7 @@ LoginManagerPromptFactory.prototype = { var runnable = { cancel: false, - run : function() { + run() { var ok = false; if (!this.cancel) { try { @@ -185,7 +185,7 @@ LoginManagerPromptFactory.prototype = { }, - _cancelPendingPrompts : function() { + _cancelPendingPrompts() { this.log("Canceling all pending prompts..."); var asyncPrompts = this._asyncPrompts; this.__proto__._asyncPrompts = {}; @@ -321,7 +321,7 @@ LoginManagerPrompter.prototype = { * Wrapper around the prompt service prompt. Saving random fields here * doesn't really make sense and therefore isn't implemented. */ - prompt : function(aDialogTitle, aText, aPasswordRealm, + prompt(aDialogTitle, aText, aPasswordRealm, aSavePassword, aDefaultText, aResult) { if (aSavePassword != Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER) throw new Components.Exception("prompt only supports SAVE_PASSWORD_NEVER", @@ -342,7 +342,7 @@ LoginManagerPrompter.prototype = { * Looks up a username and password in the database. Will prompt the user * with a dialog, even if a username and password are found. */ - promptUsernameAndPassword : function(aDialogTitle, aText, aPasswordRealm, + promptUsernameAndPassword(aDialogTitle, aText, aPasswordRealm, aSavePassword, aUsername, aPassword) { this.log("===== promptUsernameAndPassword() called ====="); @@ -443,7 +443,7 @@ LoginManagerPrompter.prototype = { * with a dialog with a text field and ok/cancel buttons. If the user * allows it, then the password will be saved in the database. */ - promptPassword : function(aDialogTitle, aText, aPasswordRealm, + promptPassword(aDialogTitle, aText, aPasswordRealm, aSavePassword, aPassword) { this.log("===== promptPassword called() ====="); @@ -519,7 +519,7 @@ LoginManagerPrompter.prototype = { * arguments to let callers know the login can't be saved because we don't * know whether it's http or https. */ - _getRealmInfo : function(aRealmString) { + _getRealmInfo(aRealmString) { var httpRealm = /^.+ \(.+\)$/; if (httpRealm.test(aRealmString)) return [null, null, null]; @@ -547,7 +547,7 @@ LoginManagerPrompter.prototype = { * @param {int} aLevel * @param {nsIAuthInformation} aAuthInfo */ - promptAuth : function(aChannel, aLevel, aAuthInfo) { + promptAuth(aChannel, aLevel, aAuthInfo) { var selectedLogin = null; var checkbox = { value : false }; var checkboxLabel = null; @@ -678,7 +678,7 @@ LoginManagerPrompter.prototype = { return ok; }, - asyncPromptAuth : function(aChannel, aCallback, aContext, aLevel, aAuthInfo) { + asyncPromptAuth(aChannel, aCallback, aContext, aLevel, aAuthInfo) { var cancelable = null; try { @@ -731,7 +731,7 @@ LoginManagerPrompter.prototype = { /* ---------- nsILoginManagerPrompter prompts ---------- */ - init : function(aWindow = null, aFactory = null) { + init(aWindow = null, aFactory = null) { if (!aWindow) { // There may be no applicable window e.g. in a Sandbox or JSM. this._chromeWindow = null; @@ -759,7 +759,7 @@ LoginManagerPrompter.prototype = { this._opener = aOpener; }, - promptToSavePassword : function(aLogin) { + promptToSavePassword(aLogin) { this.log("promptToSavePassword"); var notifyObj = this._getPopupNote() || this._getNotifyBox(); if (notifyObj) @@ -771,7 +771,7 @@ LoginManagerPrompter.prototype = { /** * Displays a notification bar. */ - _showLoginNotification : function(aNotifyBox, aName, aText, aButtons) { + _showLoginNotification(aNotifyBox, aName, aText, aButtons) { var oldBar = aNotifyBox.getNotificationWithValue(aName); const priority = aNotifyBox.PRIORITY_INFO_MEDIUM; @@ -1014,7 +1014,7 @@ LoginManagerPrompter.prototype = { persistent: true, passwordNotificationType: type, hideClose: true, - eventCallback: function(topic) { + eventCallback(topic) { switch (topic) { case "showing": currentNotification = this; @@ -1072,7 +1072,7 @@ LoginManagerPrompter.prototype = { * @param aLogin * The login captured from the form. */ - _showSaveLoginNotification : function(aNotifyObj, aLogin) { + _showSaveLoginNotification(aNotifyObj, aLogin) { // Ugh. We can't use the strings from the popup window, because they // have the access key marked in the string (eg "Mo&zilla"), along // with some weird rules for handling access keys that do not occur @@ -1110,7 +1110,7 @@ LoginManagerPrompter.prototype = { label: rememberButtonText, accessKey: rememberButtonAccessKey, popup: null, - callback: function(aNotifyObj, aButton) { + callback(aNotifyObj, aButton) { pwmgr.addLogin(aLogin); } }, @@ -1120,7 +1120,7 @@ LoginManagerPrompter.prototype = { label: neverButtonText, accessKey: neverButtonAccessKey, popup: null, - callback: function(aNotifyObj, aButton) { + callback(aNotifyObj, aButton) { pwmgr.setLoginSavingEnabled(aLogin.hostname, false); } }, @@ -1130,7 +1130,7 @@ LoginManagerPrompter.prototype = { label: notNowButtonText, accessKey: notNowButtonAccessKey, popup: null, - callback: function() { /* NOP */ } + callback() { /* NOP */ } } ]; @@ -1141,7 +1141,7 @@ LoginManagerPrompter.prototype = { Services.obs.notifyObservers(aLogin, "passwordmgr-prompt-save", null); }, - _removeLoginNotifications : function() { + _removeLoginNotifications() { var popupNote = this._getPopupNote(); if (popupNote) popupNote = popupNote.getNotification("password"); @@ -1169,7 +1169,7 @@ LoginManagerPrompter.prototype = { * Called when we detect a new login in a form submission, * asks the user what to do. */ - _showSaveLoginDialog : function(aLogin) { + _showSaveLoginDialog(aLogin) { const buttonFlags = Ci.nsIPrompt.BUTTON_POS_1_DEFAULT + (Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_0) + (Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_1) + @@ -1292,7 +1292,7 @@ LoginManagerPrompter.prototype = { label: changeButtonText, accessKey: changeButtonAccessKey, popup: null, - callback: function(aNotifyObj, aButton) { + callback(aNotifyObj, aButton) { self._updateLogin(aOldLogin, aNewLogin); } }, @@ -1302,7 +1302,7 @@ LoginManagerPrompter.prototype = { label: dontChangeButtonText, accessKey: dontChangeButtonAccessKey, popup: null, - callback: function(aNotifyObj, aButton) { + callback(aNotifyObj, aButton) { // do nothing } } @@ -1361,7 +1361,7 @@ LoginManagerPrompter.prototype = { * * Note; XPCOM stupidity: |count| is just |logins.length|. */ - promptToChangePasswordWithUsernames : function(logins, count, aNewLogin) { + promptToChangePasswordWithUsernames(logins, count, aNewLogin) { this.log("promptToChangePasswordWithUsernames with count:", count); var usernames = logins.map(l => l.username); @@ -1419,7 +1419,7 @@ LoginManagerPrompter.prototype = { /** * Given a content DOM window, returns the chrome window and browser it's in. */ - _getChromeWindow: function(aWindow) { + _getChromeWindow(aWindow) { let windows = Services.wm.getEnumerator(null); while (windows.hasMoreElements()) { let win = windows.getNext(); @@ -1431,7 +1431,7 @@ LoginManagerPrompter.prototype = { return null; }, - _getNotifyWindow: function() { + _getNotifyWindow() { // Some sites pop up a temporary login window, which disappears // upon submission of credentials. We want to put the notification // bar in the opener window if this seems to be happening. @@ -1455,7 +1455,7 @@ LoginManagerPrompter.prototype = { * Returns the popup notification to this prompter, * or null if there isn't one available. */ - _getPopupNote : function() { + _getPopupNote() { let popupNote = null; try { @@ -1475,7 +1475,7 @@ LoginManagerPrompter.prototype = { * Returns the notification box to this prompter, or null if there isn't * a notification box available. */ - _getNotifyBox : function() { + _getNotifyBox() { let notifyBox = null; try { @@ -1496,7 +1496,7 @@ LoginManagerPrompter.prototype = { * is the same as some other existing login. So, pick a login with a * matching username, or return null. */ - _repickSelectedLogin : function(foundLogins, username) { + _repickSelectedLogin(foundLogins, username) { for (var i = 0; i < foundLogins.length; i++) if (foundLogins[i].username == username) return foundLogins[i]; @@ -1515,7 +1515,7 @@ LoginManagerPrompter.prototype = { * formatted if required. * */ - _getLocalizedString : function(key, formatArgs) { + _getLocalizedString(key, formatArgs) { if (formatArgs) return this._strBundle.formatStringFromName( key, formatArgs, formatArgs.length); @@ -1528,7 +1528,7 @@ LoginManagerPrompter.prototype = { * it's too long. This helps prevent an evil site from messing with the * "save password?" prompt too much. */ - _sanitizeUsername : function(username) { + _sanitizeUsername(username) { if (username.length > 30) { username = username.substring(0, 30); username += this._ellipsis; @@ -1543,7 +1543,7 @@ LoginManagerPrompter.prototype = { * Returns the hostname to use in a nsILoginInfo object (for example, * "http://example.com"). */ - _getFormattedHostname : function(aURI) { + _getFormattedHostname(aURI) { let uri; if (aURI instanceof Ci.nsIURI) { uri = aURI; @@ -1560,7 +1560,7 @@ LoginManagerPrompter.prototype = { * prompting purposes. Eg, "http://foo.com" --> "foo.com", or * "ftp://www.site.co.uk" --> "site.co.uk". */ - _getShortDisplayHost: function(aURIString) { + _getShortDisplayHost(aURIString) { var displayHost; var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"]. @@ -1586,7 +1586,7 @@ LoginManagerPrompter.prototype = { * Returns the hostname and realm for which authentication is being * requested, in the format expected to be used with nsILoginInfo. */ - _getAuthTarget : function(aChannel, aAuthInfo) { + _getAuthTarget(aChannel, aAuthInfo) { var hostname, realm; // If our proxy is demanding authentication, don't use the @@ -1634,7 +1634,7 @@ LoginManagerPrompter.prototype = { * If the authentication was for a Windows domain, we'll prepend the * return username with the domain. (eg, "domain\user") */ - _GetAuthInfo : function(aAuthInfo) { + _GetAuthInfo(aAuthInfo) { var username, password; var flags = aAuthInfo.flags; @@ -1654,7 +1654,7 @@ LoginManagerPrompter.prototype = { * domain out of the username if necessary and sets domain, username and * password on the auth information object. */ - _SetAuthInfo : function(aAuthInfo, username, password) { + _SetAuthInfo(aAuthInfo, username, password) { var flags = aAuthInfo.flags; if (flags & Ci.nsIAuthInformation.NEED_DOMAIN) { // Domain is separated from username by a backslash @@ -1671,12 +1671,12 @@ LoginManagerPrompter.prototype = { aAuthInfo.password = password; }, - _newAsyncPromptConsumer : function(aCallback, aContext) { + _newAsyncPromptConsumer(aCallback, aContext) { return { QueryInterface: XPCOMUtils.generateQI([Ci.nsICancelable]), callback: aCallback, context: aContext, - cancel: function() { + cancel() { this.callback.onAuthCancelled(this.context, false); this.callback = null; this.context = null; diff --git a/toolkit/components/passwordmgr/storage-json.js b/toolkit/components/passwordmgr/storage-json.js index 5bf75aab5071..bf9b13cc4e28 100644 --- a/toolkit/components/passwordmgr/storage-json.js +++ b/toolkit/components/passwordmgr/storage-json.js @@ -141,7 +141,7 @@ this.LoginManagerStorage_json.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: loginClone.guid, - encType: encType, + encType, timeCreated: loginClone.timeCreated, timeLastUsed: loginClone.timeLastUsed, timePasswordChanged: loginClone.timePasswordChanged, @@ -377,9 +377,9 @@ this.LoginManagerStorage_json.prototype = { findLogins(count, hostname, formSubmitURL, httpRealm) { let loginData = { - hostname: hostname, - formSubmitURL: formSubmitURL, - httpRealm: httpRealm + hostname, + formSubmitURL, + httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) @@ -397,9 +397,9 @@ this.LoginManagerStorage_json.prototype = { countLogins(hostname, formSubmitURL, httpRealm) { let loginData = { - hostname: hostname, - formSubmitURL: formSubmitURL, - httpRealm: httpRealm + hostname, + formSubmitURL, + httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) diff --git a/toolkit/components/passwordmgr/storage-mozStorage.js b/toolkit/components/passwordmgr/storage-mozStorage.js index f1f1273c70c5..54f640ae4f83 100644 --- a/toolkit/components/passwordmgr/storage-mozStorage.js +++ b/toolkit/components/passwordmgr/storage-mozStorage.js @@ -31,12 +31,12 @@ function Transaction(aDatabase) { } Transaction.prototype = { - commit : function() { + commit() { if (this._hasTransaction) this._db.commitTransaction(); }, - rollback : function() { + rollback() { if (this._hasTransaction) this._db.rollbackTransaction(); }, @@ -50,7 +50,7 @@ LoginManagerStorage_mozStorage.prototype = { classID : Components.ID("{8c2023b9-175c-477e-9761-44ae7b549756}"), QueryInterface : XPCOMUtils.generateQI([Ci.nsILoginManagerStorage, Ci.nsIInterfaceRequestor]), - getInterface : function(aIID) { + getInterface(aIID) { if (aIID.equals(Ci.nsIVariant)) { // Allows unwrapping the JavaScript object for regression tests. return this; @@ -155,7 +155,7 @@ LoginManagerStorage_mozStorage.prototype = { * Internal method used by regression tests only. It overrides the default * database location. */ - initWithFile : function(aDBFile) { + initWithFile(aDBFile) { if (aDBFile) this._signonsFile = aDBFile; @@ -163,7 +163,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - initialize : function() { + initialize() { this._dbStmts = {}; let isFirstRun; @@ -200,12 +200,12 @@ LoginManagerStorage_mozStorage.prototype = { * Internal method used by regression tests only. It is called before * replacing this storage module with a new instance. */ - terminate : function() { + terminate() { return Promise.resolve(); }, - addLogin : function(login) { + addLogin(login) { // Throws if there are bogus values. LoginHelper.checkLoginValues(login); @@ -254,7 +254,7 @@ LoginManagerStorage_mozStorage.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: loginClone.guid, - encType: encType, + encType, timeCreated: loginClone.timeCreated, timeLastUsed: loginClone.timeLastUsed, timePasswordChanged: loginClone.timePasswordChanged, @@ -280,7 +280,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - removeLogin : function(login) { + removeLogin(login) { let [idToDelete, storedLogin] = this._getIdForLogin(login); if (!idToDelete) throw new Error("No matching logins"); @@ -307,7 +307,7 @@ LoginManagerStorage_mozStorage.prototype = { LoginHelper.notifyStorageChanged("removeLogin", storedLogin); }, - modifyLogin : function(oldLogin, newLoginData) { + modifyLogin(oldLogin, newLoginData) { let [idToModify, oldStoredLogin] = this._getIdForLogin(oldLogin); if (!idToModify) throw new Error("No matching logins"); @@ -360,7 +360,7 @@ LoginManagerStorage_mozStorage.prototype = { encryptedUsername: encUsername, encryptedPassword: encPassword, guid: newLogin.guid, - encType: encType, + encType, timeCreated: newLogin.timeCreated, timeLastUsed: newLogin.timeLastUsed, timePasswordChanged: newLogin.timePasswordChanged, @@ -387,7 +387,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Returns an array of nsILoginInfo. */ - getAllLogins : function(count) { + getAllLogins(count) { let [logins, ids] = this._searchLogins({}); // decrypt entries for caller. @@ -406,7 +406,7 @@ LoginManagerStorage_mozStorage.prototype = { * * @return {nsILoginInfo[]} which are decrypted. */ - searchLogins : function(count, matchData) { + searchLogins(count, matchData) { let realMatchData = {}; let options = {}; // Convert nsIPropertyBag to normal JS object @@ -444,7 +444,7 @@ LoginManagerStorage_mozStorage.prototype = { * is an array of encrypted nsLoginInfo and ids is an array of associated * ids in the database. */ - _searchLogins : function(matchData, aOptions = { + _searchLogins(matchData, aOptions = { schemeUpgrades: false, }) { let conditions = [], params = {}; @@ -551,7 +551,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Moves a login to the deleted logins table */ - storeDeletedLogin : function(aLogin) { + storeDeletedLogin(aLogin) { let stmt = null; try { this.log("Storing " + aLogin.guid + " in deleted passwords\n"); @@ -572,7 +572,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Removes all logins from storage. */ - removeAllLogins : function() { + removeAllLogins() { this.log("Removing all logins"); let query; let stmt; @@ -600,11 +600,11 @@ LoginManagerStorage_mozStorage.prototype = { }, - findLogins : function(count, hostname, formSubmitURL, httpRealm) { + findLogins(count, hostname, formSubmitURL, httpRealm) { let loginData = { - hostname: hostname, - formSubmitURL: formSubmitURL, - httpRealm: httpRealm + hostname, + formSubmitURL, + httpRealm }; let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) @@ -621,7 +621,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - countLogins : function(hostname, formSubmitURL, httpRealm) { + countLogins(hostname, formSubmitURL, httpRealm) { let _countLoginsHelper = (hostname, formSubmitURL, httpRealm) => { // Do checks for null and empty strings, adjust conditions and params @@ -670,7 +670,7 @@ LoginManagerStorage_mozStorage.prototype = { * found, both items will be null. The returned login contains the actual * stored login (useful for looking at the actual nsILoginMetaInfo values). */ - _getIdForLogin : function(login) { + _getIdForLogin(login) { let matchData = { }; for (let field of ["hostname", "formSubmitURL", "httpRealm"]) if (login[field] != '') @@ -705,7 +705,7 @@ LoginManagerStorage_mozStorage.prototype = { * statement being created. This fixes the cases where nulls are involved * and the empty string is supposed to be a wildcard match */ - _buildConditionsAndParams : function(hostname, formSubmitURL, httpRealm) { + _buildConditionsAndParams(hostname, formSubmitURL, httpRealm) { let conditions = [], params = {}; if (hostname == null) { @@ -736,9 +736,9 @@ LoginManagerStorage_mozStorage.prototype = { /** * Checks to see if the specified GUID already exists. */ - _isGuidUnique : function(guid) { + _isGuidUnique(guid) { let query = "SELECT COUNT(1) AS numLogins FROM moz_logins WHERE guid = :guid"; - let params = { guid: guid }; + let params = { guid }; let stmt, numLogins; try { @@ -761,7 +761,7 @@ LoginManagerStorage_mozStorage.prototype = { * Returns the encrypted username, password, and encrypton type for the specified * login. Can throw if the user cancels a master password entry. */ - _encryptLogin : function(login) { + _encryptLogin(login) { let encUsername = this._crypto.encrypt(login.username); let encPassword = this._crypto.encrypt(login.password); let encType = this._crypto.defaultEncType; @@ -781,7 +781,7 @@ LoginManagerStorage_mozStorage.prototype = { * to lose unencrypted entries (eg, because the user clicked Cancel * instead of entering their master password) */ - _decryptLogins : function(logins) { + _decryptLogins(logins) { let result = []; for (let login of logins) { @@ -809,7 +809,7 @@ LoginManagerStorage_mozStorage.prototype = { * Returns the wrapped statement for execution. Will use memoization * so that statements can be reused. */ - _dbCreateStatement : function(query, params) { + _dbCreateStatement(query, params) { let wrappedStmt = this._dbStmts[query]; // Memoize the statements if (!wrappedStmt) { @@ -829,7 +829,7 @@ LoginManagerStorage_mozStorage.prototype = { * Attempts to initialize the database. This creates the file if it doesn't * exist, performs any migrations, etc. Return if this is the first run. */ - _dbInit : function() { + _dbInit() { this.log("Initializing Database"); let isFirstRun = false; try { @@ -856,7 +856,7 @@ LoginManagerStorage_mozStorage.prototype = { return isFirstRun; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { switch (topic) { case "profile-before-change": Services.obs.removeObserver(this, "profile-before-change"); @@ -865,27 +865,27 @@ LoginManagerStorage_mozStorage.prototype = { } }, - _dbCreate: function() { + _dbCreate() { this.log("Creating Database"); this._dbCreateSchema(); this._dbConnection.schemaVersion = DB_VERSION; }, - _dbCreateSchema : function() { + _dbCreateSchema() { this._dbCreateTables(); this._dbCreateIndices(); }, - _dbCreateTables : function() { + _dbCreateTables() { this.log("Creating Tables"); for (let name in this._dbSchema.tables) this._dbConnection.createTable(name, this._dbSchema.tables[name]); }, - _dbCreateIndices : function() { + _dbCreateIndices() { this.log("Creating Indices"); for (let name in this._dbSchema.indices) { let index = this._dbSchema.indices[name]; @@ -896,7 +896,7 @@ LoginManagerStorage_mozStorage.prototype = { }, - _dbMigrate : function(oldVersion) { + _dbMigrate(oldVersion) { this.log("Attempting to migrate from version " + oldVersion); if (oldVersion > DB_VERSION) { @@ -943,7 +943,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 2 adds a GUID column. Existing logins are assigned a random GUID. */ - _dbMigrateToVersion2 : function() { + _dbMigrateToVersion2() { // Check to see if GUID column already exists, add if needed let query; if (!this._dbColumnExists("guid")) { @@ -975,7 +975,7 @@ LoginManagerStorage_mozStorage.prototype = { query = "UPDATE moz_logins SET guid = :guid WHERE id = :id"; for (let id of ids) { let params = { - id: id, + id, guid: this._uuidService.generateUUID().toString() }; @@ -997,7 +997,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 3 adds a encType column. */ - _dbMigrateToVersion3 : function() { + _dbMigrateToVersion3() { // Check to see if encType column already exists, add if needed let query; if (!this._dbColumnExists("encType")) { @@ -1057,7 +1057,7 @@ LoginManagerStorage_mozStorage.prototype = { * Version 4 adds timeCreated, timeLastUsed, timePasswordChanged, * and timesUsed columns */ - _dbMigrateToVersion4 : function() { + _dbMigrateToVersion4() { let query; // Add the new columns, if needed. for (let column of ["timeCreated", "timeLastUsed", "timePasswordChanged", "timesUsed"]) { @@ -1112,7 +1112,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Version 5 adds the moz_deleted_logins table */ - _dbMigrateToVersion5 : function() { + _dbMigrateToVersion5() { if (!this._dbConnection.tableExists("moz_deleted_logins")) { this._dbConnection.createTable("moz_deleted_logins", this._dbSchema.tables.moz_deleted_logins); } @@ -1122,7 +1122,7 @@ LoginManagerStorage_mozStorage.prototype = { * Version 6 migrates all the hosts from * moz_disabledHosts to the permission manager. */ - _dbMigrateToVersion6 : function() { + _dbMigrateToVersion6() { let disabledHosts = []; let query = "SELECT hostname FROM moz_disabledHosts"; let stmt; @@ -1158,7 +1158,7 @@ LoginManagerStorage_mozStorage.prototype = { * Sanity check to ensure that the columns this version of the code expects * are present in the DB we're using. */ - _dbAreExpectedColumnsPresent : function() { + _dbAreExpectedColumnsPresent() { let query = "SELECT " + "id, " + "hostname, " + @@ -1203,7 +1203,7 @@ LoginManagerStorage_mozStorage.prototype = { /** * Checks to see if the named column already exists. */ - _dbColumnExists : function(columnName) { + _dbColumnExists(columnName) { let query = "SELECT " + columnName + " FROM moz_logins"; try { let stmt = this._dbConnection.createStatement(query); @@ -1215,7 +1215,7 @@ LoginManagerStorage_mozStorage.prototype = { } }, - _dbClose : function() { + _dbClose() { this.log("Closing the DB connection."); // Finalize all statements to free memory, avoid errors later for (let query in this._dbStmts) { @@ -1238,7 +1238,7 @@ LoginManagerStorage_mozStorage.prototype = { * Called when database creation fails. Finalizes database statements, * closes the database connection, deletes the database file. */ - _dbCleanup : function(backup) { + _dbCleanup(backup) { this.log("Cleaning up DB file - close & remove & backup=" + backup); // Create backup file diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js index f2255b32738d..0b04042e3482 100644 --- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js @@ -19,7 +19,7 @@ add_task(function* test() { let modifiedLogin; let testNumber = 0; let testObserver = { - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic == "passwordmgr-dialog-updated") { switch (testNumber) { case 1: diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js index efe7c26c5d7c..4f841f042c34 100644 --- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js @@ -12,7 +12,7 @@ add_task(function* test() { isnot(tab, gBrowser.selectedTab, "New tab shouldn't be selected"); let listener = { - onOpenWindow: function(window) { + onOpenWindow(window) { var domwindow = window.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindow); waitForFocus(() => { @@ -25,7 +25,7 @@ add_task(function* test() { }, domwindow); }, - onCloseWindow: function() { + onCloseWindow() { } }; diff --git a/toolkit/components/passwordmgr/test/prompt_common.js b/toolkit/components/passwordmgr/test/prompt_common.js index a72e04ba28eb..6749ea4db6a2 100644 --- a/toolkit/components/passwordmgr/test/prompt_common.js +++ b/toolkit/components/passwordmgr/test/prompt_common.js @@ -26,7 +26,7 @@ function startCallbackTimer() { var observer = SpecialPowers.wrapCallbackObject({ - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports, Ci.nsISupportsWeakReference]; @@ -35,7 +35,7 @@ var observer = SpecialPowers.wrapCallbackObject({ return this; }, - observe : function(subject, topic, data) { + observe(subject, topic, data) { var doc = getDialogDoc(); if (doc) handleDialog(doc, testNum); diff --git a/toolkit/components/passwordmgr/test/unit/test_notifications.js b/toolkit/components/passwordmgr/test/unit/test_notifications.js index d564c766aa08..0ff2253baa47 100644 --- a/toolkit/components/passwordmgr/test/unit/test_notifications.js +++ b/toolkit/components/passwordmgr/test/unit/test_notifications.js @@ -8,7 +8,7 @@ var expectedData; var TestObserver = { QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - observe : function(subject, topic, data) { + observe(subject, topic, data) { do_check_eq(topic, "passwordmgr-storage-changed"); do_check_eq(data, expectedNotification); diff --git a/toolkit/components/passwordmgr/test/unit/test_storage.js b/toolkit/components/passwordmgr/test/unit/test_storage.js index d65516d9b007..09ec96131164 100644 --- a/toolkit/components/passwordmgr/test/unit/test_storage.js +++ b/toolkit/components/passwordmgr/test/unit/test_storage.js @@ -31,7 +31,7 @@ add_task(function* test_storage_addLogin_nonascii() // Store the strings "user" and "pass" using similarly looking glyphs. let loginInfo = TestData.formLogin({ - hostname: hostname, + hostname, formSubmitURL: hostname, username: String.fromCharCode(533, 537, 7570, 345), password: String.fromCharCode(421, 259, 349, 537), diff --git a/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js b/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js index 36da8e8b72bb..7b869ab6ebb3 100644 --- a/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js +++ b/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js @@ -35,7 +35,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -63,7 +63,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -95,7 +95,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -123,7 +123,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -155,7 +155,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -183,7 +183,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -211,7 +211,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: true, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -239,7 +239,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: true, isSecure: false, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -267,7 +267,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -295,7 +295,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -327,7 +327,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -355,7 +355,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: "This connection is not secure. Logins entered here could be compromised.", @@ -387,7 +387,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "", label: LABEL_NO_USERNAME, @@ -415,7 +415,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: false, - matchingLogins: matchingLogins, + matchingLogins, items: [] }, { @@ -423,7 +423,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: true, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [{ value: "emptypass1", label: LABEL_NO_USERNAME, @@ -451,7 +451,7 @@ let expectedResults = [ insecureAutoFillFormsEnabled: false, isSecure: false, isPasswordField: true, - matchingLogins: matchingLogins, + matchingLogins, items: [] }, ]; diff --git a/toolkit/components/perfmonitoring/AddonWatcher.jsm b/toolkit/components/perfmonitoring/AddonWatcher.jsm index 58decba85722..b081f97e98d2 100644 --- a/toolkit/components/perfmonitoring/AddonWatcher.jsm +++ b/toolkit/components/perfmonitoring/AddonWatcher.jsm @@ -44,7 +44,7 @@ this.AddonWatcher = { */ TOPIC_SLOW_ADDON_DETECTED: "addon-watcher-detected-slow-addon", - init: function() { + init() { this._initializedTimeStamp = Cu.now(); try { @@ -58,7 +58,7 @@ this.AddonWatcher = { this._idleThreshold = Preferences.get("browser.addon-watch.deactivate-after-idle-ms", 3000); this.paused = false; }, - uninit: function() { + uninit() { this.paused = true; }, _initializedTimeStamp: 0, @@ -87,7 +87,7 @@ this.AddonWatcher = { * {number} latestNotificationTimeStamp The timestamp of the latest user notification * that this add-on is slow. */ - _getAlerts: function(addonId) { + _getAlerts(addonId) { let alerts = this._alerts.get(addonId); if (!alerts) { alerts = { @@ -100,7 +100,7 @@ this.AddonWatcher = { return alerts; }, _alerts: new Map(), - _onSlowAddons: function(addons) { + _onSlowAddons(addons) { try { if (IdleService.idleTime >= this._idleThreshold) { // The application is idle. Maybe the computer is sleeping, or maybe @@ -202,10 +202,10 @@ this.AddonWatcher = { } }, - ignoreAddonForSession: function(addonid) { + ignoreAddonForSession(addonid) { this._ignoreList.add(addonid); }, - ignoreAddonPermanently: function(addonid) { + ignoreAddonPermanently(addonid) { this._ignoreList.add(addonid); try { let ignoreList = JSON.parse(Preferences.get("browser.addon-watch.ignore", "[]")) diff --git a/toolkit/components/perfmonitoring/PerformanceStats.jsm b/toolkit/components/perfmonitoring/PerformanceStats.jsm index 6b5fb117c49e..155009bb2916 100644 --- a/toolkit/components/perfmonitoring/PerformanceStats.jsm +++ b/toolkit/components/perfmonitoring/PerformanceStats.jsm @@ -79,7 +79,7 @@ Probe.prototype = { * If the probe was inactive, activate it. Note that activating a probe * can incur a memory or performance cost. */ - acquire: function() { + acquire() { if (this._counter == 0) { this._impl.isActive = true; Process.broadcast("acquire", [this._name]); @@ -92,7 +92,7 @@ Probe.prototype = { * * If this was the last client for this probe, deactivate it. */ - release: function() { + release() { this._counter--; if (this._counter == 0) { try { @@ -117,7 +117,7 @@ Probe.prototype = { * @return {object} An object containing the data extracted from this * probe. Actual format depends on the probe. */ - extract: function(xpcom) { + extract(xpcom) { if (!this._impl.isActive) { throw new Error(`Probe is inactive: ${this._name}`); } @@ -130,7 +130,7 @@ Probe.prototype = { * * @return {true} If `a` and `b` hold identical values. */ - isEqual: function(a, b) { + isEqual(a, b) { if (a == null && b == null) { return true; } @@ -149,7 +149,7 @@ Probe.prototype = { * @return {object} An object representing `a - b`. If `b` is * `null`, this is `a`. */ - subtract: function(a, b) { + subtract(a, b) { if (a == null) { throw new TypeError(); } @@ -159,7 +159,7 @@ Probe.prototype = { return this._impl.subtract(a, b); }, - importChildCompartments: function(parent, children) { + importChildCompartments(parent, children) { if (!Array.isArray(children)) { throw new TypeError(); } @@ -176,7 +176,7 @@ Probe.prototype = { return this._name; }, - compose: function(stats) { + compose(stats) { if (!Array.isArray(stats)) { throw new TypeError(); } @@ -221,17 +221,17 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringJank; }, - extract: function(xpcom) { + extract(xpcom) { let durations = xpcom.getDurations(); return { totalUserTime: xpcom.totalUserTime, totalSystemTime: xpcom.totalSystemTime, totalCPUTime: xpcom.totalUserTime + xpcom.totalSystemTime, - durations: durations, + durations, longestDuration: lastNonZero(durations) } }, - isEqual: function(a, b) { + isEqual(a, b) { // invariant: `a` and `b` are both non-null if (a.totalUserTime != b.totalUserTime) { return false; @@ -246,7 +246,7 @@ var Probes = { } return true; }, - subtract: function(a, b) { + subtract(a, b) { // invariant: `a` and `b` are both non-null let result = { totalUserTime: a.totalUserTime - b.totalUserTime, @@ -261,8 +261,8 @@ var Probes = { result.longestDuration = lastNonZero(result.durations); return result; }, - importChildCompartments: function() { /* nothing to do */ }, - compose: function(stats) { + importChildCompartments() { /* nothing to do */ }, + compose(stats) { let result = { totalUserTime: 0, totalSystemTime: 0, @@ -298,21 +298,21 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringCPOW; }, - extract: function(xpcom) { + extract(xpcom) { return { totalCPOWTime: xpcom.totalCPOWTime }; }, - isEqual: function(a, b) { + isEqual(a, b) { return a.totalCPOWTime == b.totalCPOWTime; }, - subtract: function(a, b) { + subtract(a, b) { return { totalCPOWTime: a.totalCPOWTime - b.totalCPOWTime }; }, - importChildCompartments: function() { /* nothing to do */ }, - compose: function(stats) { + importChildCompartments() { /* nothing to do */ }, + compose(stats) { let totalCPOWTime = 0; for (let stat of stats) { totalCPOWTime += stat.totalCPOWTime; @@ -335,21 +335,21 @@ var Probes = { ticks: new Probe("ticks", { set isActive(x) { /* this probe cannot be deactivated */ }, get isActive() { return true; }, - extract: function(xpcom) { + extract(xpcom) { return { ticks: xpcom.ticks }; }, - isEqual: function(a, b) { + isEqual(a, b) { return a.ticks == b.ticks; }, - subtract: function(a, b) { + subtract(a, b) { return { ticks: a.ticks - b.ticks }; }, - importChildCompartments: function() { /* nothing to do */ }, - compose: function(stats) { + importChildCompartments() { /* nothing to do */ }, + compose(stats) { let ticks = 0; for (let stat of stats) { ticks += stat.ticks; @@ -365,19 +365,19 @@ var Probes = { get isActive() { return performanceStatsService.isMonitoringPerCompartment; }, - extract: function(xpcom) { + extract(xpcom) { return null; }, - isEqual: function(a, b) { + isEqual(a, b) { return true; }, - subtract: function(a, b) { + subtract(a, b) { return true; }, - importChildCompartments: function(parent, children) { + importChildCompartments(parent, children) { parent.children = children; }, - compose: function(stats) { + compose(stats) { return null; }, }), @@ -447,7 +447,7 @@ PerformanceMonitor.prototype = { * @return {Promise} * @resolve {Snapshot} */ - _checkBeforeSnapshot: function(options) { + _checkBeforeSnapshot(options) { if (!this._finalizer) { throw new Error("dispose() has already been called, this PerformanceMonitor is not usable anymore"); } @@ -472,11 +472,11 @@ PerformanceMonitor.prototype = { } return probes; }, - promiseContentSnapshot: function(options = null) { + promiseContentSnapshot(options = null) { this._checkBeforeSnapshot(options); return (new ProcessSnapshot(performanceStatsService.getSnapshot())); }, - promiseSnapshot: function(options = null) { + promiseSnapshot(options = null) { let probes = this._checkBeforeSnapshot(options); return Task.spawn(function*() { let childProcesses = yield Process.broadcastAndCollect("collect", {probeNames: probes.map(p => p.name)}); @@ -496,7 +496,7 @@ PerformanceMonitor.prototype = { * Releasing probes as soon as they are unused is a good idea, as some probes * cost CPU and/or memory. */ - dispose: function() { + dispose() { if (!this._finalizer) { return; } @@ -573,7 +573,7 @@ this.PerformanceStats = { /** * Create a monitor for observing a set of performance probes. */ - getMonitor: function(probes) { + getMonitor(probes) { return PerformanceMonitor.make(probes); } }; @@ -640,7 +640,7 @@ PerformanceDataLeaf.prototype = { * * @return `true` if `this` and `to` have equal values in all fields. */ - equals: function(to) { + equals(to) { if (!(to instanceof PerformanceDataLeaf)) { throw new TypeError(); } @@ -661,7 +661,7 @@ PerformanceDataLeaf.prototype = { * * @return {PerformanceDiff} The performance usage between `to` and `this`. */ - subtract: function(to = null) { + subtract(to = null) { return (new PerformanceDiffLeaf(this, to)); } }; @@ -673,7 +673,7 @@ function PerformanceData(timestamp) { this._timestamp = timestamp; } PerformanceData.prototype = { - addChild: function(stat) { + addChild(stat) { if (!(stat instanceof PerformanceDataLeaf)) { throw new TypeError(); // FIXME } @@ -684,7 +684,7 @@ PerformanceData.prototype = { this._all.push(stat); stat.owner = this; }, - setParent: function(stat) { + setParent(stat) { if (!(stat instanceof PerformanceDataLeaf)) { throw new TypeError(); // FIXME } @@ -695,7 +695,7 @@ PerformanceData.prototype = { this._all.push(stat); stat.owner = this; }, - equals: function(to) { + equals(to) { if (this._parent && !to._parent) { return false; } @@ -719,7 +719,7 @@ PerformanceData.prototype = { } return true; }, - subtract: function(to = null) { + subtract(to = null) { return (new PerformanceDiff(this, to)); }, get addonId() { @@ -767,7 +767,7 @@ function PerformanceDiff(current, old = null) { } } PerformanceDiff.prototype = { - toString: function() { + toString() { return `[PerformanceDiff] ${this.key}`; }, get windowIds() { @@ -924,7 +924,7 @@ var Process = { * * NOOP if we are in a child process. */ - broadcast: function(topic, payload) { + broadcast(topic, payload) { if (!this.loader) { return; } diff --git a/toolkit/components/perfmonitoring/PerformanceWatcher.jsm b/toolkit/components/perfmonitoring/PerformanceWatcher.jsm index d0d034974967..994c057c59f6 100644 --- a/toolkit/components/perfmonitoring/PerformanceWatcher.jsm +++ b/toolkit/components/perfmonitoring/PerformanceWatcher.jsm @@ -95,20 +95,20 @@ ChildManager.prototype = { * Add a listener, which will be notified whenever a child process * reports a slow performance alert for this addon/window. */ - addListener: function(listener) { + addListener(listener) { this._listeners.add(listener); }, /** * Remove a listener. */ - removeListener: function(listener) { + removeListener(listener) { let deleted = this._listeners.delete(listener); if (!deleted) { throw new Error("Unknown listener"); } }, - listeners: function() { + listeners() { return this._listeners.values(); } }; @@ -216,7 +216,7 @@ function Observable(target) { } } Observable.prototype = { - addJankObserver: function(listener) { + addJankObserver(listener) { if (this._observers.has(listener)) { throw new TypeError(`Listener already registered for target ${this._key}`); } @@ -230,7 +230,7 @@ Observable.prototype = { this._process.addJankObserver(observer); }, - removeJankObserver: function(listener) { + removeJankObserver(listener) { let observer = this._observers.get(listener); if (!observer) { throw new TypeError(`No listener for target ${this._key}`); @@ -284,10 +284,10 @@ function Observer(listener) { this._listener = listener; } Observer.prototype = { - observe: function(...args) { + observe(...args) { this._listener(...args); }, - dispose: function() { + dispose() { this._monitor.dispose(); this.observe = function poison() { throw new Error("Internal error: I should have stopped receiving notifications"); @@ -350,14 +350,14 @@ this.PerformanceWatcher = { * If the listener listens to all add-ons/all webpages, it is triggered with * an array of {source, details}, as described above. */ - addPerformanceListener: function(target, listener) { + addPerformanceListener(target, listener) { if (typeof listener != "function") { throw new TypeError(); } let observable = Observable.get(target); observable.addJankObserver(listener); }, - removePerformanceListener: function(target, listener) { + removePerformanceListener(target, listener) { if (typeof listener != "function") { throw new TypeError(); } diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js b/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js index 8b674937282f..b7bc198e05b6 100644 --- a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js +++ b/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js @@ -64,25 +64,25 @@ function frameScript() { // A variant of `Assert` that doesn't spam the logs // in case of success. var SilentAssert = { - equal: function(a, b, msg) { + equal(a, b, msg) { if (a == b) { return; } Assert.equal(a, b, msg); }, - notEqual: function(a, b, msg) { + notEqual(a, b, msg) { if (a != b) { return; } Assert.notEqual(a, b, msg); }, - ok: function(a, msg) { + ok(a, msg) { if (a) { return; } Assert.ok(a, msg); }, - leq: function(a, b, msg) { + leq(a, b, msg) { this.ok(a <= b, `${msg}: ${a} <= ${b}`); } }; diff --git a/toolkit/components/perfmonitoring/tests/browser/head.js b/toolkit/components/perfmonitoring/tests/browser/head.js index 92258fd1b9d6..85e2ca5f2bb0 100644 --- a/toolkit/components/perfmonitoring/tests/browser/head.js +++ b/toolkit/components/perfmonitoring/tests/browser/head.js @@ -45,7 +45,7 @@ CPUBurner.prototype = { } return false; }), - dispose: function() { + dispose() { info(`CPUBurner: Closing tab for ${this.url}\n`); gBrowser.removeTab(this.tab); } @@ -142,7 +142,7 @@ function AlertListener(accept, {register, unregister}) { register(); } AlertListener.prototype = { - unregister: function() { + unregister() { this.reset(); if (this._unregistered) { info(`head.js: No need to unregister, we're already unregistered.\n`); @@ -153,7 +153,7 @@ AlertListener.prototype = { this._unregister(); info(`head.js: Unregistration complete.\n`); }, - reset: function() { + reset() { this.triggered = false; this.result = null; }, @@ -181,7 +181,7 @@ function AddonBurner(addonId = "fake add-on id: " + Math.random()) { } AddonBurner.prototype = Object.create(CPUBurner.prototype); Object.defineProperty(AddonBurner.prototype, "addonId", { - get: function() { + get() { return this._addonId; } }); diff --git a/toolkit/components/places/BookmarkHTMLUtils.jsm b/toolkit/components/places/BookmarkHTMLUtils.jsm index 5aff75e9d084..10db007368c6 100644 --- a/toolkit/components/places/BookmarkHTMLUtils.jsm +++ b/toolkit/components/places/BookmarkHTMLUtils.jsm @@ -1037,19 +1037,19 @@ BookmarkExporter.prototype = { _converterOut: null, - _write: function(aText) { + _write(aText) { this._converterOut.writeString(aText || ""); }, - _writeAttribute: function(aName, aValue) { + _writeAttribute(aName, aValue) { this._write(' ' + aName + '="' + aValue + '"'); }, - _writeLine: function(aText) { + _writeLine(aText) { this._write(aText + "\n"); }, - _writeHeader: function() { + _writeHeader() { this._writeLine(""); this._writeLine(" { this._rebuild(); }, - onError: function(errorCode) { + onError(errorCode) { if (errorCode != Ci.nsISearchInstallCallback.ERROR_DUPLICATE_ENGINE) { // Download error is shown by the search service return; diff --git a/toolkit/components/alerts/test/test_alerts.html b/toolkit/components/alerts/test/test_alerts.html index 2e55aa5ffa8a..b210af4b6d9a 100644 --- a/toolkit/components/alerts/test/test_alerts.html +++ b/toolkit/components/alerts/test/test_alerts.html @@ -21,7 +21,7 @@ var observer = { alertShow: false, - observe: function(aSubject, aTopic, aData) { + observe(aSubject, aTopic, aData) { is(aData, "foobarcookie", "Checking whether the alert cookie was passed correctly"); if (aTopic == "alertclickcallback") { todo(false, "Did someone click the notification while running mochitests? (Please don't.)"); diff --git a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html index 65c79f3bb78b..dc4acbd01cd1 100644 --- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html +++ b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html @@ -76,14 +76,14 @@ var startupComplete = new Promise(resolve => startupCompleteResolver = resolve); function proxyChannelListener() { } proxyChannelListener.prototype = { - onStartRequest: function(request, context) { + onStartRequest(request, context) { startupCompleteResolver(); }, - onStopRequest: function(request, context, status) { } + onStopRequest(request, context, status) { } }; var resolveCallback = SpecialPowers.wrapCallbackObject({ - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -91,7 +91,7 @@ var resolveCallback = SpecialPowers.wrapCallbackObject({ return this; }, - onProxyAvailable : function(req, uri, pi, status) { + onProxyAvailable(req, uri, pi, status) { initLogins(pi); // I'm cheating a bit here... We should probably do some magic foo to get diff --git a/toolkit/components/passwordmgr/test/test_master_password.html b/toolkit/components/passwordmgr/test/test_master_password.html index c8884811f7c6..1b2d5f48194d 100644 --- a/toolkit/components/passwordmgr/test/test_master_password.html +++ b/toolkit/components/passwordmgr/test/test_master_password.html @@ -128,7 +128,7 @@ function handleDialog(doc, testNumber) { } var outerWindowObserver = { - observe: function(id) { + observe(id) { SpecialPowers.removeObserver(outerWindowObserver, "outer-window-destroyed"); var func; if (testNum == 1) diff --git a/toolkit/components/passwordmgr/test/test_prompt_async.html b/toolkit/components/passwordmgr/test/test_prompt_async.html index 03bea611bc8f..4cb08e0959b6 100644 --- a/toolkit/components/passwordmgr/test/test_prompt_async.html +++ b/toolkit/components/passwordmgr/test/test_prompt_async.html @@ -39,7 +39,7 @@ windowsOpen : 0, windowsRegistered : 0, - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIObserver, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -47,7 +47,7 @@ return this; }, - observe: function(subject, topic, data) { + observe(subject, topic, data) { if (topic === "domwindowopened") { this.windowsOpen++; this.windowsRegistered++; @@ -59,14 +59,14 @@ } }, - shutdown: function() { + shutdown() { var observerService = SpecialPowers.Cc["@mozilla.org/observer-service;1"] .getService(Ci.nsIObserverService); observerService.removeObserver(this, "domwindowopened"); observerService.removeObserver(this, "domwindowclosed"); }, - reset: function() { + reset() { this.windowsOpen = 0; this.windowsRegistered = 0; } @@ -130,7 +130,7 @@ } var resolveCallback = SpecialPowers.wrapCallbackObject({ - QueryInterface : function(iid) { + QueryInterface(iid) { const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports]; if (!interfaces.some( function(v) { return iid.equals(v); } )) @@ -138,7 +138,7 @@ return this; }, - onProxyAvailable : function(req, uri, pi, status) { + onProxyAvailable(req, uri, pi, status) { initLogins(pi); doTest(testNum); } diff --git a/toolkit/components/printing/content/printPreviewBindings.xml b/toolkit/components/printing/content/printPreviewBindings.xml index 6b279d5cca42..6054c21733a8 100644 --- a/toolkit/components/printing/content/printPreviewBindings.xml +++ b/toolkit/components/printing/content/printPreviewBindings.xml @@ -219,8 +219,8 @@ } this.mMessageManager.sendAsyncMessage("Printing:Preview:Navigate", { - navType: navType, - pageNum: pageNum, + navType, + pageNum, }); ]]> @@ -242,8 +242,8 @@ var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService); var promptStr = this.mScaleLabel.value; var renameTitle = this.mCustomTitle; - var result = {value:value}; - var confirmed = promptService.prompt(window, renameTitle, promptStr, result, null, {value:value}); + var result = {value}; + var confirmed = promptService.prompt(window, renameTitle, promptStr, result, null, {value}); if (!confirmed || (!result.value) || (result.value == "") || result.value == value) { return -1; } diff --git a/toolkit/components/satchel/test/test_form_autocomplete.html b/toolkit/components/satchel/test/test_form_autocomplete.html index 57750af28e5c..447841df00ac 100644 --- a/toolkit/components/satchel/test/test_form_autocomplete.html +++ b/toolkit/components/satchel/test/test_form_autocomplete.html @@ -1032,7 +1032,7 @@ function runTest() { function addEntry(name, value) { - updateFormHistory({ op : "add", fieldname : name, value: value }, runTest); + updateFormHistory({ op : "add", fieldname : name, value }, runTest); } // Runs the next test when scroll event occurs diff --git a/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html b/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html index 540eeacf4b29..8ccd1ef65d87 100644 --- a/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html +++ b/toolkit/content/tests/mochitest/test_autocomplete_change_after_focus.html @@ -24,7 +24,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=998893 { op : "bump", fieldname: "field1", value: "Default text option" }, { op : "bump", fieldname: "field1", value: "New value option" }, ], { - handleCompletion: function() { + handleCompletion() { sendAsyncMessage("Test:Resume"); }, }); diff --git a/toolkit/content/widgets/autocomplete.xml b/toolkit/content/widgets/autocomplete.xml index ac20f255a93f..92df64a34be0 100644 --- a/toolkit/content/widgets/autocomplete.xml +++ b/toolkit/content/widgets/autocomplete.xml @@ -618,16 +618,16 @@ _autocomplete: this, _kGlobalClipboard: Components.interfaces.nsIClipboard.kGlobalClipboard, supportsCommand: aCommand => aCommand == "cmd_paste", - doCommand: function(aCommand) { + doCommand(aCommand) { this._autocomplete._valueIsPasted = true; this._autocomplete.editor.paste(this._kGlobalClipboard); this._autocomplete._valueIsPasted = false; }, - isCommandEnabled: function(aCommand) { + isCommandEnabled(aCommand) { return this._autocomplete.editor.isSelectionEditable && this._autocomplete.editor.canPaste(this._kGlobalClipboard); }, - onEvent: function() {} + onEvent() {} }) ]]> @@ -2353,7 +2353,7 @@ extends="chrome://global/content/bindings/popup.xml#popup"> let [, type, params] = aUrl.match(/^moz-action:([^,]+),(.*)$/); let action = { - type: type, + type, }; try { diff --git a/toolkit/content/widgets/editor.xml b/toolkit/content/widgets/editor.xml index 637586dc2c74..0fd0eb24c26a 100644 --- a/toolkit/content/widgets/editor.xml +++ b/toolkit/content/widgets/editor.xml @@ -26,7 +26,7 @@ Date: Wed, 14 Dec 2016 17:16:01 -0500 Subject: [PATCH 095/229] Bug 1323100 - Use NS_NewNamedThread to name the proxy resolution thread. r=froydnj MozReview-Commit-ID: Fqxr4XmvS7I --HG-- extra : rebase_source : 70a09ac76919d104092e7c35ec3383191243f130 --- netwerk/base/nsPACMan.cpp | 18 +++--------------- netwerk/base/nsPACMan.h | 1 - 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/netwerk/base/nsPACMan.cpp b/netwerk/base/nsPACMan.cpp index 37d3e8b6bba2..43c569d8b3fd 100644 --- a/netwerk/base/nsPACMan.cpp +++ b/netwerk/base/nsPACMan.cpp @@ -742,27 +742,15 @@ nsPACMan::AsyncOnChannelRedirect(nsIChannel *oldChannel, nsIChannel *newChannel, return NS_OK; } -void -nsPACMan::NamePACThread() -{ - MOZ_ASSERT(!NS_IsMainThread(), "wrong thread"); - PR_SetCurrentThreadName("Proxy Resolution"); -} - nsresult nsPACMan::Init(nsISystemProxySettings *systemProxySettings) { mSystemProxySettings = systemProxySettings; - nsresult rv = NS_NewThread(getter_AddRefs(mPACThread), nullptr); - if (NS_FAILED(rv)) - return rv; + nsresult rv = + NS_NewNamedThread("ProxyResolution", getter_AddRefs(mPACThread)); - // don't check return value as it is not a big deal for this to fail. - mPACThread->Dispatch(NewRunnableMethod(this, &nsPACMan::NamePACThread), - nsIEventTarget::DISPATCH_NORMAL); - - return NS_OK; + return rv; } } // namespace net diff --git a/netwerk/base/nsPACMan.h b/netwerk/base/nsPACMan.h index def0843cb80a..df952ff9ee25 100644 --- a/netwerk/base/nsPACMan.h +++ b/netwerk/base/nsPACMan.h @@ -214,7 +214,6 @@ private: void PostProcessPendingQ(); void PostCancelPendingQ(nsresult); bool ProcessPending(); - void NamePACThread(); private: ProxyAutoConfig mPAC; From 11948b78b59ca5895b1e2e3d9f6c2a85f64793c5 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:26:48 +0100 Subject: [PATCH 096/229] Bug 1323100 - Use NS_NewNamedThread for IndexedDB threads. r=froydnj MozReview-Commit-ID: Do4l5QL2qSG --HG-- extra : rebase_source : 858b23dc85847849393e54709a68564d735bb638 --- dom/indexedDB/ActorsParent.cpp | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp index fc70257c2b81..1f84a832a0f0 100644 --- a/dom/indexedDB/ActorsParent.cpp +++ b/dom/indexedDB/ActorsParent.cpp @@ -5720,6 +5720,11 @@ public: return mSerialNumber; } + nsCString GetThreadName() const + { + return nsPrintfCString("IndexedDB #%lu", mSerialNumber); + } + private: ~ThreadRunnable() override; @@ -12571,7 +12576,10 @@ ConnectionPool::ScheduleTransaction(TransactionInfo* aTransactionInfo, RefPtr runnable = new ThreadRunnable(); nsCOMPtr newThread; - if (NS_SUCCEEDED(NS_NewThread(getter_AddRefs(newThread), runnable))) { + nsresult rv = + NS_NewNamedThread(runnable->GetThreadName(), + getter_AddRefs(newThread), runnable); + if (NS_SUCCEEDED(rv)) { MOZ_ASSERT(newThread); IDB_DEBUG_LOG(("ConnectionPool created thread %lu", @@ -13284,10 +13292,6 @@ nsresult ConnectionPool:: ThreadRunnable::Run() { -#ifdef MOZ_ENABLE_PROFILER_SPS - char stackTopGuess; -#endif // MOZ_ENABLE_PROFILER_SPS - MOZ_ASSERT(!IsOnBackgroundThread()); MOZ_ASSERT(mContinueRunning); @@ -13298,18 +13302,6 @@ ThreadRunnable::Run() mFirstRun = false; - { - // Scope for the thread name. Both PR_SetCurrentThreadName() and - // profiler_register_thread() copy the string so we don't need to keep it. - const nsPrintfCString threadName("IndexedDB #%lu", mSerialNumber); - - PR_SetCurrentThreadName(threadName.get()); - -#ifdef MOZ_ENABLE_PROFILER_SPS - profiler_register_thread(threadName.get(), &stackTopGuess); -#endif // MOZ_ENABLE_PROFILER_SPS - } - { // Scope for the profiler label. PROFILER_LABEL("IndexedDB", @@ -13351,10 +13343,6 @@ ThreadRunnable::Run() } } -#ifdef MOZ_ENABLE_PROFILER_SPS - profiler_unregister_thread(); -#endif // MOZ_ENABLE_PROFILER_SPS - return NS_OK; } From 615f9ce1dbf4da87eb356e7961358b8d4762b4c8 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:31:15 +0100 Subject: [PATCH 097/229] Bug 1323100 - Use NS_NewNamedThread for the Android Audio thread. r=froydnj MozReview-Commit-ID: IcKsOZCZVwB --HG-- extra : rebase_source : 2b5381faf2370792e715dfb20a7b274644f775f2 --- dom/plugins/base/android/ANPAudio.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/dom/plugins/base/android/ANPAudio.cpp b/dom/plugins/base/android/ANPAudio.cpp index bc47e8999e7a..dd4f0b29cdbe 100644 --- a/dom/plugins/base/android/ANPAudio.cpp +++ b/dom/plugins/base/android/ANPAudio.cpp @@ -122,8 +122,6 @@ public: NS_IMETHODIMP AudioRunnable::Run() { - PR_SetCurrentThreadName("Android Audio"); - JNIEnv* const jenv = mozilla::jni::GetEnvForThread(); mozilla::AutoLocalJNIFrame autoFrame(jenv, 2); @@ -321,7 +319,7 @@ anp_audio_start(ANPAudioTrack* s) RefPtr runnable = new AudioRunnable(s); nsCOMPtr thread; - NS_NewThread(getter_AddRefs(thread), runnable); + NS_NewNamedThread("Android Audio", getter_AddRefs(thread), runnable); } void From cb3be9a8e99c36ab95641340b5337b246082a521 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:32:39 +0100 Subject: [PATCH 098/229] Bug 1323100 - Use NS_NewNamedThread for the Link Monitor thread. r=froydnj MozReview-Commit-ID: ETOGkxMgknN --HG-- extra : rebase_source : 253161c0028458c79f162b5b4d8fd9d57f36944c --- netwerk/system/win32/nsNotifyAddrListener.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/netwerk/system/win32/nsNotifyAddrListener.cpp b/netwerk/system/win32/nsNotifyAddrListener.cpp index 5d1ec3a61fe1..bebbf4d0efc9 100644 --- a/netwerk/system/win32/nsNotifyAddrListener.cpp +++ b/netwerk/system/win32/nsNotifyAddrListener.cpp @@ -323,8 +323,6 @@ nsNotifyAddrListener::nextCoalesceWaitTime() NS_IMETHODIMP nsNotifyAddrListener::Run() { - PR_SetCurrentThreadName("Link Monitor"); - mStartTime = TimeStamp::Now(); calculateNetworkId(); @@ -421,7 +419,7 @@ nsNotifyAddrListener::Init(void) mCheckEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); NS_ENSURE_TRUE(mCheckEvent, NS_ERROR_OUT_OF_MEMORY); - rv = NS_NewThread(getter_AddRefs(mThread), this); + rv = NS_NewNamedThread("Link Monitor", getter_AddRefs(mThread), this); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; From 1874a5d84bc39ae888a644ca6b0c26c995596bb1 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:33:21 +0100 Subject: [PATCH 099/229] Bug 1323100 - Use NS_NewNamedThread for the Wifi Monitor thread. r=froydnj MozReview-Commit-ID: 25lwf8WdANT --HG-- extra : rebase_source : 3f9accf44b8fd9f269d2e2a6b46aa1c8440d3a9c --- netwerk/wifi/nsWifiMonitor.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/netwerk/wifi/nsWifiMonitor.cpp b/netwerk/wifi/nsWifiMonitor.cpp index 4613a107dc61..2c1885f2be78 100644 --- a/netwerk/wifi/nsWifiMonitor.cpp +++ b/netwerk/wifi/nsWifiMonitor.cpp @@ -84,7 +84,7 @@ NS_IMETHODIMP nsWifiMonitor::StartWatching(nsIWifiListener *aListener) } if (!mThread) { - rv = NS_NewThread(getter_AddRefs(mThread), this); + rv = NS_NewNamedThread("Wifi Monitor", getter_AddRefs(mThread), this); if (NS_FAILED(rv)) return rv; } @@ -155,8 +155,6 @@ NS_IMETHODIMP nsWifiMonitor::Run() { LOG(("@@@@@ wifi monitor run called\n")); - PR_SetCurrentThreadName("Wifi Monitor"); - nsresult rv = DoScan(); LOG(("@@@@@ wifi monitor run::doscan complete %x\n", rv)); From 448c1b51ef87d7c0a6981dc8755138a98c3227e0 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:34:36 +0100 Subject: [PATCH 100/229] Bug 1323100 - Use NS_NewNamedThread for the Filewatcher IO thread. r=froydnj MozReview-Commit-ID: 18qfXNx8BtJ --HG-- extra : rebase_source : 406d59b7e840466af49aa5197e12201764f3ed34 --- toolkit/components/filewatcher/NativeFileWatcherWin.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp index 8bb40bfd4d89..8e2ed8a7278e 100644 --- a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp +++ b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp @@ -1253,7 +1253,8 @@ NativeFileWatcherService::Init() // Start the IO worker thread. mWorkerIORunnable = new NativeFileWatcherIOTask(completionPort); - nsresult rv = NS_NewThread(getter_AddRefs(mIOThread), mWorkerIORunnable); + nsresult rv = NS_NewNamedThread("FileWatcher IO", getter_AddRefs(mIOThread), + mWorkerIORunnable); if (NS_FAILED(rv)) { FILEWATCHERLOG( "NativeFileWatcherIOTask::Init - Unable to create and dispatch the worker thread (%x).", @@ -1261,9 +1262,6 @@ NativeFileWatcherService::Init() return rv; } - // Set the name for the worker thread. - NS_SetThreadName(mIOThread, "FileWatcher IO"); - mIOCompletionPort = completionPort.forget(); return NS_OK; From 6e0ccc9df6a99d3c7eb99117a9e98d9e8376e1e4 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 22 Dec 2016 00:05:51 +0100 Subject: [PATCH 101/229] Bug 1323100 - Create a version of NS_NewNamedThread that accepts an nsACString. r=froydnj MozReview-Commit-ID: LhRjdzZeWCB --HG-- extra : rebase_source : 350ec2fbdc535a72eed34dc20d67765e4602da4b --- xpcom/glue/nsThreadUtils.h | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index 309729a1e99a..3644f48b1238 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -71,9 +71,8 @@ NS_NewThread(nsIThread** aResult, /** * Creates a named thread, otherwise the same as NS_NewThread */ -template inline nsresult -NS_NewNamedThread(const char (&aName)[LEN], +NS_NewNamedThread(const nsACString& aName, nsIThread** aResult, nsIRunnable* aInitialEvent = nullptr, uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) @@ -84,7 +83,7 @@ NS_NewNamedThread(const char (&aName)[LEN], if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - NS_SetThreadName(thread, aName); + NS_SetThreadName(thread, aName); if (aInitialEvent) { rv = thread->Dispatch(aInitialEvent, NS_DISPATCH_NORMAL); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Initial event dispatch failed"); @@ -95,6 +94,19 @@ NS_NewNamedThread(const char (&aName)[LEN], return rv; } +template +inline nsresult +NS_NewNamedThread(const char (&aName)[LEN], + nsIThread** aResult, + nsIRunnable* aInitialEvent = nullptr, + uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) +{ + static_assert(LEN <= 16, + "Thread name must be no more than 16 characters"); + return NS_NewNamedThread(nsDependentCString(aName, LEN - 1), + aResult, aInitialEvent, aStackSize); +} + /** * Get a reference to the current thread. * From 2d69e3878a0e23473a4ab1edc4c4674cbe02a935 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Mon, 12 Dec 2016 19:17:51 -0500 Subject: [PATCH 102/229] Bug 1323100 - Use NS_NewNamedThread in SingletonThreadHolder. r=froydnj MozReview-Commit-ID: Jcf5DfSrxrf --HG-- extra : rebase_source : 8ba5017efc93289570f4358fb1694692d935ba48 --- media/mtransport/nr_socket_prsock.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/media/mtransport/nr_socket_prsock.cpp b/media/mtransport/nr_socket_prsock.cpp index f22229df86f5..1aab40f8b478 100644 --- a/media/mtransport/nr_socket_prsock.cpp +++ b/media/mtransport/nr_socket_prsock.cpp @@ -212,10 +212,9 @@ public: nsrefcnt count = ++mUseCount; if (count == 1) { // idle -> in-use - nsresult rv = NS_NewThread(getter_AddRefs(mThread)); + nsresult rv = NS_NewNamedThread(mName, getter_AddRefs(mThread)); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && mThread, "Should successfully create mtransport I/O thread"); - NS_SetThreadName(mThread, mName); r_log(LOG_GENERIC,LOG_DEBUG,"Created wrapped SingletonThread %p", mThread.get()); } From 67fcd34390e2994b76217620712f3bd2e94b122b Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:27:18 +0100 Subject: [PATCH 103/229] Bug 1323100 - Use NS_NewNamedThread for CryptoTask threads. r=froydnj MozReview-Commit-ID: 6c6iDuGyE2X --HG-- extra : rebase_source : 91520bffd5d9bd31caa27fb52cf7bd9aac86a732 --- security/manager/ssl/CryptoTask.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/security/manager/ssl/CryptoTask.cpp b/security/manager/ssl/CryptoTask.cpp index 71b8ac88d5b3..2ffc1d93159a 100644 --- a/security/manager/ssl/CryptoTask.cpp +++ b/security/manager/ssl/CryptoTask.cpp @@ -31,13 +31,13 @@ CryptoTask::Dispatch(const nsACString& taskThreadName) } // Can't add 'this' as the event to run, since mThread may not be set yet - nsresult rv = NS_NewThread(getter_AddRefs(mThread), nullptr, - nsIThreadManager::DEFAULT_STACK_SIZE); + nsresult rv = NS_NewNamedThread(taskThreadName, getter_AddRefs(mThread), + nullptr, + nsIThreadManager::DEFAULT_STACK_SIZE); if (NS_FAILED(rv)) { return rv; } - NS_SetThreadName(mThread, taskThreadName); // Note: event must not null out mThread! return mThread->Dispatch(this, NS_DISPATCH_NORMAL); } From 1b72f37c9836043f016c8f4c152b9bb769edf8b5 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 11:43:50 +0100 Subject: [PATCH 104/229] Bug 1323100 - Assign names to all remaining threads that are created through NS_NewThread and create them using NS_NewNamedThread instead. r=froydnj MozReview-Commit-ID: 7W1dt2BBKJZ --HG-- extra : rebase_source : ad47978ef81d048a90b9803803201eee32974024 --- dom/gamepad/cocoa/CocoaGamepad.cpp | 5 +- dom/gamepad/windows/WindowsGamepad.cpp | 2 +- dom/media/FileBlockCache.cpp | 7 ++- .../android/AndroidMediaResourceServer.cpp | 2 +- dom/media/gtest/TestMP4Reader.cpp | 2 +- .../gonk/GonkGPSGeolocationProvider.cpp | 2 +- gfx/layers/LayerScope.cpp | 2 +- hal/gonk/GonkHal.cpp | 2 +- image/test/gtest/TestDecodeToSurface.cpp | 3 +- netwerk/base/BackgroundFileSaver.cpp | 2 +- netwerk/sctp/datachannel/DataChannel.cpp | 5 +- netwerk/test/TestFileInput2.cpp | 61 ++++++++++--------- .../test_service_init_background_thread.cpp | 2 +- .../url-classifier/tests/gtest/Common.cpp | 3 +- toolkit/crashreporter/nsExceptionHandler.cpp | 2 +- toolkit/identity/IdentityCryptoService.cpp | 5 +- toolkit/xre/nsUpdateDriver.cpp | 3 +- widget/windows/LSPAnnotator.cpp | 2 +- widget/windows/nsSound.cpp | 7 ++- xpcom/tests/gtest/TestPipes.cpp | 10 +-- .../tests/gtest/TestRacingServiceManager.cpp | 2 +- xpcom/tests/gtest/TestThreads.cpp | 11 ++-- xpcom/tests/gtest/TestTimers.cpp | 2 +- xpcom/threads/LazyIdleThread.cpp | 2 +- xpcom/threads/TimerThread.cpp | 3 +- 25 files changed, 84 insertions(+), 65 deletions(-) diff --git a/dom/gamepad/cocoa/CocoaGamepad.cpp b/dom/gamepad/cocoa/CocoaGamepad.cpp index e7c986e22a60..0000d616e223 100644 --- a/dom/gamepad/cocoa/CocoaGamepad.cpp +++ b/dom/gamepad/cocoa/CocoaGamepad.cpp @@ -541,8 +541,9 @@ DarwinGamepadService::StartupInternal() void DarwinGamepadService::Startup() { - Unused << NS_NewThread(getter_AddRefs(mMonitorThread), - new DarwinGamepadServiceStartupRunnable(this)); + Unused << NS_NewNamedThread("Gamepad", + getter_AddRefs(mMonitorThread), + new DarwinGamepadServiceStartupRunnable(this)); } void DarwinGamepadService::Shutdown() diff --git a/dom/gamepad/windows/WindowsGamepad.cpp b/dom/gamepad/windows/WindowsGamepad.cpp index 5f60fd0b79d8..7c2819ed05df 100644 --- a/dom/gamepad/windows/WindowsGamepad.cpp +++ b/dom/gamepad/windows/WindowsGamepad.cpp @@ -1065,7 +1065,7 @@ StartGamepadMonitoring() return; } sIsShutdown = false; - NS_NewThread(getter_AddRefs(gMonitorThread)); + NS_NewNamedThread("Gamepad", getter_AddRefs(gMonitorThread)); gMonitorThread->Dispatch(new StartWindowsGamepadServiceRunnable(), NS_DISPATCH_NORMAL); } diff --git a/dom/media/FileBlockCache.cpp b/dom/media/FileBlockCache.cpp index d85e6cd016de..16a3a0043f39 100644 --- a/dom/media/FileBlockCache.cpp +++ b/dom/media/FileBlockCache.cpp @@ -22,9 +22,10 @@ nsresult FileBlockCache::Open(PRFileDesc* aFD) } { MonitorAutoLock mon(mDataMonitor); - nsresult res = NS_NewThread(getter_AddRefs(mThread), - nullptr, - SharedThreadPool::kStackSize); + nsresult res = NS_NewNamedThread("FileBlockCache", + getter_AddRefs(mThread), + nullptr, + SharedThreadPool::kStackSize); mIsOpen = NS_SUCCEEDED(res); return res; } diff --git a/dom/media/android/AndroidMediaResourceServer.cpp b/dom/media/android/AndroidMediaResourceServer.cpp index bd76a8c68c49..f6ca13f5aa61 100644 --- a/dom/media/android/AndroidMediaResourceServer.cpp +++ b/dom/media/android/AndroidMediaResourceServer.cpp @@ -375,7 +375,7 @@ ResourceSocketListener::OnSocketAccepted(nsIServerSocket* aServ, if (NS_FAILED(rv)) return rv; nsCOMPtr thread; - rv = NS_NewThread(getter_AddRefs(thread)); + rv = NS_NewNamedThread("ServeResource", getter_AddRefs(thread)); if (NS_FAILED(rv)) return rv; nsCOMPtr event = new ServeResourceEvent(input.get(), output.get(), mServer); diff --git a/dom/media/gtest/TestMP4Reader.cpp b/dom/media/gtest/TestMP4Reader.cpp index f08f7a40da3c..2cf72681585c 100644 --- a/dom/media/gtest/TestMP4Reader.cpp +++ b/dom/media/gtest/TestMP4Reader.cpp @@ -44,7 +44,7 @@ public: void Init() { nsCOMPtr thread; nsCOMPtr r = NewRunnableMethod(this, &TestBinding::ReadMetadata); - nsresult rv = NS_NewThread(getter_AddRefs(thread), r); + nsresult rv = NS_NewNamedThread("ReadMetadata", getter_AddRefs(thread), r); EXPECT_EQ(NS_OK, rv); thread->Shutdown(); } diff --git a/dom/system/gonk/GonkGPSGeolocationProvider.cpp b/dom/system/gonk/GonkGPSGeolocationProvider.cpp index 9ce6ce2e5a30..b3336f02af12 100644 --- a/dom/system/gonk/GonkGPSGeolocationProvider.cpp +++ b/dom/system/gonk/GonkGPSGeolocationProvider.cpp @@ -556,7 +556,7 @@ GonkGPSGeolocationProvider::Startup() } if (!mInitThread) { - nsresult rv = NS_NewThread(getter_AddRefs(mInitThread)); + nsresult rv = NS_NewNamedThread("Gonk GPS", getter_AddRefs(mInitThread)); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/gfx/layers/LayerScope.cpp b/gfx/layers/LayerScope.cpp index a3b7778ef40f..55f87023d6d7 100644 --- a/gfx/layers/LayerScope.cpp +++ b/gfx/layers/LayerScope.cpp @@ -1569,7 +1569,7 @@ LayerScopeWebSocketManager::SocketHandler::CloseConnection() LayerScopeWebSocketManager::LayerScopeWebSocketManager() : mHandlerMutex("LayerScopeWebSocketManager::mHandlerMutex") { - NS_NewThread(getter_AddRefs(mDebugSenderThread)); + NS_NewNamedThread("LayerScope", getter_AddRefs(mDebugSenderThread)); mServerSocket = do_CreateInstance(NS_SERVERSOCKET_CONTRACTID); int port = gfxPrefs::LayerScopePort(); diff --git a/hal/gonk/GonkHal.cpp b/hal/gonk/GonkHal.cpp index 05d9295a225d..e2ca40fbbac6 100644 --- a/hal/gonk/GonkHal.cpp +++ b/hal/gonk/GonkHal.cpp @@ -395,7 +395,7 @@ EnsureVibratorThreadInitialized() sVibratorRunnable = new VibratorRunnable(); nsCOMPtr thread; - NS_NewThread(getter_AddRefs(thread), sVibratorRunnable); + NS_NewNamedThread("Gonk Vibrator", getter_AddRefs(thread), sVibratorRunnable); } } // namespace diff --git a/image/test/gtest/TestDecodeToSurface.cpp b/image/test/gtest/TestDecodeToSurface.cpp index bd52e75901c8..278cdb1fdc89 100644 --- a/image/test/gtest/TestDecodeToSurface.cpp +++ b/image/test/gtest/TestDecodeToSurface.cpp @@ -69,7 +69,8 @@ RunDecodeToSurface(const ImageTestCase& aTestCase) ASSERT_TRUE(inputStream != nullptr); nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), nullptr); + nsresult rv = + NS_NewNamedThread("DecodeToSurface", getter_AddRefs(thread), nullptr); ASSERT_TRUE(NS_SUCCEEDED(rv)); // We run the DecodeToSurface tests off-main-thread to ensure that diff --git a/netwerk/base/BackgroundFileSaver.cpp b/netwerk/base/BackgroundFileSaver.cpp index e4bc05826249..ee81113006b3 100644 --- a/netwerk/base/BackgroundFileSaver.cpp +++ b/netwerk/base/BackgroundFileSaver.cpp @@ -152,7 +152,7 @@ BackgroundFileSaver::Init() rv = NS_GetCurrentThread(getter_AddRefs(mControlThread)); NS_ENSURE_SUCCESS(rv, rv); - rv = NS_NewThread(getter_AddRefs(mWorkerThread)); + rv = NS_NewNamedThread("BgFileSaver", getter_AddRefs(mWorkerThread)); NS_ENSURE_SUCCESS(rv, rv); sThreadCount++; diff --git a/netwerk/sctp/datachannel/DataChannel.cpp b/netwerk/sctp/datachannel/DataChannel.cpp index 98810061bb24..b5adef05ab66 100644 --- a/netwerk/sctp/datachannel/DataChannel.cpp +++ b/netwerk/sctp/datachannel/DataChannel.cpp @@ -2326,8 +2326,9 @@ DataChannelConnection::SendBlob(uint16_t stream, nsIInputStream *aBlob) NS_ENSURE_TRUE(channel, 0); // Spawn a thread to send the data if (!mInternalIOThread) { - nsresult res = NS_NewThread(getter_AddRefs(mInternalIOThread)); - if (NS_FAILED(res)) { + nsresult rv = NS_NewNamedThread("DataChannel IO", + getter_AddRefs(mInternalIOThread)); + if (NS_FAILED(rv)) { return -1; } } diff --git a/netwerk/test/TestFileInput2.cpp b/netwerk/test/TestFileInput2.cpp index f51988010e20..a23437891b9d 100644 --- a/netwerk/test/TestFileInput2.cpp +++ b/netwerk/test/TestFileInput2.cpp @@ -315,7 +315,7 @@ NS_IMPL_ISUPPORTS(FileChannelWorker, nsIRunnable) //////////////////////////////////////////////////////////////////////////////// void -Test(CreateFun create, uint32_t count, +Test(CreateFun create, const char* name, uint32_t count, nsIFile* inDirSpec, nsIFile* outDirSpec, uint32_t bufSize) { nsresult rv; @@ -375,7 +375,8 @@ Test(CreateFun create, uint32_t count, bufSize); if (NS_FAILED(rv)) goto done; - rv = NS_NewThread(getter_AddRefs(thread), worker, 0, PR_JOINABLE_THREAD); + rv = NS_NewNamedThread(name, getter_AddRefs(thread), + worker, 0, PR_JOINABLE_THREAD); if (NS_FAILED(rv)) goto done; bool inserted = threads.InsertObjectAt(thread, i); @@ -433,42 +434,44 @@ main(int argc, char* argv[]) if (NS_FAILED(rv)) return rv; CreateFun create = FileChannelWorker::Create; + const char* name = "FileChannelWorker"; Test(create, 1, inDirFile, outDirFile, 16 * 1024); #if 1 printf("FileChannelWorker *****************************\n"); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); #endif create = FileSpecWorker::Create; + name = "FileSpecWorker"; printf("FileSpecWorker ********************************\n"); #if 1 - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); #endif #if 1 - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); #endif } // this scopes the nsCOMPtrs // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM diff --git a/storage/test/gtest/test_service_init_background_thread.cpp b/storage/test/gtest/test_service_init_background_thread.cpp index 022026cbaefd..e811e249702b 100644 --- a/storage/test/gtest/test_service_init_background_thread.cpp +++ b/storage/test/gtest/test_service_init_background_thread.cpp @@ -46,7 +46,7 @@ TEST(storage_service_init_background_thread_DeathTest, Test) do_check_true(event); nsCOMPtr thread; - do_check_success(NS_NewThread(getter_AddRefs(thread))); + do_check_success(NS_NewNamedThread("StorageService", getter_AddRefs(thread))); do_check_success(thread->Dispatch(event, NS_DISPATCH_NORMAL)); diff --git a/toolkit/components/url-classifier/tests/gtest/Common.cpp b/toolkit/components/url-classifier/tests/gtest/Common.cpp index b5f024b38e41..b2c9bad8bc41 100644 --- a/toolkit/components/url-classifier/tests/gtest/Common.cpp +++ b/toolkit/components/url-classifier/tests/gtest/Common.cpp @@ -14,7 +14,8 @@ template void RunTestInNewThread(Function&& aFunction) { nsCOMPtr r = NS_NewRunnableFunction(mozilla::Forward(aFunction)); nsCOMPtr testingThread; - nsresult rv = NS_NewThread(getter_AddRefs(testingThread), r); + nsresult rv = + NS_NewNamedThread("Testing Thread", getter_AddRefs(testingThread), r); ASSERT_EQ(rv, NS_OK); testingThread->Shutdown(); } diff --git a/toolkit/crashreporter/nsExceptionHandler.cpp b/toolkit/crashreporter/nsExceptionHandler.cpp index 9fd69f504830..5922b9b80c2d 100644 --- a/toolkit/crashreporter/nsExceptionHandler.cpp +++ b/toolkit/crashreporter/nsExceptionHandler.cpp @@ -3609,7 +3609,7 @@ InjectCrashReporterIntoProcess(DWORD processID, InjectorCrashCallback* cb) OOPInit(); if (!sInjectorThread) { - if (NS_FAILED(NS_NewThread(&sInjectorThread))) + if (NS_FAILED(NS_NewNamedThread("CrashRep Inject", &sInjectorThread))) return; } diff --git a/toolkit/identity/IdentityCryptoService.cpp b/toolkit/identity/IdentityCryptoService.cpp index 0aeaed2f3f94..5ad3fd19c9d4 100644 --- a/toolkit/identity/IdentityCryptoService.cpp +++ b/toolkit/identity/IdentityCryptoService.cpp @@ -205,7 +205,8 @@ IdentityCryptoService::GenerateKeyPair( nsCOMPtr r = new KeyGenRunnable(keyType, callback); nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), r); + nsresult rv = NS_NewNamedThread("GenerateKeyPair", getter_AddRefs(thread), + r); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -309,7 +310,7 @@ KeyPair::Sign(const nsACString & textToSign, callback); nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), r); + nsresult rv = NS_NewNamedThread("KeyPair Sign", getter_AddRefs(thread), r); return rv; } diff --git a/toolkit/xre/nsUpdateDriver.cpp b/toolkit/xre/nsUpdateDriver.cpp index ce60c652187a..8c1bb9bca843 100644 --- a/toolkit/xre/nsUpdateDriver.cpp +++ b/toolkit/xre/nsUpdateDriver.cpp @@ -1246,7 +1246,8 @@ nsUpdateProcessor::ProcessUpdate(nsIUpdate* aUpdate) MOZ_ASSERT(NS_IsMainThread(), "not main thread"); nsCOMPtr r = NewRunnableMethod(this, &nsUpdateProcessor::StartStagedUpdate); - return NS_NewThread(getter_AddRefs(mProcessWatcher), r); + return NS_NewNamedThread("Update Watcher", getter_AddRefs(mProcessWatcher), + r); } diff --git a/widget/windows/LSPAnnotator.cpp b/widget/windows/LSPAnnotator.cpp index 5b0c1d14b484..5e8f465116e1 100644 --- a/widget/windows/LSPAnnotator.cpp +++ b/widget/windows/LSPAnnotator.cpp @@ -151,7 +151,7 @@ void LSPAnnotate() nsCOMPtr thread; nsCOMPtr runnable = do_QueryObject(new LSPAnnotationGatherer()); - NS_NewThread(getter_AddRefs(thread), runnable); + NS_NewNamedThread("LSP Annotate", getter_AddRefs(thread), runnable); } } // namespace crashreporter diff --git a/widget/windows/nsSound.cpp b/widget/windows/nsSound.cpp index 5635f8356b9d..a22e048df3ef 100644 --- a/widget/windows/nsSound.cpp +++ b/widget/windows/nsSound.cpp @@ -241,7 +241,9 @@ NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias) return NS_OK; nsCOMPtr player = new nsSoundPlayer(this, aSoundAlias); NS_ENSURE_TRUE(player, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = NS_NewThread(getter_AddRefs(mPlayerThread), player); + nsresult rv = + NS_NewNamedThread("PlaySystemSound", getter_AddRefs(mPlayerThread), + player); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } @@ -299,7 +301,8 @@ NS_IMETHODIMP nsSound::PlayEventSound(uint32_t aEventId) nsCOMPtr player = new nsSoundPlayer(this, sound); NS_ENSURE_TRUE(player, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = NS_NewThread(getter_AddRefs(mPlayerThread), player); + nsresult rv = + NS_NewNamedThread("PlayEventSound", getter_AddRefs(mPlayerThread), player); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } diff --git a/xpcom/tests/gtest/TestPipes.cpp b/xpcom/tests/gtest/TestPipes.cpp index 87b923008258..5bf31c94197e 100644 --- a/xpcom/tests/gtest/TestPipes.cpp +++ b/xpcom/tests/gtest/TestPipes.cpp @@ -107,7 +107,7 @@ TestPipe(nsIInputStream* in, nsIOutputStream* out) nsresult rv; nsCOMPtr thread; - rv = NS_NewThread(getter_AddRefs(thread), receiver); + rv = NS_NewNamedThread("TestPipe", getter_AddRefs(thread), receiver); if (NS_FAILED(rv)) return rv; uint32_t total = 0; @@ -225,7 +225,8 @@ TestShortWrites(nsIInputStream* in, nsIOutputStream* out) nsresult rv; nsCOMPtr thread; - rv = NS_NewThread(getter_AddRefs(thread), receiver); + rv = NS_NewNamedThread("TestShortWrites", getter_AddRefs(thread), + receiver); if (NS_FAILED(rv)) return rv; uint32_t total = 0; @@ -330,14 +331,15 @@ TEST(Pipes, ChainedPipes) if (pump == nullptr) return; nsCOMPtr thread; - rv = NS_NewThread(getter_AddRefs(thread), pump); + rv = NS_NewNamedThread("ChainedPipePump", getter_AddRefs(thread), pump); if (NS_FAILED(rv)) return; RefPtr receiver = new nsReceiver(in2); if (receiver == nullptr) return; nsCOMPtr receiverThread; - rv = NS_NewThread(getter_AddRefs(receiverThread), receiver); + rv = NS_NewNamedThread("ChainedPipeRecv", getter_AddRefs(receiverThread), + receiver); if (NS_FAILED(rv)) return; uint32_t total = 0; diff --git a/xpcom/tests/gtest/TestRacingServiceManager.cpp b/xpcom/tests/gtest/TestRacingServiceManager.cpp index b0638db02f48..1309083ed853 100644 --- a/xpcom/tests/gtest/TestRacingServiceManager.cpp +++ b/xpcom/tests/gtest/TestRacingServiceManager.cpp @@ -255,7 +255,7 @@ TEST(RacingServiceManager, Test) // Run the classID test nsCOMPtr newThread; - rv = NS_NewThread(getter_AddRefs(newThread), runnable); + rv = NS_NewNamedThread("RacingServMan", getter_AddRefs(newThread), runnable); ASSERT_TRUE(NS_SUCCEEDED(rv)); { diff --git a/xpcom/tests/gtest/TestThreads.cpp b/xpcom/tests/gtest/TestThreads.cpp index 4f6055dce9b9..4d47f2649415 100644 --- a/xpcom/tests/gtest/TestThreads.cpp +++ b/xpcom/tests/gtest/TestThreads.cpp @@ -49,7 +49,7 @@ TEST(Threads, Main) EXPECT_TRUE(event); nsCOMPtr runner; - rv = NS_NewThread(getter_AddRefs(runner), event); + rv = NS_NewNamedThread("TestThreadsMain", getter_AddRefs(runner), event); EXPECT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr thread; @@ -112,7 +112,8 @@ TEST(Threads, Stress) for (k = 0; k < threads; k++) { nsCOMPtr t; - nsresult rv = NS_NewThread(getter_AddRefs(t), new nsStressRunner(k)); + nsresult rv = NS_NewNamedThread("StressRunner", getter_AddRefs(t), + new nsStressRunner(k)); EXPECT_TRUE(NS_SUCCEEDED(rv)); NS_ADDREF(array[k] = t); } @@ -169,7 +170,8 @@ public: { mozilla::MonitorAutoLock lock(*gBeginAsyncShutdownMonitor); - rv = NS_NewThread(getter_AddRefs(t), new AsyncShutdownPreparer()); + rv = NS_NewNamedThread("AsyncShutdownPr", getter_AddRefs(t), + new AsyncShutdownPreparer()); EXPECT_TRUE(NS_SUCCEEDED(rv)); lock.Wait(); @@ -221,7 +223,8 @@ TEST(Threads, AsyncShutdown) { mozilla::MonitorAutoLock lock(*gAsyncShutdownReadyMonitor); - rv = NS_NewThread(getter_AddRefs(t), new AsyncShutdownWaiter()); + rv = NS_NewNamedThread("AsyncShutdownWt", getter_AddRefs(t), + new AsyncShutdownWaiter()); EXPECT_TRUE(NS_SUCCEEDED(rv)); lock.Wait(); diff --git a/xpcom/tests/gtest/TestTimers.cpp b/xpcom/tests/gtest/TestTimers.cpp index fe7520ab1018..524e1e8b3f7b 100644 --- a/xpcom/tests/gtest/TestTimers.cpp +++ b/xpcom/tests/gtest/TestTimers.cpp @@ -31,7 +31,7 @@ class AutoTestThread public: AutoTestThread() { nsCOMPtr newThread; - nsresult rv = NS_NewThread(getter_AddRefs(newThread)); + nsresult rv = NS_NewNamedThread("AutoTestThread", getter_AddRefs(newThread)); if (NS_FAILED(rv)) return; diff --git a/xpcom/threads/LazyIdleThread.cpp b/xpcom/threads/LazyIdleThread.cpp index 527cc681962f..b6218e959292 100644 --- a/xpcom/threads/LazyIdleThread.cpp +++ b/xpcom/threads/LazyIdleThread.cpp @@ -169,7 +169,7 @@ LazyIdleThread::EnsureThread() return NS_ERROR_UNEXPECTED; } - rv = NS_NewThread(getter_AddRefs(mThread), runnable); + rv = NS_NewNamedThread("Lazy Idle", getter_AddRefs(mThread), runnable); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/xpcom/threads/TimerThread.cpp b/xpcom/threads/TimerThread.cpp index 8536f0395ab7..da4bc6edba26 100644 --- a/xpcom/threads/TimerThread.cpp +++ b/xpcom/threads/TimerThread.cpp @@ -323,7 +323,8 @@ TimerThread::Init() if (mInitInProgress.exchange(true) == false) { // We hold on to mThread to keep the thread alive. - nsresult rv = NS_NewThread(getter_AddRefs(mThread), this); + nsresult rv = + NS_NewNamedThread("Timer Thread", getter_AddRefs(mThread), this); if (NS_FAILED(rv)) { mThread = nullptr; } else { From 70d7bf2304882716460030b147735ed94aa5f1f2 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 22 Dec 2016 00:38:41 +0100 Subject: [PATCH 105/229] Bug 1323100 - Create nsThreadPoolNaming::GetNextThreadName. r=froydnj MozReview-Commit-ID: F0ZFFa5VkAW --HG-- extra : rebase_source : 9ebc1118e30bf841af2a2d1df3ada4d31e4035bd --- xpcom/glue/nsThreadUtils.cpp | 13 ++++++++++--- xpcom/glue/nsThreadUtils.h | 11 +++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index 994f71de7d25..7374f54d9251 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -440,13 +440,20 @@ NS_GetCurrentThread() #endif // nsThreadPoolNaming +nsCString +nsThreadPoolNaming::GetNextThreadName(const nsACString& aPoolName) +{ + nsCString name(aPoolName); + name.AppendLiteral(" #"); + name.AppendInt(++mCounter, 10); // The counter is declared as atomic + return name; +} + void nsThreadPoolNaming::SetThreadPoolName(const nsACString& aPoolName, nsIThread* aThread) { - nsCString name(aPoolName); - name.AppendLiteral(" #"); - name.AppendInt(++mCounter, 10); // The counter is declared as volatile + nsCString name = GetNextThreadName(aPoolName); if (aThread) { // Set on the target thread diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index 3644f48b1238..d9671b160fb2 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -1037,6 +1037,17 @@ class nsThreadPoolNaming public: nsThreadPoolNaming() : mCounter(0) {} + /** + * Returns a thread name as " #" and increments the counter. + */ + nsCString GetNextThreadName(const nsACString& aPoolName); + + template + nsCString GetNextThreadName(const char (&aPoolName)[LEN]) + { + return GetNextThreadName(nsDependentCString(aPoolName, LEN - 1)); + } + /** * Creates and sets next thread name as " #" * on the specified thread. If no thread is specified (aThread From 882a11ecd0d476be0407214c53bbe1deac73227c Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:20:15 +0100 Subject: [PATCH 106/229] Bug 1323100 - Use nsThreadPoolNaming::GetNextThreadName and NS_NewNamedThread for the mozStorage thread. r=froydnj MozReview-Commit-ID: 145CjwiQawB --HG-- extra : rebase_source : 9403849151907d2437f6874f8a7bd4d539394417 --- storage/mozStorageConnection.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/storage/mozStorageConnection.cpp b/storage/mozStorageConnection.cpp index 2ad50fb51d21..6129ac4442a1 100644 --- a/storage/mozStorageConnection.cpp +++ b/storage/mozStorageConnection.cpp @@ -589,14 +589,13 @@ Connection::getAsyncExecutionTarget() return nullptr; if (!mAsyncExecutionThread) { - nsresult rv = ::NS_NewThread(getter_AddRefs(mAsyncExecutionThread)); + static nsThreadPoolNaming naming; + nsresult rv = NS_NewNamedThread(naming.GetNextThreadName("mozStorage"), + getter_AddRefs(mAsyncExecutionThread)); if (NS_FAILED(rv)) { NS_WARNING("Failed to create async thread."); return nullptr; } - static nsThreadPoolNaming naming; - naming.SetThreadPoolName(NS_LITERAL_CSTRING("mozStorage"), - mAsyncExecutionThread); } #ifdef DEBUG From 67aee994bd3f452347e17e627b5eb60302d11e18 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:20:48 +0100 Subject: [PATCH 107/229] Bug 1323100 - Use nsThreadPoolNaming::GetNextThreadName and NS_NewNamedThread in the DecodePool. r=froydnj MozReview-Commit-ID: CAbaAe0bKe8 --HG-- extra : rebase_source : bc0db71ff4dd1031ea74c292b2162e0ac8f302f2 --- image/DecodePool.cpp | 27 +++++++-------------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/image/DecodePool.cpp b/image/DecodePool.cpp index 9aa3d58229f4..8053b2f9d19d 100644 --- a/image/DecodePool.cpp +++ b/image/DecodePool.cpp @@ -60,14 +60,6 @@ public: , mShuttingDown(false) { } - /// Initialize the current thread for use by the decode pool. - void InitCurrentThread() - { - MOZ_ASSERT(!NS_IsMainThread()); - - mThreadNaming.SetThreadPoolName(NS_LITERAL_CSTRING("ImgDecoder")); - } - /// Shut down the provided decode pool thread. static void ShutdownThread(nsIThread* aThisThread) { @@ -135,6 +127,12 @@ public: } while (true); } + nsresult CreateThread(nsIThread** aThread, nsIRunnable* aInitialEvent) + { + return NS_NewNamedThread(mThreadNaming.GetNextThreadName("ImgDecoder"), + aThread, aInitialEvent); + } + private: ~DecodePoolImpl() { } @@ -166,22 +164,11 @@ public: NS_IMETHOD Run() override { -#ifdef MOZ_ENABLE_PROFILER_SPS - char stackBaseGuess; // Need to be the first variable of main loop function. -#endif // MOZ_ENABLE_PROFILER_SPS - MOZ_ASSERT(!NS_IsMainThread()); - mImpl->InitCurrentThread(); - nsCOMPtr thisThread; nsThreadManager::get().GetCurrentThread(getter_AddRefs(thisThread)); -#ifdef MOZ_ENABLE_PROFILER_SPS - // InitCurrentThread() has assigned the thread name. - profiler_register_thread(PR_GetThreadName(PR_GetCurrentThread()), &stackBaseGuess); -#endif // MOZ_ENABLE_PROFILER_SPS - do { Work work = mImpl->PopWork(); switch (work.mType) { @@ -272,7 +259,7 @@ DecodePool::DecodePool() for (uint32_t i = 0 ; i < limit ; ++i) { nsCOMPtr worker = new DecodePoolWorker(mImpl); nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), worker); + nsresult rv = mImpl->CreateThread(getter_AddRefs(thread), worker); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && thread, "Should successfully create image decoding threads"); mThreads.AppendElement(Move(thread)); From 4361d7a6e073f79e9d39bef38b6441a59d4d3295 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 22 Dec 2016 00:14:30 +0100 Subject: [PATCH 108/229] Bug 1323100 - Use nsThreadPoolNaming::GetNextThreadName and NS_NewNamedThread in nsThreadPool. r=froydnj MozReview-Commit-ID: 6IB5yvJtAQm --HG-- extra : rebase_source : d4d9bf2dab3e75821e931a11fa0a16f6ee1eb970 --- xpcom/threads/nsThreadPool.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/xpcom/threads/nsThreadPool.cpp b/xpcom/threads/nsThreadPool.cpp index 241fad39dcc2..f1d849ed1a85 100644 --- a/xpcom/threads/nsThreadPool.cpp +++ b/xpcom/threads/nsThreadPool.cpp @@ -104,8 +104,9 @@ nsThreadPool::PutEvent(already_AddRefed aEvent, uint32_t aFlags) } nsCOMPtr thread; - nsThreadManager::get().NewThread(0, stackSize, getter_AddRefs(thread)); - if (NS_WARN_IF(!thread)) { + nsresult rv = NS_NewNamedThread(mThreadNaming.GetNextThreadName(mName), + getter_AddRefs(thread), nullptr, stackSize); + if (NS_WARN_IF(NS_FAILED(rv))) { return NS_ERROR_UNEXPECTED; } @@ -152,8 +153,6 @@ nsThreadPool::ShutdownThread(nsIThread* aThread) NS_IMETHODIMP nsThreadPool::Run() { - mThreadNaming.SetThreadPoolName(mName); - LOG(("THRD-P(%p) enter %s\n", this, mName.BeginReading())); nsCOMPtr current; From c3fde6edb807e01ed9ceb1b8ac6912656753e5f0 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:21:34 +0100 Subject: [PATCH 109/229] Bug 1323100 - Use nsThreadPoolNaming::GetNextThreadName for the DNS resolver thread. r=froydnj MozReview-Commit-ID: EQvKoIIorKG --HG-- extra : rebase_source : a386139905d17c7c5bcfb9dad887dbb9b82597fd --- netwerk/dns/nsHostResolver.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index f2e26cadd4eb..78cdfebf0909 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -1438,7 +1438,9 @@ nsHostResolver::ThreadFunc(void *arg) LOG(("DNS lookup thread - starting execution.\n")); static nsThreadPoolNaming naming; - naming.SetThreadPoolName(NS_LITERAL_CSTRING("DNS Resolver")); + nsCString name = naming.GetNextThreadName("DNS Resolver"); + + PR_SetCurrentThreadName(name.BeginReading()); #if defined(RES_RETRY_ON_FAILURE) nsResState rs; From 2643eefe78d692f8caeaabba3dadf4dd0cbef78b Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Mon, 19 Dec 2016 16:16:50 +0100 Subject: [PATCH 110/229] Bug 1323100 - Remove nsThreadPoolNaming::SetThreadPoolName because it's now unused. r=froydnj MozReview-Commit-ID: CYgF2NGD6pt --HG-- extra : rebase_source : cc09c212670d845c00629903b477674806618699 extra : source : 1cd63b3998c4a4c2ef5c59eee24bd344b2d3bc6d --- xpcom/glue/nsThreadUtils.cpp | 17 ----------------- xpcom/glue/nsThreadUtils.h | 8 -------- 2 files changed, 25 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index 7374f54d9251..a6d570a534c0 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -448,23 +448,6 @@ nsThreadPoolNaming::GetNextThreadName(const nsACString& aPoolName) name.AppendInt(++mCounter, 10); // The counter is declared as atomic return name; } - -void -nsThreadPoolNaming::SetThreadPoolName(const nsACString& aPoolName, - nsIThread* aThread) -{ - nsCString name = GetNextThreadName(aPoolName); - - if (aThread) { - // Set on the target thread - NS_SetThreadName(aThread, name); - } else { - // Set on the current thread -#ifndef XPCOM_GLUE_AVOID_NSPR - PR_SetCurrentThreadName(name.BeginReading()); -#endif - } -} // nsAutoLowPriorityIO nsAutoLowPriorityIO::nsAutoLowPriorityIO() diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index d9671b160fb2..87d9dbcd3076 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -1048,14 +1048,6 @@ public: return GetNextThreadName(nsDependentCString(aPoolName, LEN - 1)); } - /** - * Creates and sets next thread name as " #" - * on the specified thread. If no thread is specified (aThread - * is null) then the name is synchronously set on the current thread. - */ - void SetThreadPoolName(const nsACString& aPoolName, - nsIThread* aThread = nullptr); - private: mozilla::Atomic mCounter; From c9adaf222f6e776f3b3aa7797df57387a6427bb2 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 15:10:20 +0100 Subject: [PATCH 111/229] Bug 1323100 - Add nsThreadManager::NewNamedThread API. r=froydnj The point of this exercise is to make the thread name available in the thread func of the thread, so that we can register the thread with the profiler from the very start of its lifetime, and so that registration and unregistration can be inside the same function. MozReview-Commit-ID: DiiMKUQVr55 --HG-- extra : rebase_source : aa1d0c19250765c80c8e8ae59d2752bb4ad7eeac --- xpcom/threads/nsIThreadManager.idl | 14 ++++++++++++++ xpcom/threads/nsThread.cpp | 26 +++++++++++++++++++++++--- xpcom/threads/nsThread.h | 4 ++-- xpcom/threads/nsThreadManager.cpp | 10 +++++++++- 4 files changed, 48 insertions(+), 6 deletions(-) diff --git a/xpcom/threads/nsIThreadManager.idl b/xpcom/threads/nsIThreadManager.idl index 9b4fc126f9b3..fa0f037c2712 100644 --- a/xpcom/threads/nsIThreadManager.idl +++ b/xpcom/threads/nsIThreadManager.idl @@ -35,6 +35,20 @@ interface nsIThreadManager : nsISupports */ nsIThread newThread(in unsigned long creationFlags, [optional] in unsigned long stackSize); + /** + * Create a new thread (a global, user PRThread) with the specified name. + * + * @param name + * The name of the thread. Passing an empty name is equivalent to + * calling newThread(0, stackSize), i.e. the thread will not be named. + * @param stackSize + * Number of bytes to reserve for the thread's stack. + * + * @returns + * The newly created nsIThread object. + */ + [noscript] nsIThread newNamedThread(in ACString name, [optional] in unsigned long stackSize); + /** * Get the nsIThread object (if any) corresponding to the given PRThread. * This method returns null if there is no corresponding nsIThread. diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp index 6c0f898240ae..fd45e79c4ea7 100644 --- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -432,15 +432,30 @@ SetupCurrentThreadForChaosMode() } } +namespace { + +struct ThreadInitData { + nsThread* thread; + const nsACString& name; +}; + +} + /*static*/ void nsThread::ThreadFunc(void* aArg) { using mozilla::ipc::BackgroundChild; - nsThread* self = static_cast(aArg); // strong reference + ThreadInitData* initData = static_cast(aArg); + nsThread* self = initData->thread; // strong reference + self->mThread = PR_GetCurrentThread(); SetupCurrentThreadForChaosMode(); + if (initData->name.Length() > 0) { + PR_SetCurrentThreadName(initData->name.BeginReading()); + } + // Inform the ThreadManager nsThreadManager::get().RegisterCurrentThread(*self); @@ -455,6 +470,9 @@ nsThread::ThreadFunc(void* aArg) return; } } + + initData = nullptr; // clear before unblocking nsThread::Init + event->Run(); // unblocks nsThread::Init event = nullptr; @@ -628,7 +646,7 @@ nsThread::~nsThread() } nsresult -nsThread::Init() +nsThread::Init(const nsACString& aName) { // spawn thread and wait until it is fully setup RefPtr startup = new nsThreadStartupEvent(); @@ -639,8 +657,10 @@ nsThread::Init() mShutdownRequired = true; + ThreadInitData initData = { this, aName }; + // ThreadFunc is responsible for setting mThread - if (!PR_CreateThread(PR_USER_THREAD, ThreadFunc, this, + if (!PR_CreateThread(PR_USER_THREAD, ThreadFunc, &initData, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, mStackSize)) { NS_RELEASE_THIS(); diff --git a/xpcom/threads/nsThread.h b/xpcom/threads/nsThread.h index 836123747aad..fd8209b0b5c4 100644 --- a/xpcom/threads/nsThread.h +++ b/xpcom/threads/nsThread.h @@ -48,8 +48,8 @@ public: nsThread(MainThreadFlag aMainThread, uint32_t aStackSize); - // Initialize this as a wrapper for a new PRThread. - nsresult Init(); + // Initialize this as a wrapper for a new PRThread, and optionally give it a name. + nsresult Init(const nsACString& aName = NS_LITERAL_CSTRING("")); // Initialize this as a wrapper for the current PRThread. nsresult InitCurrentThread(); diff --git a/xpcom/threads/nsThreadManager.cpp b/xpcom/threads/nsThreadManager.cpp index d1eb84b8f84c..217e557a8274 100644 --- a/xpcom/threads/nsThreadManager.cpp +++ b/xpcom/threads/nsThreadManager.cpp @@ -248,6 +248,14 @@ NS_IMETHODIMP nsThreadManager::NewThread(uint32_t aCreationFlags, uint32_t aStackSize, nsIThread** aResult) +{ + return NewNamedThread(NS_LITERAL_CSTRING(""), aStackSize, aResult); +} + +NS_IMETHODIMP +nsThreadManager::NewNamedThread(const nsACString& aName, + uint32_t aStackSize, + nsIThread** aResult) { // Note: can be called from arbitrary threads @@ -257,7 +265,7 @@ nsThreadManager::NewThread(uint32_t aCreationFlags, } RefPtr thr = new nsThread(nsThread::NOT_MAIN_THREAD, aStackSize); - nsresult rv = thr->Init(); // Note: blocks until the new thread has been set up + nsresult rv = thr->Init(aName); // Note: blocks until the new thread has been set up if (NS_FAILED(rv)) { return rv; } From b289e8b1362a3defb7ac9c27397e3f97b472ed96 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:18:22 +0100 Subject: [PATCH 112/229] Bug 1323100 - Make NS_NewNamedThread use nsThreadManager::NewNamedThread. r=froydnj MozReview-Commit-ID: 7e6l1A89he9 --HG-- extra : rebase_source : 0bbd888a568937710d3bb6cd5b856063e3405ae6 --- xpcom/glue/nsThreadUtils.cpp | 17 +++++++++++++---- xpcom/glue/nsThreadUtils.h | 21 ++------------------- 2 files changed, 15 insertions(+), 23 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index a6d570a534c0..8f9cb092e15b 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -95,13 +95,16 @@ IncrementalRunnable::SetDeadline(TimeStamp aDeadline) //----------------------------------------------------------------------------- nsresult -NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) +NS_NewNamedThread(const nsACString& aName, + nsIThread** aResult, + nsIRunnable* aEvent, + uint32_t aStackSize) { nsCOMPtr thread; #ifdef MOZILLA_INTERNAL_API nsresult rv = - nsThreadManager::get().nsThreadManager::NewThread(0, aStackSize, - getter_AddRefs(thread)); + nsThreadManager::get().nsThreadManager::NewNamedThread(aName, aStackSize, + getter_AddRefs(thread)); #else nsresult rv; nsCOMPtr mgr = @@ -110,7 +113,7 @@ NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) return rv; } - rv = mgr->NewThread(0, aStackSize, getter_AddRefs(thread)); + rv = mgr->NewNamedThread(aName, aStackSize, getter_AddRefs(thread)); #endif if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -128,6 +131,12 @@ NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) return NS_OK; } +nsresult +NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) +{ + return NS_NewNamedThread(NS_LITERAL_CSTRING(""), aResult, aEvent, aStackSize); +} + nsresult NS_GetCurrentThread(nsIThread** aResult) { diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index 87d9dbcd3076..a398e6c91c8f 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -71,28 +71,11 @@ NS_NewThread(nsIThread** aResult, /** * Creates a named thread, otherwise the same as NS_NewThread */ -inline nsresult +extern nsresult NS_NewNamedThread(const nsACString& aName, nsIThread** aResult, nsIRunnable* aInitialEvent = nullptr, - uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) -{ - // Hold a ref while dispatching the initial event to match NS_NewThread() - nsCOMPtr thread; - nsresult rv = NS_NewThread(getter_AddRefs(thread), nullptr, aStackSize); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - NS_SetThreadName(thread, aName); - if (aInitialEvent) { - rv = thread->Dispatch(aInitialEvent, NS_DISPATCH_NORMAL); - NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Initial event dispatch failed"); - } - - *aResult = nullptr; - thread.swap(*aResult); - return rv; -} + uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE); template inline nsresult From ce1d36ccc8abb9ddeb029a80533fdacf35dabfbc Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 20 Dec 2016 14:43:11 +0100 Subject: [PATCH 113/229] Bug 1323100 - Remove NS_SetThreadName which is now unused. r=froydnj MozReview-Commit-ID: 7je5PhV1TsU --HG-- extra : rebase_source : 74a4339b3c7338e85caf9287b225d75a556b2938 --- xpcom/glue/nsThreadUtils.cpp | 50 ------------------------------------ xpcom/glue/nsThreadUtils.h | 18 ------------- 2 files changed, 68 deletions(-) diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index 8f9cb092e15b..d2f5c88bcb6f 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -390,56 +390,6 @@ NS_ProcessNextEvent(nsIThread* aThread, bool aMayWait) return NS_SUCCEEDED(aThread->ProcessNextEvent(aMayWait, &val)) && val; } -#ifndef XPCOM_GLUE_AVOID_NSPR - -namespace { - -class nsNameThreadRunnable final : public nsIRunnable -{ - ~nsNameThreadRunnable() {} - -public: - explicit nsNameThreadRunnable(const nsACString& aName) : mName(aName) {} - - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSIRUNNABLE - -protected: - const nsCString mName; -}; - -NS_IMPL_ISUPPORTS(nsNameThreadRunnable, nsIRunnable) - -NS_IMETHODIMP -nsNameThreadRunnable::Run() -{ - PR_SetCurrentThreadName(mName.BeginReading()); - return NS_OK; -} - -} // namespace - -void -NS_SetThreadName(nsIThread* aThread, const nsACString& aName) -{ - if (!aThread) { - return; - } - - aThread->Dispatch(new nsNameThreadRunnable(aName), - nsIEventTarget::DISPATCH_NORMAL); -} - -#else // !XPCOM_GLUE_AVOID_NSPR - -void -NS_SetThreadName(nsIThread* aThread, const nsACString& aName) -{ - // No NSPR, no love. -} - -#endif - #ifdef MOZILLA_INTERNAL_API nsIThread* NS_GetCurrentThread() diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index a398e6c91c8f..82ed1294cdfc 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -32,24 +32,6 @@ // These methods are alternatives to the methods on nsIThreadManager, provided // for convenience. -/** - * Set name of the target thread. This operation is asynchronous. - */ -extern void NS_SetThreadName(nsIThread* aThread, const nsACString& aName); - -/** - * Static length version of the above function checking length of the - * name at compile time. - */ -template -inline void -NS_SetThreadName(nsIThread* aThread, const char (&aName)[LEN]) -{ - static_assert(LEN <= 16, - "Thread name must be no more than 16 characters"); - NS_SetThreadName(aThread, nsDependentCString(aName)); -} - /** * Create a new thread, and optionally provide an initial event for the thread. * From 34808aee092ba614c691c8414f20cafff042a5d7 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 14 Dec 2016 19:50:11 -0500 Subject: [PATCH 114/229] Bug 1323100 - Register named threads with the profiler. r=froydnj MozReview-Commit-ID: FbE4BTcnfEh --HG-- extra : rebase_source : 4690ebcaf3b71008e9a4d5db31486683dcdb3f91 --- xpcom/threads/nsThread.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp index fd45e79c4ea7..119e0c788471 100644 --- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -38,6 +38,7 @@ #include "nsIIncrementalRunnable.h" #include "nsThreadSyncDispatch.h" #include "LeakRefPtr.h" +#include "GeckoProfiler.h" #ifdef MOZ_CRASHREPORTER #include "nsServiceManagerUtils.h" @@ -446,6 +447,8 @@ nsThread::ThreadFunc(void* aArg) { using mozilla::ipc::BackgroundChild; + char stackTop; + ThreadInitData* initData = static_cast(aArg); nsThread* self = initData->thread; // strong reference @@ -454,6 +457,8 @@ nsThread::ThreadFunc(void* aArg) if (initData->name.Length() > 0) { PR_SetCurrentThreadName(initData->name.BeginReading()); + + profiler_register_thread(initData->name.BeginReading(), &stackTop); } // Inform the ThreadManager @@ -519,6 +524,8 @@ nsThread::ThreadFunc(void* aArg) // Inform the threadmanager that this thread is going away nsThreadManager::get().UnregisterCurrentThread(*self); + profiler_unregister_thread(); + // Dispatch shutdown ACK NotNull context = WrapNotNull(self->mShutdownContext); From 61b02e4fd79c06fa6b3d581fe5b22ee3d8e7b48d Mon Sep 17 00:00:00 2001 From: Jeff Gilbert Date: Thu, 29 Dec 2016 00:08:39 -0800 Subject: [PATCH 115/229] Bug 1326159 - Update TF buffer restrictions. - r=daoshengmu Update conformance2/buffers/bound-buffer-size-change-test.html to top-of-tree 2.0.0. MozReview-Commit-ID: CgfP70Y0wul --- dom/canvas/WebGL2Context.cpp | 2 + dom/canvas/WebGL2ContextBuffers.cpp | 21 ++++- dom/canvas/WebGL2ContextTransformFeedback.cpp | 8 ++ dom/canvas/WebGLBuffer.cpp | 2 + dom/canvas/WebGLBuffer.h | 32 ++++++- dom/canvas/WebGLContext.cpp | 46 ++-------- dom/canvas/WebGLContext.h | 14 +-- dom/canvas/WebGLContextBuffers.cpp | 85 ++++++++++--------- dom/canvas/WebGLContextDraw.cpp | 56 +++++++++--- dom/canvas/WebGLContextGL.cpp | 11 ++- dom/canvas/WebGLContextVertexArray.cpp | 7 ++ dom/canvas/WebGLProgram.cpp | 24 +++++- dom/canvas/WebGLProgram.h | 1 + dom/canvas/WebGLTransformFeedback.cpp | 35 +++----- dom/canvas/WebGLTransformFeedback.h | 9 +- dom/canvas/WebGLVertexArray.cpp | 15 ++++ dom/canvas/WebGLVertexArray.h | 8 +- dom/canvas/WebGLVertexAttribData.cpp | 3 +- .../bound-buffer-size-change-test.html | 4 - 19 files changed, 231 insertions(+), 152 deletions(-) diff --git a/dom/canvas/WebGL2Context.cpp b/dom/canvas/WebGL2Context.cpp index 9c659ca7da5d..f9a1eba4bff9 100644 --- a/dom/canvas/WebGL2Context.cpp +++ b/dom/canvas/WebGL2Context.cpp @@ -163,6 +163,8 @@ WebGLContext::InitWebGL2(FailureReason* const out_failReason) mDefaultTransformFeedback = new WebGLTransformFeedback(this, 0); mBoundTransformFeedback = mDefaultTransformFeedback; + gl->fGenTransformFeedbacks(1, &mEmptyTFO); + //// if (!gl->IsGLES()) { diff --git a/dom/canvas/WebGL2ContextBuffers.cpp b/dom/canvas/WebGL2ContextBuffers.cpp index efa18b42bc78..f59fa08b836e 100644 --- a/dom/canvas/WebGL2ContextBuffers.cpp +++ b/dom/canvas/WebGL2ContextBuffers.cpp @@ -132,11 +132,26 @@ WebGL2Context::GetBufferSubData(GLenum target, GLintptr srcByteOffset, const ScopedLazyBind readBind(gl, target, buffer); if (byteLen) { - const auto mappedBytes = gl->fMapBufferRange(target, srcByteOffset, glByteLen, + const bool isTF = (target == LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER); + GLenum mapTarget = target; + if (isTF) { + gl->fBindTransformFeedback(LOCAL_GL_TRANSFORM_FEEDBACK, mEmptyTFO); + gl->fBindBuffer(LOCAL_GL_ARRAY_BUFFER, buffer->mGLName); + mapTarget = LOCAL_GL_ARRAY_BUFFER; + } + + const auto mappedBytes = gl->fMapBufferRange(mapTarget, srcByteOffset, glByteLen, LOCAL_GL_MAP_READ_BIT); - // Warning: Possibly shared memory. See bug 1225033. memcpy(bytes, mappedBytes, byteLen); - gl->fUnmapBuffer(target); + gl->fUnmapBuffer(mapTarget); + + if (isTF) { + const GLuint vbo = (mBoundArrayBuffer ? mBoundArrayBuffer->mGLName : 0); + gl->fBindBuffer(LOCAL_GL_ARRAY_BUFFER, vbo); + const GLuint tfo = (mBoundTransformFeedback ? mBoundTransformFeedback->mGLName + : 0); + gl->fBindTransformFeedback(LOCAL_GL_TRANSFORM_FEEDBACK, tfo); + } } } diff --git a/dom/canvas/WebGL2ContextTransformFeedback.cpp b/dom/canvas/WebGL2ContextTransformFeedback.cpp index ee2f99341535..48bdf756c97c 100644 --- a/dom/canvas/WebGL2ContextTransformFeedback.cpp +++ b/dom/canvas/WebGL2ContextTransformFeedback.cpp @@ -81,10 +81,18 @@ WebGL2Context::BindTransformFeedback(GLenum target, WebGLTransformFeedback* tf) //// + if (mBoundTransformFeedback) { + mBoundTransformFeedback->AddBufferBindCounts(-1); + } + mBoundTransformFeedback = (tf ? tf : mDefaultTransformFeedback); MakeContextCurrent(); gl->fBindTransformFeedback(target, mBoundTransformFeedback->mGLName); + + if (mBoundTransformFeedback) { + mBoundTransformFeedback->AddBufferBindCounts(+1); + } } void diff --git a/dom/canvas/WebGLBuffer.cpp b/dom/canvas/WebGLBuffer.cpp index 4558a4603f9e..f202c9950d1c 100644 --- a/dom/canvas/WebGLBuffer.cpp +++ b/dom/canvas/WebGLBuffer.cpp @@ -18,6 +18,8 @@ WebGLBuffer::WebGLBuffer(WebGLContext* webgl, GLuint buf) , mContent(Kind::Undefined) , mUsage(LOCAL_GL_STATIC_DRAW) , mByteLength(0) + , mTFBindCount(0) + , mNonTFBindCount(0) { mContext->mBuffers.insertBack(this); } diff --git a/dom/canvas/WebGLBuffer.h b/dom/canvas/WebGLBuffer.h index c60bc9b5d81f..883712aad451 100644 --- a/dom/canvas/WebGLBuffer.h +++ b/dom/canvas/WebGLBuffer.h @@ -26,7 +26,6 @@ class WebGLBuffer final friend class WebGLContext; friend class WebGL2Context; friend class WebGLTexture; - friend class WebGLTransformFeedback; public: enum class Kind { @@ -66,6 +65,35 @@ public: bool ValidateCanBindToTarget(const char* funcName, GLenum target); void BufferData(GLenum target, size_t size, const void* data, GLenum usage); + //// + + static void AddBindCount(GLenum target, WebGLBuffer* buffer, int8_t addVal) { + if (!buffer) + return; + + if (target == LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER) { + MOZ_ASSERT_IF(addVal < 0, buffer->mTFBindCount >= size_t(-addVal)); + buffer->mTFBindCount += addVal; + } else { + MOZ_ASSERT_IF(addVal < 0, buffer->mNonTFBindCount >= size_t(-addVal)); + buffer->mNonTFBindCount += addVal; + } + } + + static void SetSlot(GLenum target, WebGLBuffer* newBuffer, + WebGLRefPtr* const out_slot) + { + WebGLBuffer* const oldBuffer = *out_slot; + AddBindCount(target, oldBuffer, -1); + AddBindCount(target, newBuffer, +1); + *out_slot = newBuffer; + } + + bool IsBoundForTF() const { return bool(mTFBindCount); } + bool IsBoundForNonTF() const { return bool(mNonTFBindCount); } + + //// + const GLenum mGLName; NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLBuffer) @@ -78,6 +106,8 @@ protected: GLenum mUsage; size_t mByteLength; UniquePtr mCache; + size_t mTFBindCount; + size_t mNonTFBindCount; }; } // namespace mozilla diff --git a/dom/canvas/WebGLContext.cpp b/dom/canvas/WebGLContext.cpp index 3c0fd978c395..3d8ae73699fd 100644 --- a/dom/canvas/WebGLContext.cpp +++ b/dom/canvas/WebGLContext.cpp @@ -120,7 +120,7 @@ WebGLContext::WebGLContext() , mMaxFetchedInstances(0) , mLayerIsMirror(false) , mBypassShaderValidation(false) - , mBuffersForUB_Dirty(true) + , mEmptyTFO(0) , mContextLossHandler(this) , mNeedsFakeNoAlpha(false) , mNeedsFakeNoDepth(false) @@ -250,7 +250,6 @@ WebGLContext::DestroyResourcesAndContext() mQuerySlot_TimeElapsed = nullptr; mIndexedUniformBufferBindings.clear(); - OnUBIndexedBindingsChanged(); ////// @@ -268,6 +267,13 @@ WebGLContext::DestroyResourcesAndContext() ////// + if (mEmptyTFO) { + gl->fDeleteTransformFeedbacks(1, &mEmptyTFO); + mEmptyTFO = 0; + } + + ////// + mFakeBlack_2D_0000 = nullptr; mFakeBlack_2D_0001 = nullptr; mFakeBlack_CubeMap_0000 = nullptr; @@ -2385,42 +2391,6 @@ WebGLContext::ValidateArrayBufferView(const char* funcName, return true; } -//// - -const decltype(WebGLContext::mBuffersForUB)& -WebGLContext::BuffersForUB() const -{ - if (mBuffersForUB_Dirty) { - mBuffersForUB.clear(); - for (const auto& cur : mIndexedUniformBufferBindings) { - if (cur.mBufferBinding) { - mBuffersForUB.insert(cur.mBufferBinding.get()); - } - } - mBuffersForUB_Dirty = false; - } - return mBuffersForUB; -} - -//// - -bool -WebGLContext::ValidateForNonTransformFeedback(const char* funcName, WebGLBuffer* buffer) -{ - if (!mBoundTransformFeedback) - return true; - - const auto& buffersForTF = mBoundTransformFeedback->BuffersForTF(); - if (buffersForTF.count(buffer)) { - ErrorInvalidOperation("%s: Specified WebGLBuffer is currently bound for transform" - " feedback.", - funcName); - return false; - } - - return true; -} - //////////////////////////////////////////////////////////////////////////////// // XPCOM goop diff --git a/dom/canvas/WebGLContext.h b/dom/canvas/WebGLContext.h index 2b657f95a26b..0648c52c4d9f 100644 --- a/dom/canvas/WebGLContext.h +++ b/dom/canvas/WebGLContext.h @@ -1654,8 +1654,6 @@ protected: return true; } - bool ValidateForNonTransformFeedback(const char* funcName, WebGLBuffer* buffer); - public: template bool ValidateNonNull(const char* funcName, const dom::Nullable& maybe) { @@ -1882,17 +1880,9 @@ protected: //////////////////////////////////// -private: - mutable bool mBuffersForUB_Dirty; - mutable std::set mBuffersForUB; - -public: - void OnUBIndexedBindingsChanged() const { mBuffersForUB_Dirty = true; } - const decltype(mBuffersForUB)& BuffersForUB() const; - - //////////////////////////////////// - protected: + GLuint mEmptyTFO; + // Generic Vertex Attributes // Though CURRENT_VERTEX_ATTRIB is listed under "Vertex Shader State" in the spec // state tables, this isn't vertex shader /object/ state. This array is merely state diff --git a/dom/canvas/WebGLContextBuffers.cpp b/dom/canvas/WebGLContextBuffers.cpp index 9fd108632abf..af506c01c1be 100644 --- a/dom/canvas/WebGLContextBuffers.cpp +++ b/dom/canvas/WebGLContextBuffers.cpp @@ -75,8 +75,27 @@ WebGLContext::ValidateBufferSelection(const char* funcName, GLenum target) return nullptr; } - if (!ValidateForNonTransformFeedback(funcName, buffer.get())) - return nullptr; + if (target == LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER) { + if (mBoundTransformFeedback->IsActiveAndNotPaused()) { + ErrorInvalidOperation("%s: Cannot select TRANSFORM_FEEDBACK_BUFFER when" + " transform feedback is active and unpaused.", + funcName); + return nullptr; + } + if (buffer->IsBoundForNonTF()) { + ErrorInvalidOperation("%s: Specified WebGLBuffer is currently bound for" + " non-transform-feedback.", + funcName); + return nullptr; + } + } else { + if (buffer->IsBoundForTF()) { + ErrorInvalidOperation("%s: Specified WebGLBuffer is currently bound for" + " transform feedback.", + funcName); + return nullptr; + } + } return buffer.get(); } @@ -132,7 +151,7 @@ WebGLContext::BindBuffer(GLenum target, WebGLBuffer* buffer) gl->MakeCurrent(); gl->fBindBuffer(target, buffer ? buffer->mGLName : 0); - *slot = buffer; + WebGLBuffer::SetSlot(target, buffer, slot); if (buffer) { buffer->SetContentAfterBind(target); } @@ -201,23 +220,14 @@ WebGLContext::BindBufferBase(GLenum target, GLuint index, WebGLBuffer* buffer) //// - *genericBinding = buffer; - indexedBinding->mBufferBinding = buffer; + WebGLBuffer::SetSlot(target, buffer, genericBinding); + WebGLBuffer::SetSlot(target, buffer, &indexedBinding->mBufferBinding); indexedBinding->mRangeStart = 0; indexedBinding->mRangeSize = 0; if (buffer) { buffer->SetContentAfterBind(target); } - - switch (target) { - case LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER: - mBoundTransformFeedback->OnIndexedBindingsChanged(); - break; - case LOCAL_GL_UNIFORM: - OnUBIndexedBindingsChanged(); - break; - } } void @@ -296,23 +306,14 @@ WebGLContext::BindBufferRange(GLenum target, GLuint index, WebGLBuffer* buffer, //// - *genericBinding = buffer; - indexedBinding->mBufferBinding = buffer; + WebGLBuffer::SetSlot(target, buffer, genericBinding); + WebGLBuffer::SetSlot(target, buffer, &indexedBinding->mBufferBinding); indexedBinding->mRangeStart = offset; indexedBinding->mRangeSize = size; if (buffer) { buffer->SetContentAfterBind(target); } - - switch (target) { - case LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER: - mBoundTransformFeedback->OnIndexedBindingsChanged(); - break; - case LOCAL_GL_UNIFORM: - OnUBIndexedBindingsChanged(); - break; - } } //////////////////////////////////////// @@ -477,39 +478,41 @@ WebGLContext::DeleteBuffer(WebGLBuffer* buffer) //// - const auto fnClearIfBuffer = [&](WebGLRefPtr& bindPoint) { + const auto fnClearIfBuffer = [&](GLenum target, WebGLRefPtr& bindPoint) { if (bindPoint == buffer) { - bindPoint = nullptr; + WebGLBuffer::SetSlot(target, nullptr, &bindPoint); } }; - fnClearIfBuffer(mBoundArrayBuffer); - fnClearIfBuffer(mBoundVertexArray->mElementArrayBuffer); + fnClearIfBuffer(0, mBoundArrayBuffer); + fnClearIfBuffer(0, mBoundVertexArray->mElementArrayBuffer); + + for (auto& cur : mBoundVertexArray->mAttribs) { + fnClearIfBuffer(0, cur.mBuf); + } // WebGL binding points if (IsWebGL2()) { - fnClearIfBuffer(mBoundCopyReadBuffer); - fnClearIfBuffer(mBoundCopyWriteBuffer); - fnClearIfBuffer(mBoundPixelPackBuffer); - fnClearIfBuffer(mBoundPixelUnpackBuffer); - fnClearIfBuffer(mBoundUniformBuffer); - fnClearIfBuffer(mBoundTransformFeedback->mGenericBufferBinding); + fnClearIfBuffer(0, mBoundCopyReadBuffer); + fnClearIfBuffer(0, mBoundCopyWriteBuffer); + fnClearIfBuffer(0, mBoundPixelPackBuffer); + fnClearIfBuffer(0, mBoundPixelUnpackBuffer); + fnClearIfBuffer(0, mBoundUniformBuffer); + fnClearIfBuffer(LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER, + mBoundTransformFeedback->mGenericBufferBinding); if (!mBoundTransformFeedback->mIsActive) { for (auto& binding : mBoundTransformFeedback->mIndexedBindings) { - fnClearIfBuffer(binding.mBufferBinding); + fnClearIfBuffer(LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER, + binding.mBufferBinding); } } for (auto& binding : mIndexedUniformBufferBindings) { - fnClearIfBuffer(binding.mBufferBinding); + fnClearIfBuffer(0, binding.mBufferBinding); } } - for (auto& cur : mBoundVertexArray->mAttribs) { - fnClearIfBuffer(cur.mBuf); - } - //// buffer->RequestDelete(); diff --git a/dom/canvas/WebGLContextDraw.cpp b/dom/canvas/WebGLContextDraw.cpp index f895fdced0bf..04cd6bfcac46 100644 --- a/dom/canvas/WebGLContextDraw.cpp +++ b/dom/canvas/WebGLContextDraw.cpp @@ -356,6 +356,7 @@ public: // Check UBO sizes. const auto& linkInfo = mWebGL->mActiveProgramLinkInfo; + for (const auto& cur : linkInfo->uniformBlocks) { const auto& dataSize = cur->mDataSize; const auto& binding = cur->mBinding; @@ -374,18 +375,10 @@ public: *out_error = true; return; } - } - //// - - const auto& tfo = mWebGL->mBoundTransformFeedback; - if (tfo) { - const auto& buffersForTF = tfo->BuffersForTF(); - const auto& buffersForUB = mWebGL->BuffersForUB(); - if (DoSetsIntersect(buffersForTF, buffersForUB)) { - mWebGL->ErrorInvalidOperation("%s: At least one WebGLBuffer is bound for" - " both transform feedback and as a uniform" - " buffer.", + if (binding->mBufferBinding->IsBoundForTF()) { + mWebGL->ErrorInvalidOperation("%s: Buffer for uniform block is bound or" + " in use for transform feedback.", funcName); *out_error = true; return; @@ -394,7 +387,38 @@ public: //// - for (const auto& progAttrib : mWebGL->mActiveProgramLinkInfo->attribs) { + const auto& tfo = mWebGL->mBoundTransformFeedback; + if (tfo && tfo->IsActiveAndNotPaused()) { + uint32_t numUsed; + switch (linkInfo->transformFeedbackBufferMode) { + case LOCAL_GL_INTERLEAVED_ATTRIBS: + numUsed = 1; + break; + + case LOCAL_GL_SEPARATE_ATTRIBS: + numUsed = linkInfo->transformFeedbackVaryings.size(); + break; + + default: + MOZ_CRASH(); + } + + for (uint32_t i = 0; i < numUsed; ++i) { + const auto& buffer = tfo->mIndexedBindings[i].mBufferBinding; + if (buffer->IsBoundForNonTF()) { + mWebGL->ErrorInvalidOperation("%s: Transform feedback varying %u's" + " buffer is bound for" + " non-transform-feedback.", + funcName, i); + *out_error = true; + return; + } + } + } + + //// + + for (const auto& progAttrib : linkInfo->attribs) { const auto& loc = progAttrib.mLoc; if (loc == -1) continue; @@ -404,6 +428,14 @@ public: GLenum attribDataBaseType; if (attribData.mEnabled) { attribDataBaseType = attribData.BaseType(); + + if (attribData.mBuf->IsBoundForTF()) { + mWebGL->ErrorInvalidOperation("%s: Vertex attrib %u's buffer is bound" + " or in use for transform feedback.", + funcName, loc); + *out_error = true; + return; + } } else { attribDataBaseType = mWebGL->mGenericVertexAttribTypes[loc]; } diff --git a/dom/canvas/WebGLContextGL.cpp b/dom/canvas/WebGLContextGL.cpp index 25a54445ca95..dfd52184f869 100644 --- a/dom/canvas/WebGLContextGL.cpp +++ b/dom/canvas/WebGLContextGL.cpp @@ -592,12 +592,19 @@ WebGLContext::GetAttribLocation(const WebGLProgram& prog, const nsAString& name) JS::Value WebGLContext::GetBufferParameter(GLenum target, GLenum pname) { + const char funcName[] = "getBufferParameter"; if (IsContextLost()) return JS::NullValue(); - const auto& buffer = ValidateBufferSelection("getBufferParameter", target); - if (!buffer) + const auto& slot = ValidateBufferSlot(funcName, target); + if (!slot) return JS::NullValue(); + const auto& buffer = *slot; + + if (!buffer) { + ErrorInvalidOperation("%s: Buffer for `target` is null.", funcName); + return JS::NullValue(); + } switch (pname) { case LOCAL_GL_BUFFER_SIZE: diff --git a/dom/canvas/WebGLContextVertexArray.cpp b/dom/canvas/WebGLContextVertexArray.cpp index e9f16d3f75e2..5b7a10f220c7 100644 --- a/dom/canvas/WebGLContextVertexArray.cpp +++ b/dom/canvas/WebGLContextVertexArray.cpp @@ -25,6 +25,10 @@ WebGLContext::BindVertexArray(WebGLVertexArray* array) MakeContextCurrent(); + if (mBoundVertexArray) { + mBoundVertexArray->AddBufferBindCounts(-1); + } + if (array == nullptr) { array = mDefaultVertexArray; } @@ -32,6 +36,9 @@ WebGLContext::BindVertexArray(WebGLVertexArray* array) array->BindVertexArray(); MOZ_ASSERT(mBoundVertexArray == array); + if (mBoundVertexArray) { + mBoundVertexArray->AddBufferBindCounts(+1); + } } already_AddRefed diff --git a/dom/canvas/WebGLProgram.cpp b/dom/canvas/WebGLProgram.cpp index 01c7f8d617e9..73567b8c4ed7 100644 --- a/dom/canvas/WebGLProgram.cpp +++ b/dom/canvas/WebGLProgram.cpp @@ -435,6 +435,7 @@ QueryProgramInfo(WebGLProgram* prog, gl::GLContext* gl) webgl::LinkedProgramInfo::LinkedProgramInfo(WebGLProgram* prog) : prog(prog) + , transformFeedbackBufferMode(prog->mNextLink_TransformFeedbackBufferMode) { } webgl::LinkedProgramInfo::~LinkedProgramInfo() @@ -697,21 +698,35 @@ WebGLProgram::GetProgramParameter(GLenum pname) const if (mContext->IsWebGL2()) { switch (pname) { case LOCAL_GL_ACTIVE_UNIFORM_BLOCKS: - return JS::Int32Value(GetProgramiv(gl, mGLName, pname)); + if (!IsLinked()) + return JS::NumberValue(0); + return JS::NumberValue(LinkInfo()->uniformBlocks.size()); case LOCAL_GL_TRANSFORM_FEEDBACK_VARYINGS: - return JS::Int32Value(mNextLink_TransformFeedbackVaryings.size()); + if (!IsLinked()) + return JS::NumberValue(0); + return JS::NumberValue(LinkInfo()->transformFeedbackVaryings.size()); case LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER_MODE: - return JS::Int32Value(mNextLink_TransformFeedbackBufferMode); + if (!IsLinked()) + return JS::NumberValue(LOCAL_GL_INTERLEAVED_ATTRIBS); + return JS::NumberValue(LinkInfo()->transformFeedbackBufferMode); } } switch (pname) { case LOCAL_GL_ATTACHED_SHADERS: + return JS::NumberValue( int(bool(mVertShader.get())) + int(bool(mFragShader)) ); + case LOCAL_GL_ACTIVE_UNIFORMS: + if (!IsLinked()) + return JS::NumberValue(0); + return JS::NumberValue(LinkInfo()->uniforms.size()); + case LOCAL_GL_ACTIVE_ATTRIBUTES: - return JS::Int32Value(GetProgramiv(gl, mGLName, pname)); + if (!IsLinked()) + return JS::NumberValue(0); + return JS::NumberValue(LinkInfo()->attribs.size()); case LOCAL_GL_DELETE_STATUS: return JS::BooleanValue(IsDeleteRequested()); @@ -725,6 +740,7 @@ WebGLProgram::GetProgramParameter(GLenum pname) const if (gl->WorkAroundDriverBugs()) return JS::BooleanValue(true); #endif + // Todo: Implement this in our code. return JS::BooleanValue(bool(GetProgramiv(gl, mGLName, pname))); default: diff --git a/dom/canvas/WebGLProgram.h b/dom/canvas/WebGLProgram.h index 14a6ba86b2fa..0f08d3df3eb9 100644 --- a/dom/canvas/WebGLProgram.h +++ b/dom/canvas/WebGLProgram.h @@ -87,6 +87,7 @@ struct LinkedProgramInfo final ////// WebGLProgram* const prog; + const GLenum transformFeedbackBufferMode; std::vector attribs; std::vector uniforms; // Owns its contents. diff --git a/dom/canvas/WebGLTransformFeedback.cpp b/dom/canvas/WebGLTransformFeedback.cpp index 6e5c0b745444..feec581eaaef 100644 --- a/dom/canvas/WebGLTransformFeedback.cpp +++ b/dom/canvas/WebGLTransformFeedback.cpp @@ -17,7 +17,6 @@ WebGLTransformFeedback::WebGLTransformFeedback(WebGLContext* webgl, GLuint tf) , mIndexedBindings(webgl->mGLMaxTransformFeedbackSeparateAttribs) , mIsPaused(false) , mIsActive(false) - , mBuffersForTF_Dirty(true) { mContext->mTransformFeedbacks.insertBack(this); } @@ -37,28 +36,6 @@ WebGLTransformFeedback::Delete() removeFrom(mContext->mTransformFeedbacks); } -//// - -const decltype(WebGLTransformFeedback::mBuffersForTF)& -WebGLTransformFeedback::BuffersForTF() const -{ - // The generic bind point cannot incur undefined read/writes because otherwise it - // would be impossible to read back from this. The spec implies that readback from - // the TRANSFORM_FEEDBACK target is possible, just not simultaneously with being - // "bound or in use for transform feedback". - // Therefore, only the indexed bindings of the TFO count. - if (mBuffersForTF_Dirty) { - mBuffersForTF.clear(); - for (const auto& cur : mIndexedBindings) { - if (cur.mBufferBinding) { - mBuffersForTF.insert(cur.mBufferBinding.get()); - } - } - mBuffersForTF_Dirty = false; - } - return mBuffersForTF; -} - //////////////////////////////////////// void @@ -209,6 +186,18 @@ WebGLTransformFeedback::ResumeTransformFeedback() //////////////////////////////////////// +void +WebGLTransformFeedback::AddBufferBindCounts(int8_t addVal) const +{ + const GLenum target = LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER; + WebGLBuffer::AddBindCount(target, mGenericBufferBinding.get(), addVal); + for (const auto& binding : mIndexedBindings) { + WebGLBuffer::AddBindCount(target, binding.mBufferBinding.get(), addVal); + } +} + +//////////////////////////////////////// + JSObject* WebGLTransformFeedback::WrapObject(JSContext* cx, JS::Handle givenProto) { diff --git a/dom/canvas/WebGLTransformFeedback.h b/dom/canvas/WebGLTransformFeedback.h index d97484a99b47..aa57372a5956 100644 --- a/dom/canvas/WebGLTransformFeedback.h +++ b/dom/canvas/WebGLTransformFeedback.h @@ -17,6 +17,7 @@ class WebGLTransformFeedback final , public WebGLRefCountedObject , public LinkedListElement { + friend class ScopedDrawHelper; friend class ScopedDrawWithTransformFeedback; friend class WebGLContext; friend class WebGL2Context; @@ -36,9 +37,6 @@ private: MOZ_INIT_OUTSIDE_CTOR size_t mActive_VertPosition; MOZ_INIT_OUTSIDE_CTOR size_t mActive_VertCapacity; - mutable bool mBuffersForTF_Dirty; - mutable std::set mBuffersForTF; - public: WebGLTransformFeedback(WebGLContext* webgl, GLuint tf); private: @@ -52,10 +50,9 @@ public: WebGLContext* GetParentObject() const { return mContext; } virtual JSObject* WrapObject(JSContext*, JS::Handle) override; - //// + bool IsActiveAndNotPaused() const { return mIsActive && !mIsPaused; } - void OnIndexedBindingsChanged() const { mBuffersForTF_Dirty = true; } - const decltype(mBuffersForTF)& BuffersForTF() const; + void AddBufferBindCounts(int8_t addVal) const; // GL Funcs void BeginTransformFeedback(GLenum primMode); diff --git a/dom/canvas/WebGLVertexArray.cpp b/dom/canvas/WebGLVertexArray.cpp index 180135b6880b..e0c30ab51eb9 100644 --- a/dom/canvas/WebGLVertexArray.cpp +++ b/dom/canvas/WebGLVertexArray.cpp @@ -28,6 +28,21 @@ WebGLVertexArray::WebGLVertexArray(WebGLContext* webgl) mContext->mVertexArrays.insertBack(this); } +WebGLVertexArray::~WebGLVertexArray() +{ + MOZ_ASSERT(IsDeleted()); +} + +void +WebGLVertexArray::AddBufferBindCounts(int8_t addVal) const +{ + const GLenum target = 0; // Anything non-TF is fine. + WebGLBuffer::AddBindCount(target, mElementArrayBuffer.get(), addVal); + for (const auto& attrib : mAttribs) { + WebGLBuffer::AddBindCount(target, attrib.mBuf.get(), addVal); + } +} + WebGLVertexArray* WebGLVertexArray::Create(WebGLContext* webgl) { diff --git a/dom/canvas/WebGLVertexArray.h b/dom/canvas/WebGLVertexArray.h index 516fbaa1bd43..74f714af13b9 100644 --- a/dom/canvas/WebGLVertexArray.h +++ b/dom/canvas/WebGLVertexArray.h @@ -10,7 +10,6 @@ #include "mozilla/LinkedList.h" #include "nsWrapperCache.h" -#include "WebGLBuffer.h" #include "WebGLObjectModel.h" #include "WebGLStrongTypes.h" #include "WebGLVertexAttribData.h" @@ -48,12 +47,11 @@ public: GLuint GLName() const { return mGLName; } + void AddBufferBindCounts(int8_t addVal) const; + protected: explicit WebGLVertexArray(WebGLContext* webgl); - - virtual ~WebGLVertexArray() { - MOZ_ASSERT(IsDeleted()); - } + virtual ~WebGLVertexArray(); virtual void GenVertexArray() = 0; virtual void BindVertexArrayImpl() = 0; diff --git a/dom/canvas/WebGLVertexAttribData.cpp b/dom/canvas/WebGLVertexAttribData.cpp index e62014c3bc01..b5aee18e5c42 100644 --- a/dom/canvas/WebGLVertexAttribData.cpp +++ b/dom/canvas/WebGLVertexAttribData.cpp @@ -6,6 +6,7 @@ #include "WebGLVertexAttribData.h" #include "GLContext.h" +#include "WebGLBuffer.h" namespace mozilla { @@ -71,7 +72,7 @@ WebGLVertexAttribData::VertexAttribPointer(bool integerFunc, WebGLBuffer* buf, uint32_t stride, uint64_t byteOffset) { mIntegerFunc = integerFunc; - mBuf = buf; + WebGLBuffer::SetSlot(0, buf, &mBuf); mType = type; mBaseType = AttribPointerBaseType(integerFunc, type); mSize = size; diff --git a/dom/canvas/test/webgl-conf/checkout/conformance2/buffers/bound-buffer-size-change-test.html b/dom/canvas/test/webgl-conf/checkout/conformance2/buffers/bound-buffer-size-change-test.html index 35532834c99f..a9d13496abd1 100644 --- a/dom/canvas/test/webgl-conf/checkout/conformance2/buffers/bound-buffer-size-change-test.html +++ b/dom/canvas/test/webgl-conf/checkout/conformance2/buffers/bound-buffer-size-change-test.html @@ -61,8 +61,6 @@ shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_SIZE, 0)", "0"); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_START, 0)", "0"); gl.bufferData(gl.TRANSFORM_FEEDBACK_BUFFER, 4, gl.STATIC_DRAW); -wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION); - shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_BINDING, 0)", "buffer1"); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_SIZE, 0)", "0"); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_START, 0)", "0"); @@ -99,13 +97,11 @@ shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_SIZE, 0)", "8"); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_START, 0)", "4"); gl.bufferData(gl.TRANSFORM_FEEDBACK_BUFFER, 4, gl.STATIC_DRAW); -wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_BINDING, 0)", "buffer3"); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_SIZE, 0)", "8"); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_START, 0)", "4"); gl.bufferData(gl.TRANSFORM_FEEDBACK_BUFFER, 12, gl.STATIC_DRAW); -wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_BINDING, 0)", "buffer3"); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_SIZE, 0)", "8"); shouldBe("gl.getIndexedParameter(gl.TRANSFORM_FEEDBACK_BUFFER_START, 0)", "4"); From 3638a0143a20b9477e7f2550340b9f05f94fda7c Mon Sep 17 00:00:00 2001 From: Jan de Mooij Date: Fri, 30 Dec 2016 14:29:32 +0100 Subject: [PATCH 116/229] Bug 1188586 - Add testcase. r=me --- js/src/jit-test/tests/ion/bug1188586.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 js/src/jit-test/tests/ion/bug1188586.js diff --git a/js/src/jit-test/tests/ion/bug1188586.js b/js/src/jit-test/tests/ion/bug1188586.js new file mode 100644 index 000000000000..df5f166ba4d8 --- /dev/null +++ b/js/src/jit-test/tests/ion/bug1188586.js @@ -0,0 +1,7 @@ +(function(y) { + for (var k = 0; k < 9; ++k) { + try { + y ** y == a; + } catch (e) {} + } +})(); From 48076d30a7ed8cbd91f11d6bf63f23f0d7dfbede Mon Sep 17 00:00:00 2001 From: Jan de Mooij Date: Fri, 30 Dec 2016 14:29:35 +0100 Subject: [PATCH 117/229] Bug 1326150 - Don't attach getter stubs to IonGetPropertyIC if the IC result isn't monitored. r=h4writer --- js/src/jit-test/tests/ion/bug1326150.js | 4 ++++ js/src/jit/BaselineIC.cpp | 2 +- js/src/jit/CacheIR.cpp | 18 +++++++++++++----- js/src/jit/CacheIR.h | 6 +++++- js/src/jit/IonIC.cpp | 8 +++++++- js/src/jit/SharedIC.cpp | 2 +- 6 files changed, 31 insertions(+), 9 deletions(-) create mode 100644 js/src/jit-test/tests/ion/bug1326150.js diff --git a/js/src/jit-test/tests/ion/bug1326150.js b/js/src/jit-test/tests/ion/bug1326150.js new file mode 100644 index 000000000000..3c9047c98325 --- /dev/null +++ b/js/src/jit-test/tests/ion/bug1326150.js @@ -0,0 +1,4 @@ +this.x = []; +Function.apply(null, this.x); +Object.defineProperty(this, "x", {get: valueOf}); +assertEq(evaluate("this.x;"), this); diff --git a/js/src/jit/BaselineIC.cpp b/js/src/jit/BaselineIC.cpp index 1ffc5e41e60a..3f5b67587a88 100644 --- a/js/src/jit/BaselineIC.cpp +++ b/js/src/jit/BaselineIC.cpp @@ -963,7 +963,7 @@ DoGetElemFallback(JSContext* cx, BaselineFrame* frame, ICGetElem_Fallback* stub_ if (!attached && !JitOptions.disableCacheIR) { ICStubEngine engine = ICStubEngine::Baseline; GetPropIRGenerator gen(cx, pc, CacheKind::GetElem, engine, &isTemporarilyUnoptimizable, - lhs, rhs); + lhs, rhs, CanAttachGetter::Yes); if (gen.tryAttachStub()) { ICStub* newStub = AttachBaselineCacheIRStub(cx, gen.writerRef(), gen.cacheKind(), engine, info.outerScript(cx), stub); diff --git a/js/src/jit/CacheIR.cpp b/js/src/jit/CacheIR.cpp index 1e518732540a..91a71ddac79c 100644 --- a/js/src/jit/CacheIR.cpp +++ b/js/src/jit/CacheIR.cpp @@ -30,12 +30,14 @@ IRGenerator::IRGenerator(JSContext* cx, jsbytecode* pc, CacheKind cacheKind) GetPropIRGenerator::GetPropIRGenerator(JSContext* cx, jsbytecode* pc, CacheKind cacheKind, ICStubEngine engine, bool* isTemporarilyUnoptimizable, - HandleValue val, HandleValue idVal) + HandleValue val, HandleValue idVal, + CanAttachGetter canAttachGetter) : IRGenerator(cx, pc, cacheKind), val_(val), idVal_(idVal), engine_(engine), isTemporarilyUnoptimizable_(isTemporarilyUnoptimizable), + canAttachGetter_(canAttachGetter), preliminaryObjectAction_(PreliminaryObjectAction::None) {} @@ -223,7 +225,8 @@ enum NativeGetPropCacheability { static NativeGetPropCacheability CanAttachNativeGetProp(JSContext* cx, HandleObject obj, HandleId id, MutableHandleNativeObject holder, MutableHandleShape shape, - jsbytecode* pc, ICStubEngine engine, bool* isTemporarilyUnoptimizable) + jsbytecode* pc, ICStubEngine engine, CanAttachGetter canAttachGetter, + bool* isTemporarilyUnoptimizable) { MOZ_ASSERT(JSID_IS_STRING(id) || JSID_IS_SYMBOL(id)); @@ -253,6 +256,9 @@ CanAttachNativeGetProp(JSContext* cx, HandleObject obj, HandleId id, if (IsCacheableNoProperty(cx, obj, holder, shape, id, pc)) return CanAttachReadSlot; + if (canAttachGetter == CanAttachGetter::No) + return CanAttachNone; + if (IsCacheableGetPropCallScripted(obj, holder, shape, isTemporarilyUnoptimizable)) { // See bug 1226816. if (engine != ICStubEngine::IonSharedIC) @@ -425,7 +431,8 @@ GetPropIRGenerator::tryAttachNative(HandleObject obj, ObjOperandId objId, Handle RootedNativeObject holder(cx_); NativeGetPropCacheability type = CanAttachNativeGetProp(cx_, obj, id, &holder, &shape, pc_, - engine_, isTemporarilyUnoptimizable_); + engine_, canAttachGetter_, + isTemporarilyUnoptimizable_); MOZ_ASSERT_IF(idempotent(), type == CanAttachNone || (type == CanAttachReadSlot && holder)); switch (type) { @@ -476,7 +483,8 @@ GetPropIRGenerator::tryAttachWindowProxy(HandleObject obj, ObjOperandId objId, H RootedShape shape(cx_); RootedNativeObject holder(cx_); NativeGetPropCacheability type = CanAttachNativeGetProp(cx_, windowObj, id, &holder, &shape, pc_, - engine_, isTemporarilyUnoptimizable_); + engine_, canAttachGetter_, + isTemporarilyUnoptimizable_); if (type != CanAttachCallGetter || !IsCacheableGetPropCallNative(windowObj, holder, shape)) { @@ -584,7 +592,7 @@ GetPropIRGenerator::tryAttachDOMProxyUnshadowed(HandleObject obj, ObjOperandId o RootedShape shape(cx_); NativeGetPropCacheability canCache = CanAttachNativeGetProp(cx_, checkObj, id, &holder, &shape, - pc_, engine_, + pc_, engine_, canAttachGetter_, isTemporarilyUnoptimizable_); MOZ_ASSERT_IF(idempotent(), canCache == CanAttachNone || (canCache == CanAttachReadSlot && holder)); diff --git a/js/src/jit/CacheIR.h b/js/src/jit/CacheIR.h index e57d3ccbff5f..216ba3cff95c 100644 --- a/js/src/jit/CacheIR.h +++ b/js/src/jit/CacheIR.h @@ -720,6 +720,8 @@ class MOZ_RAII IRGenerator CacheKind cacheKind() const { return cacheKind_; } }; +enum class CanAttachGetter { Yes, No }; + // GetPropIRGenerator generates CacheIR for a GetProp IC. class MOZ_RAII GetPropIRGenerator : public IRGenerator { @@ -727,6 +729,7 @@ class MOZ_RAII GetPropIRGenerator : public IRGenerator HandleValue idVal_; ICStubEngine engine_; bool* isTemporarilyUnoptimizable_; + CanAttachGetter canAttachGetter_; enum class PreliminaryObjectAction { None, Unlink, NotePreliminary }; PreliminaryObjectAction preliminaryObjectAction_; @@ -777,7 +780,8 @@ class MOZ_RAII GetPropIRGenerator : public IRGenerator public: GetPropIRGenerator(JSContext* cx, jsbytecode* pc, CacheKind cacheKind, ICStubEngine engine, - bool* isTemporarilyUnoptimizable, HandleValue val, HandleValue idVal); + bool* isTemporarilyUnoptimizable, HandleValue val, HandleValue idVal, + CanAttachGetter canAttachGetter); bool tryAttachStub(); bool tryAttachIdempotentStub(); diff --git a/js/src/jit/IonIC.cpp b/js/src/jit/IonIC.cpp index 5b35a4dbc05f..2e411020e9cc 100644 --- a/js/src/jit/IonIC.cpp +++ b/js/src/jit/IonIC.cpp @@ -127,12 +127,18 @@ IonGetPropertyIC::update(JSContext* cx, HandleScript outerScript, IonGetProperty bool attached = false; if (!JitOptions.disableCacheIR && !ic->disabled()) { if (ic->canAttachStub()) { + // IonBuilder calls PropertyReadNeedsTypeBarrier to determine if it + // needs a type barrier. Unfortunately, PropertyReadNeedsTypeBarrier + // does not account for getters, so we should only attach a getter + // stub if we inserted a type barrier. + CanAttachGetter canAttachGetter = + ic->monitoredResult() ? CanAttachGetter::Yes : CanAttachGetter::No; jsbytecode* pc = ic->idempotent() ? nullptr : ic->pc(); RootedValue objVal(cx, ObjectValue(*obj)); bool isTemporarilyUnoptimizable; GetPropIRGenerator gen(cx, pc, ic->kind(), ICStubEngine::IonIC, &isTemporarilyUnoptimizable, - objVal, idVal); + objVal, idVal, canAttachGetter); if (ic->idempotent() ? gen.tryAttachIdempotentStub() : gen.tryAttachStub()) { attached = ic->attachCacheIRStub(cx, gen.writerRef(), gen.cacheKind(), outerScript); diff --git a/js/src/jit/SharedIC.cpp b/js/src/jit/SharedIC.cpp index 1155709c7683..3967b9288948 100644 --- a/js/src/jit/SharedIC.cpp +++ b/js/src/jit/SharedIC.cpp @@ -2296,7 +2296,7 @@ DoGetPropFallback(JSContext* cx, void* payload, ICGetProp_Fallback* stub_, if (!attached && !JitOptions.disableCacheIR) { RootedValue idVal(cx, StringValue(name)); GetPropIRGenerator gen(cx, pc, CacheKind::GetProp, engine, &isTemporarilyUnoptimizable, - val, idVal); + val, idVal, CanAttachGetter::Yes); if (gen.tryAttachStub()) { ICStub* newStub = AttachBaselineCacheIRStub(cx, gen.writerRef(), gen.cacheKind(), engine, info.outerScript(cx), stub); From ec79f44e1fde06eae5b9265d84e694fde03b318e Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Tue, 27 Dec 2016 15:48:46 +0100 Subject: [PATCH 118/229] Bug 1320374: Batch function compilations; r=luke MozReview-Commit-ID: BmFx1UuesSL --HG-- extra : rebase_source : c43ae49d7cb048ec06b0c592894b8361758d7543 --- js/src/jit/JitAllocPolicy.h | 2 +- js/src/jit/JitOptions.cpp | 10 ++ js/src/jit/JitOptions.h | 2 + js/src/wasm/WasmBaselineCompile.cpp | 39 ++--- js/src/wasm/WasmBaselineCompile.h | 3 +- js/src/wasm/WasmGenerator.cpp | 158 +++++++++++--------- js/src/wasm/WasmGenerator.h | 218 ++++++++++++++++------------ js/src/wasm/WasmIonCompile.cpp | 37 +++-- js/src/wasm/WasmIonCompile.h | 3 +- 9 files changed, 273 insertions(+), 199 deletions(-) diff --git a/js/src/jit/JitAllocPolicy.h b/js/src/jit/JitAllocPolicy.h index bf162929063f..ab4f8693591c 100644 --- a/js/src/jit/JitAllocPolicy.h +++ b/js/src/jit/JitAllocPolicy.h @@ -173,7 +173,7 @@ struct TempObject "Placement new argument type must inherit from TempObject"); MOZ_ASSERT(pos); return pos; - } + } }; template diff --git a/js/src/jit/JitOptions.cpp b/js/src/jit/JitOptions.cpp index eb5a6c1c2242..fca633662216 100644 --- a/js/src/jit/JitOptions.cpp +++ b/js/src/jit/JitOptions.cpp @@ -237,6 +237,16 @@ DefaultJitOptions::DefaultJitOptions() // included in the bounds check. SET_DEFAULT(wasmFoldOffsets, true); + // Until which wasm bytecode size should we accumulate functions, in order + // to compile efficiently on helper threads (see also bug 1320374). + SET_DEFAULT(wasmBatchThreshold, 10000); + + // In order to have different batching thresholds for Ion and the wasm + // baseline, and since a same batch can contain both Ion and baseline + // compiled functions, we make Ion functions weight more by using a scaling + // factor. + SET_DEFAULT(wasmBatchIonScaleFactor, 9); + // Determines whether we suppress using signal handlers // for interrupting jit-ed code. This is used only for testing. SET_DEFAULT(ionInterruptWithoutSignals, false); diff --git a/js/src/jit/JitOptions.h b/js/src/jit/JitOptions.h index 076980b4e55b..769b42f59759 100644 --- a/js/src/jit/JitOptions.h +++ b/js/src/jit/JitOptions.h @@ -87,6 +87,8 @@ struct DefaultJitOptions uint32_t branchPruningBlockSpanFactor; uint32_t branchPruningEffectfulInstFactor; uint32_t branchPruningThreshold; + uint32_t wasmBatchThreshold; + uint32_t wasmBatchIonScaleFactor; mozilla::Maybe forcedDefaultIonWarmUpThreshold; mozilla::Maybe forcedDefaultIonSmallFunctionWarmUpThreshold; mozilla::Maybe forcedRegisterAllocator; diff --git a/js/src/wasm/WasmBaselineCompile.cpp b/js/src/wasm/WasmBaselineCompile.cpp index dbd7a3737592..2aa9508174e7 100644 --- a/js/src/wasm/WasmBaselineCompile.cpp +++ b/js/src/wasm/WasmBaselineCompile.cpp @@ -512,7 +512,7 @@ class BaseCompiler Assembler::Condition latentIntCmp_; // Comparison operator, if latentOp_ == Compare, int types Assembler::DoubleCondition latentDoubleCmp_;// Comparison operator, if latentOp_ == Compare, float types - FuncCompileResults& compileResults_; + FuncOffsets offsets_; MacroAssembler& masm; // No '_' suffix - too tedious... AllocatableGeneralRegisterSet availGPR_; @@ -567,11 +567,12 @@ class BaseCompiler Decoder& decoder, const FuncBytes& func, const ValTypeVector& locals, - FuncCompileResults& compileResults); + TempAllocator* alloc, + MacroAssembler* masm); MOZ_MUST_USE bool init(); - void finish(); + FuncOffsets finish(); MOZ_MUST_USE bool emitFunction(); @@ -2053,7 +2054,7 @@ class BaseCompiler JitSpew(JitSpew_Codegen, "# Emitting wasm baseline code"); SigIdDesc sigId = env_.funcSigs[func_.index()]->id; - GenerateFunctionPrologue(masm, localSize_, sigId, &compileResults_.offsets()); + GenerateFunctionPrologue(masm, localSize_, sigId, &offsets_); MOZ_ASSERT(masm.framePushed() == uint32_t(localSize_)); @@ -2148,7 +2149,7 @@ class BaseCompiler // Restore the TLS register in case it was overwritten by the function. loadFromFramePtr(WasmTlsReg, frameOffsetFromSlot(tlsSlot_, MIRType::Pointer)); - GenerateFunctionEpilogue(masm, localSize_, &compileResults_.offsets()); + GenerateFunctionEpilogue(masm, localSize_, &offsets_); #if defined(JS_ION_PERF) // FIXME - profiling code missing. Bug 1286948. @@ -2162,7 +2163,7 @@ class BaseCompiler masm.wasmEmitTrapOutOfLineCode(); - compileResults_.offsets().end = masm.currentOffset(); + offsets_.end = masm.currentOffset(); // A frame greater than 256KB is implausible, probably an attack, // so fail the compilation. @@ -7540,12 +7541,13 @@ BaseCompiler::BaseCompiler(const ModuleEnvironment& env, Decoder& decoder, const FuncBytes& func, const ValTypeVector& locals, - FuncCompileResults& compileResults) + TempAllocator* alloc, + MacroAssembler* masm) : env_(env), iter_(decoder, func.lineOrBytecode()), func_(func), lastReadCallSite_(0), - alloc_(compileResults.alloc()), + alloc_(*alloc), locals_(locals), localSize_(0), varLow_(0), @@ -7558,8 +7560,7 @@ BaseCompiler::BaseCompiler(const ModuleEnvironment& env, latentType_(ValType::I32), latentIntCmp_(Assembler::Equal), latentDoubleCmp_(Assembler::DoubleEqual), - compileResults_(compileResults), - masm(compileResults_.masm()), + masm(*masm), availGPR_(GeneralRegisterSet::All()), availFPU_(FloatRegisterSet::All()), #ifdef DEBUG @@ -7702,13 +7703,15 @@ BaseCompiler::init() return true; } -void +FuncOffsets BaseCompiler::finish() { MOZ_ASSERT(done(), "all bytes must be consumed"); MOZ_ASSERT(func_.callSiteLineNums().length() == lastReadCallSite_); masm.flushBuffer(); + + return offsets_; } static LiveRegisterSet @@ -7756,12 +7759,11 @@ js::wasm::BaselineCanCompile(const FunctionGenerator* fg) } bool -js::wasm::BaselineCompileFunction(CompileTask* task) +js::wasm::BaselineCompileFunction(CompileTask* task, FuncCompileUnit* unit) { - MOZ_ASSERT(task->mode() == CompileTask::CompileMode::Baseline); + MOZ_ASSERT(unit->mode() == CompileMode::Baseline); - const FuncBytes& func = task->func(); - FuncCompileResults& results = task->results(); + const FuncBytes& func = unit->func(); Decoder d(func.bytes()); @@ -7775,19 +7777,18 @@ js::wasm::BaselineCompileFunction(CompileTask* task) // The MacroAssembler will sometimes access the jitContext. - JitContext jitContext(&results.alloc()); + JitContext jitContext(&task->alloc()); // One-pass baseline compilation. - BaseCompiler f(task->env(), d, func, locals, results); + BaseCompiler f(task->env(), d, func, locals, &task->alloc(), &task->masm()); if (!f.init()) return false; if (!f.emitFunction()) return false; - f.finish(); - + unit->finish(f.finish()); return true; } diff --git a/js/src/wasm/WasmBaselineCompile.h b/js/src/wasm/WasmBaselineCompile.h index 3c7a0d2e8364..3fc43ba9606a 100644 --- a/js/src/wasm/WasmBaselineCompile.h +++ b/js/src/wasm/WasmBaselineCompile.h @@ -24,6 +24,7 @@ namespace wasm { class FunctionGenerator; class CompileTask; +class FuncCompileUnit; // Return true if BaselineCompileFunction can generate code for the // function held in the FunctionGenerator. If false is returned a @@ -39,7 +40,7 @@ BaselineCanCompile(const FunctionGenerator* fg); // Generate adequate code quickly. bool -BaselineCompileFunction(CompileTask* task); +BaselineCompileFunction(CompileTask* task, FuncCompileUnit* unit); } // namespace wasm } // namespace js diff --git a/js/src/wasm/WasmGenerator.cpp b/js/src/wasm/WasmGenerator.cpp index dcda4ab4519f..a89f9aa4a29e 100644 --- a/js/src/wasm/WasmGenerator.cpp +++ b/js/src/wasm/WasmGenerator.cpp @@ -55,6 +55,8 @@ ModuleGenerator::ModuleGenerator() startOfUnpatchedCallsites_(0), parallel_(false), outstanding_(0), + currentTask_(nullptr), + batchedBytecode_(0), activeFuncDef_(nullptr), startedFuncDefs_(false), finishedFuncDefs_(false), @@ -96,6 +98,8 @@ ModuleGenerator::~ModuleGenerator() } else { MOZ_ASSERT(!outstanding_); } + MOZ_ASSERT_IF(finishedFuncDefs_, !batchedBytecode_); + MOZ_ASSERT_IF(finishedFuncDefs_, !currentTask_); } bool @@ -391,42 +395,45 @@ ModuleGenerator::patchFarJumps(const TrapExitOffsetArray& trapExits) bool ModuleGenerator::finishTask(CompileTask* task) { - const FuncBytes& func = task->func(); - FuncCompileResults& results = task->results(); - masm_.haltingAlign(CodeAlignment); // Before merging in the new function's code, if calls in a prior function // body might go out of range, insert far jumps to extend the range. - if ((masm_.size() - startOfUnpatchedCallsites_) + results.masm().size() > JumpRange()) { + if ((masm_.size() - startOfUnpatchedCallsites_) + task->masm().size() > JumpRange()) { startOfUnpatchedCallsites_ = masm_.size(); if (!patchCallSites()) return false; } - // Offset the recorded FuncOffsets by the offset of the function in the - // whole module's code segment. uint32_t offsetInWhole = masm_.size(); - results.offsets().offsetBy(offsetInWhole); + for (const FuncCompileUnit& unit : task->units()) { + const FuncBytes& func = unit.func(); - // Add the CodeRange for this function. - uint32_t funcCodeRangeIndex = metadata_->codeRanges.length(); - if (!metadata_->codeRanges.emplaceBack(func.index(), func.lineOrBytecode(), results.offsets())) - return false; + // Offset the recorded FuncOffsets by the offset of the function in the + // whole module's code segment. + FuncOffsets offsets = unit.offsets(); + offsets.offsetBy(offsetInWhole); - MOZ_ASSERT(!funcIsCompiled(func.index())); - funcToCodeRange_[func.index()] = funcCodeRangeIndex; + // Add the CodeRange for this function. + uint32_t funcCodeRangeIndex = metadata_->codeRanges.length(); + if (!metadata_->codeRanges.emplaceBack(func.index(), func.lineOrBytecode(), offsets)) + return false; + + MOZ_ASSERT(!funcIsCompiled(func.index())); + funcToCodeRange_[func.index()] = funcCodeRangeIndex; + } // Merge the compiled results into the whole-module masm. mozilla::DebugOnly sizeBefore = masm_.size(); - if (!masm_.asmMergeWith(results.masm())) + if (!masm_.asmMergeWith(task->masm())) + return false; + MOZ_ASSERT(masm_.size() == offsetInWhole + task->masm().size()); + + if (!task->reset(&freeFuncBytes_)) return false; - MOZ_ASSERT(masm_.size() == offsetInWhole + results.masm().size()); - UniqueBytes recycled; - task->reset(&recycled); freeTasks_.infallibleAppend(task); - return freeBytes_.emplaceBack(Move(recycled)); + return true; } bool @@ -864,15 +871,6 @@ ModuleGenerator::startFuncDefs() for (size_t i = 0; i < numTasks; i++) freeTasks_.infallibleAppend(&tasks_[i]); - if (!freeBytes_.reserve(numTasks)) - return false; - for (size_t i = 0; i < numTasks; i++) { - auto bytes = js::MakeUnique(); - if (!bytes) - return false; - freeBytes_.infallibleAppend(Move(bytes)); - } - startedFuncDefs_ = true; MOZ_ASSERT(!finishedFuncDefs_); return true; @@ -885,58 +883,81 @@ ModuleGenerator::startFuncDef(uint32_t lineOrBytecode, FunctionGenerator* fg) MOZ_ASSERT(!activeFuncDef_); MOZ_ASSERT(!finishedFuncDefs_); - if (!freeBytes_.empty()) { - fg->bytes_ = Move(freeBytes_.back()); - freeBytes_.popBack(); + if (!freeFuncBytes_.empty()) { + fg->funcBytes_ = Move(freeFuncBytes_.back()); + freeFuncBytes_.popBack(); } else { - fg->bytes_ = js::MakeUnique(); - if (!fg->bytes_) + fg->funcBytes_ = js::MakeUnique(); + if (!fg->funcBytes_) return false; } - fg->lineOrBytecode_ = lineOrBytecode; + if (!currentTask_) { + if (freeTasks_.empty() && !finishOutstandingTask()) + return false; + currentTask_ = freeTasks_.popCopy(); + } + + fg->funcBytes_->setLineOrBytecode(lineOrBytecode); fg->m_ = this; activeFuncDef_ = fg; return true; } +bool +ModuleGenerator::launchBatchCompile() +{ + MOZ_ASSERT(currentTask_); + + size_t numBatchedFuncs = currentTask_->units().length(); + MOZ_ASSERT(numBatchedFuncs); + + if (parallel_) { + if (!StartOffThreadWasmCompile(currentTask_)) + return false; + outstanding_++; + } else { + if (!CompileFunction(currentTask_)) + return false; + if (!finishTask(currentTask_)) + return false; + } + + currentTask_ = nullptr; + batchedBytecode_ = 0; + + numFinishedFuncDefs_ += numBatchedFuncs; + return true; +} + bool ModuleGenerator::finishFuncDef(uint32_t funcIndex, FunctionGenerator* fg) { MOZ_ASSERT(activeFuncDef_ == fg); - auto func = js::MakeUnique(Move(fg->bytes_), - funcIndex, - funcSig(funcIndex), - fg->lineOrBytecode_, - Move(fg->callSiteLineNums_)); - if (!func) - return false; + UniqueFuncBytes func = Move(fg->funcBytes_); + + func->setFunc(funcIndex, &funcSig(funcIndex)); auto mode = alwaysBaseline_ && BaselineCanCompile(fg) - ? CompileTask::CompileMode::Baseline - : CompileTask::CompileMode::Ion; + ? CompileMode::Baseline + : CompileMode::Ion; - if (freeTasks_.empty() && !finishOutstandingTask()) + CheckedInt newBatched = func->bytes().length(); + if (mode == CompileMode::Ion) + newBatched *= JitOptions.wasmBatchIonScaleFactor; + newBatched += batchedBytecode_; + + if (!currentTask_->units().emplaceBack(Move(func), mode)) return false; - CompileTask* task = freeTasks_.popCopy(); - task->init(Move(func), mode); - - if (parallel_) { - if (!StartOffThreadWasmCompile(task)) - return false; - outstanding_++; - } else { - if (!CompileFunction(task)) - return false; - if (!finishTask(task)) - return false; - } + if (newBatched.isValid() && newBatched.value() < JitOptions.wasmBatchThreshold) + batchedBytecode_ = newBatched.value(); + else if (!launchBatchCompile()) + return false; fg->m_ = nullptr; activeFuncDef_ = nullptr; - numFinishedFuncDefs_++; return true; } @@ -947,6 +968,9 @@ ModuleGenerator::finishFuncDefs() MOZ_ASSERT(!activeFuncDef_); MOZ_ASSERT(!finishedFuncDefs_); + if (currentTask_ && !launchBatchCompile()) + return false; + while (outstanding_ > 0) { if (!finishOutstandingTask()) return false; @@ -1146,14 +1170,18 @@ wasm::CompileFunction(CompileTask* task) TraceLoggerThread* logger = TraceLoggerForCurrentThread(); AutoTraceLog logCompile(logger, TraceLogger_WasmCompilation); - switch (task->mode()) { - case wasm::CompileTask::CompileMode::Ion: - return wasm::IonCompileFunction(task); - case wasm::CompileTask::CompileMode::Baseline: - return wasm::BaselineCompileFunction(task); - case wasm::CompileTask::CompileMode::None: - break; + for (FuncCompileUnit& unit : task->units()) { + switch (unit.mode()) { + case CompileMode::Ion: + if (!IonCompileFunction(task, &unit)) + return false; + break; + case CompileMode::Baseline: + if (!BaselineCompileFunction(task, &unit)) + return false; + break; + } } - MOZ_CRASH("Uninitialized task"); + return true; } diff --git a/js/src/wasm/WasmGenerator.h b/js/src/wasm/WasmGenerator.h index 9e0fab45f1cf..daa98a005434 100644 --- a/js/src/wasm/WasmGenerator.h +++ b/js/src/wasm/WasmGenerator.h @@ -36,124 +36,158 @@ struct CompileArgs; class FunctionGenerator; -typedef Vector UniqueBytesVector; - // The FuncBytes class represents a single, concurrently-compilable function. // A FuncBytes object is composed of the wasm function body bytes along with the // ambient metadata describing the function necessary to compile it. class FuncBytes { - UniqueBytes bytes_; + Bytes bytes_; uint32_t index_; - const SigWithId& sig_; + const SigWithId* sig_; uint32_t lineOrBytecode_; Uint32Vector callSiteLineNums_; public: - FuncBytes(UniqueBytes bytes, - uint32_t index, - const SigWithId& sig, - uint32_t lineOrBytecode, - Uint32Vector&& callSiteLineNums) - : bytes_(Move(bytes)), - index_(index), - sig_(sig), - lineOrBytecode_(lineOrBytecode), - callSiteLineNums_(Move(callSiteLineNums)) + FuncBytes() + : index_(UINT32_MAX), + sig_(nullptr), + lineOrBytecode_(UINT32_MAX) {} - Bytes& bytes() { return *bytes_; } - const Bytes& bytes() const { return *bytes_; } - UniqueBytes recycle() { return Move(bytes_); } + Bytes& bytes() { + return bytes_; + } + MOZ_MUST_USE bool addCallSiteLineNum(uint32_t lineno) { + return callSiteLineNums_.append(lineno); + } + void setLineOrBytecode(uint32_t lineOrBytecode) { + MOZ_ASSERT(lineOrBytecode_ == UINT32_MAX); + lineOrBytecode_ = lineOrBytecode; + } + void setFunc(uint32_t index, const SigWithId* sig) { + MOZ_ASSERT(index_ == UINT32_MAX); + MOZ_ASSERT(sig_ == nullptr); + index_ = index; + sig_ = sig; + } + void reset() { + bytes_.clear(); + index_ = UINT32_MAX; + sig_ = nullptr; + lineOrBytecode_ = UINT32_MAX; + callSiteLineNums_.clear(); + } + + const Bytes& bytes() const { return bytes_; } uint32_t index() const { return index_; } - const SigWithId& sig() const { return sig_; } + const SigWithId& sig() const { return *sig_; } uint32_t lineOrBytecode() const { return lineOrBytecode_; } const Uint32Vector& callSiteLineNums() const { return callSiteLineNums_; } }; typedef UniquePtr UniqueFuncBytes; +typedef Vector UniqueFuncBytesVector; -// The FuncCompileResults class contains the results of compiling a single -// function body, ready to be merged into the whole-module MacroAssembler. - -class FuncCompileResults +enum class CompileMode { - jit::TempAllocator alloc_; - jit::MacroAssembler masm_; - FuncOffsets offsets_; - - FuncCompileResults(const FuncCompileResults&) = delete; - FuncCompileResults& operator=(const FuncCompileResults&) = delete; - - public: - explicit FuncCompileResults(LifoAlloc& lifo) - : alloc_(&lifo), - masm_(jit::MacroAssembler::WasmToken(), alloc_) - {} - - jit::TempAllocator& alloc() { return alloc_; } - jit::MacroAssembler& masm() { return masm_; } - FuncOffsets& offsets() { return offsets_; } + Baseline, + Ion }; -// A CompileTask represents the task of compiling a single function body. An -// CompileTask is filled with the wasm code to be compiled on the main -// validation thread, sent off to a compilation helper thread which creates -// the FuncCompileResults, and finally sent back to the validation thread. To -// save time allocating and freeing memory, CompileTasks are reset() and -// reused. +// FuncCompileUnit contains all the data necessary to produce and store the +// results of a single function's compilation. + +class FuncCompileUnit +{ + UniqueFuncBytes func_; + CompileMode mode_; + FuncOffsets offsets_; + DebugOnly finished_; + + public: + FuncCompileUnit(UniqueFuncBytes func, CompileMode mode) + : func_(Move(func)), + mode_(mode), + finished_(false) + {} + + const FuncBytes& func() const { return *func_; } + CompileMode mode() const { return mode_; } + FuncOffsets offsets() const { MOZ_ASSERT(finished_); return offsets_; } + + void finish(FuncOffsets offsets) { + MOZ_ASSERT(!finished_); + offsets_ = offsets; + finished_ = true; + } + + UniqueFuncBytes recycle() { + MOZ_ASSERT(finished_); + func_->reset(); + return Move(func_); + } +}; + +typedef Vector FuncCompileUnitVector; + +// A CompileTask represents the task of compiling a batch of functions. It is +// filled with a certain number of function's bodies that are sent off to a +// compilation helper thread, which fills in the resulting code offsets, and +// finally sent back to the validation thread. To save time allocating and +// freeing memory, CompileTasks are reset() and reused. class CompileTask { - public: - enum class CompileMode { None, Baseline, Ion }; - - private: - const ModuleEnvironment& env_; - LifoAlloc lifo_; - UniqueFuncBytes func_; - CompileMode mode_; - Maybe results_; + const ModuleEnvironment& env_; + LifoAlloc lifo_; + Maybe alloc_; + Maybe masm_; + FuncCompileUnitVector units_; CompileTask(const CompileTask&) = delete; CompileTask& operator=(const CompileTask&) = delete; + void init() { + alloc_.emplace(&lifo_); + masm_.emplace(jit::MacroAssembler::WasmToken(), *alloc_); + } + public: CompileTask(const ModuleEnvironment& env, size_t defaultChunkSize) - : env_(env), lifo_(defaultChunkSize), func_(nullptr), mode_(CompileMode::None) - {} + : env_(env), + lifo_(defaultChunkSize) + { + init(); + } LifoAlloc& lifo() { return lifo_; } + jit::TempAllocator& alloc() { + return *alloc_; + } const ModuleEnvironment& env() const { return env_; } - void init(UniqueFuncBytes func, CompileMode mode) { - MOZ_ASSERT(!func_); - func_ = Move(func); - results_.emplace(lifo_); - mode_ = mode; + jit::MacroAssembler& masm() { + return *masm_; } - CompileMode mode() const { - return mode_; + FuncCompileUnitVector& units() { + return units_; } - const FuncBytes& func() const { - MOZ_ASSERT(func_); - return *func_; - } - FuncCompileResults& results() { - return *results_; - } - void reset(UniqueBytes* recycled) { - if (func_) { - *recycled = Move(func_->recycle()); - (*recycled)->clear(); + bool reset(UniqueFuncBytesVector* freeFuncBytes) { + for (FuncCompileUnit& unit : units_) { + if (!freeFuncBytes->emplaceBack(Move(unit.recycle()))) + return false; } - func_.reset(nullptr); - results_.reset(); + + units_.clear(); + masm_.reset(); + alloc_.reset(); lifo_.releaseAll(); - mode_ = CompileMode::None; + + init(); + return true; } }; @@ -196,7 +230,9 @@ class MOZ_STACK_CLASS ModuleGenerator uint32_t outstanding_; CompileTaskVector tasks_; CompileTaskPtrVector freeTasks_; - UniqueBytesVector freeBytes_; + UniqueFuncBytesVector freeFuncBytes_; + CompileTask* currentTask_; + uint32_t batchedBytecode_; // Assertions DebugOnly activeFuncDef_; @@ -206,6 +242,7 @@ class MOZ_STACK_CLASS ModuleGenerator bool funcIsCompiled(uint32_t funcIndex) const; const CodeRange& funcCodeRange(uint32_t funcIndex) const; + uint32_t numFuncImports() const; MOZ_MUST_USE bool patchCallSites(TrapExitOffsetArray* maybeTrapExits = nullptr); MOZ_MUST_USE bool patchFarJumps(const TrapExitOffsetArray& trapExits); MOZ_MUST_USE bool finishTask(CompileTask* task); @@ -217,12 +254,11 @@ class MOZ_STACK_CLASS ModuleGenerator MOZ_MUST_USE bool allocateGlobalBytes(uint32_t bytes, uint32_t align, uint32_t* globalDataOff); MOZ_MUST_USE bool allocateGlobal(GlobalDesc* global); + MOZ_MUST_USE bool launchBatchCompile(); + MOZ_MUST_USE bool initAsmJS(Metadata* asmJSMetadata); MOZ_MUST_USE bool initWasm(); - // Functions declarations: - uint32_t numFuncImports() const; - public: explicit ModuleGenerator(); ~ModuleGenerator(); @@ -275,10 +311,11 @@ class MOZ_STACK_CLASS ModuleGenerator }; // A FunctionGenerator encapsulates the generation of a single function body. -// ModuleGenerator::startFunc must be called after construction and before doing -// anything else. After the body is complete, ModuleGenerator::finishFunc must -// be called before the FunctionGenerator is destroyed and the next function is -// started. +// ModuleGenerator::startFuncDef must be called after construction and before +// doing anything else. +// +// After the body is complete, ModuleGenerator::finishFuncDef must be called +// before the FunctionGenerator is destroyed and the next function is started. class MOZ_STACK_CLASS FunctionGenerator { @@ -288,16 +325,11 @@ class MOZ_STACK_CLASS FunctionGenerator bool usesSimd_; bool usesAtomics_; - // Data created during function generation, then handed over to the - // FuncBytes in ModuleGenerator::finishFunc(). - UniqueBytes bytes_; - Uint32Vector callSiteLineNums_; - - uint32_t lineOrBytecode_; + UniqueFuncBytes funcBytes_; public: FunctionGenerator() - : m_(nullptr), usesSimd_(false), usesAtomics_(false), bytes_(nullptr), lineOrBytecode_(0) + : m_(nullptr), usesSimd_(false), usesAtomics_(false), funcBytes_(nullptr) {} bool usesSimd() const { @@ -315,10 +347,10 @@ class MOZ_STACK_CLASS FunctionGenerator } Bytes& bytes() { - return *bytes_; + return funcBytes_->bytes(); } MOZ_MUST_USE bool addCallSiteLineNum(uint32_t lineno) { - return callSiteLineNums_.append(lineno); + return funcBytes_->addCallSiteLineNum(lineno); } }; diff --git a/js/src/wasm/WasmIonCompile.cpp b/js/src/wasm/WasmIonCompile.cpp index 565196d9d19f..b1ffb0c9e52a 100644 --- a/js/src/wasm/WasmIonCompile.cpp +++ b/js/src/wasm/WasmIonCompile.cpp @@ -168,8 +168,6 @@ class FunctionCompiler uint32_t blockDepth_; ControlFlowPatchsVector blockPatches_; - FuncCompileResults& compileResults_; - // TLS pointer argument to the current function. MWasmParameter* tlsPointer_; @@ -178,8 +176,7 @@ class FunctionCompiler Decoder& decoder, const FuncBytes& func, const ValTypeVector& locals, - MIRGenerator& mirGen, - FuncCompileResults& compileResults) + MIRGenerator& mirGen) : env_(env), iter_(decoder, func.lineOrBytecode()), func_(func), @@ -194,14 +191,12 @@ class FunctionCompiler maxStackArgBytes_(0), loopDepth_(0), blockDepth_(0), - compileResults_(compileResults), tlsPointer_(nullptr) {} const ModuleEnvironment& env() const { return env_; } IonOpIter& iter() { return iter_; } TempAllocator& alloc() const { return alloc_; } - MacroAssembler& masm() const { return compileResults_.masm(); } const Sig& sig() const { return func_.sig(); } TrapOffset trapOffset() const { @@ -3697,12 +3692,12 @@ EmitExpr(FunctionCompiler& f) } bool -wasm::IonCompileFunction(CompileTask* task) +wasm::IonCompileFunction(CompileTask* task, FuncCompileUnit* unit) { - MOZ_ASSERT(task->mode() == CompileTask::CompileMode::Ion); + MOZ_ASSERT(unit->mode() == CompileMode::Ion); - const FuncBytes& func = task->func(); - FuncCompileResults& results = task->results(); + const FuncBytes& func = unit->func(); + const ModuleEnvironment& env = task->env(); Decoder d(func.bytes()); @@ -3711,18 +3706,18 @@ wasm::IonCompileFunction(CompileTask* task) ValTypeVector locals; if (!locals.appendAll(func.sig().args())) return false; - if (!DecodeLocalEntries(d, task->env().kind, &locals)) + if (!DecodeLocalEntries(d, env.kind, &locals)) return false; // Set up for Ion compilation. - JitContext jitContext(&results.alloc()); + JitContext jitContext(&task->alloc()); const JitCompileOptions options; - MIRGraph graph(&results.alloc()); + MIRGraph graph(&task->alloc()); CompileInfo compileInfo(locals.length()); - MIRGenerator mir(nullptr, options, &results.alloc(), &graph, &compileInfo, + MIRGenerator mir(nullptr, options, &task->alloc(), &graph, &compileInfo, IonOptimizations.get(OptimizationLevel::Wasm)); - mir.initMinWasmHeapLength(task->env().minMemoryLength); + mir.initMinWasmHeapLength(env.minMemoryLength); // Capture the prologue's trap site before decoding the function. @@ -3730,7 +3725,7 @@ wasm::IonCompileFunction(CompileTask* task) // Build MIR graph { - FunctionCompiler f(task->env(), d, func, locals, mir, results); + FunctionCompiler f(env, d, func, locals, mir); if (!f.init()) return false; @@ -3770,11 +3765,15 @@ wasm::IonCompileFunction(CompileTask* task) if (!lir) return false; - SigIdDesc sigId = task->env().funcSigs[func.index()]->id; + SigIdDesc sigId = env.funcSigs[func.index()]->id; - CodeGenerator codegen(&mir, lir, &results.masm()); - if (!codegen.generateWasm(sigId, prologueTrapOffset, &results.offsets())) + CodeGenerator codegen(&mir, lir, &task->masm()); + + FuncOffsets offsets; + if (!codegen.generateWasm(sigId, prologueTrapOffset, &offsets)) return false; + + unit->finish(offsets); } return true; diff --git a/js/src/wasm/WasmIonCompile.h b/js/src/wasm/WasmIonCompile.h index e8636a90f90f..a228dbde871d 100644 --- a/js/src/wasm/WasmIonCompile.h +++ b/js/src/wasm/WasmIonCompile.h @@ -25,10 +25,11 @@ namespace js { namespace wasm { class CompileTask; +class FuncCompileUnit; // Generates very fast code at the expense of compilation time. MOZ_MUST_USE bool -IonCompileFunction(CompileTask* task); +IonCompileFunction(CompileTask* task, FuncCompileUnit* unit); } // namespace wasm } // namespace js From 83aebb62530c4f211f74ae770c840dd2f469cda0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Tue, 13 Dec 2016 12:14:36 +0100 Subject: [PATCH 119/229] Bug 1304792: Minimal Loader and CSSParser cleanup. r=heycam MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MozReview-Commit-ID: DYOh8BtK7NT Signed-off-by: Emilio Cobos Álvarez --- layout/style/Loader.cpp | 4 +--- layout/style/nsCSSParser.cpp | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/layout/style/Loader.cpp b/layout/style/Loader.cpp index 796eca4098dd..892beb9a38cd 100644 --- a/layout/style/Loader.cpp +++ b/layout/style/Loader.cpp @@ -1426,8 +1426,6 @@ Loader::InsertChildSheet(StyleSheet* aSheet, aParentRule->SetSheet(aSheet->AsGecko()); // This sets the ownerRule on the sheet LOG((" Inserting into parent sheet")); - // LOG((" Inserting into parent sheet at position %d", insertionPoint)); - return NS_OK; } @@ -1991,7 +1989,7 @@ Loader::LoadInlineStyle(nsIContent* aElement, bool* aIsAlternate) { LOG(("css::Loader::LoadInlineStyle")); - NS_ASSERTION(mParsingDatas.Length() == 0, "We're in the middle of a parse?"); + MOZ_ASSERT(mParsingDatas.IsEmpty(), "We're in the middle of a parse?"); *aCompleted = true; diff --git a/layout/style/nsCSSParser.cpp b/layout/style/nsCSSParser.cpp index 8167dae58717..84203899fcaf 100644 --- a/layout/style/nsCSSParser.cpp +++ b/layout/style/nsCSSParser.cpp @@ -3796,8 +3796,8 @@ CSSParserImpl::ProcessImport(const nsString& aURLSpec, uint32_t aColumnNumber) { RefPtr rule = new css::ImportRule(aMedia, aURLSpec, - aLineNumber, - aColumnNumber); + aLineNumber, + aColumnNumber); (*aAppendFunc)(rule, aData); // Diagnose bad URIs even if we don't have a child loader. From a25a3083ce44efb88dd040b23b794421d43a6238 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Sat, 17 Dec 2016 10:58:56 +0100 Subject: [PATCH 120/229] Bug 1304792: stylo: Implement @import. r=heycam MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MozReview-Commit-ID: Hw1V66JxIBD Signed-off-by: Emilio Cobos Álvarez --- layout/style/Loader.cpp | 53 +++++++++++++++--------- layout/style/Loader.h | 13 ++++-- layout/style/ServoArcTypeList.h | 1 + layout/style/ServoBindingList.h | 14 +++++++ layout/style/ServoBindings.cpp | 37 +++++++++++++++++ layout/style/ServoBindings.h | 8 ++++ layout/style/ServoStyleSheet.cpp | 21 ++++++---- layout/style/ServoStyleSheet.h | 11 ++++- layout/style/nsCSSParser.cpp | 4 +- layout/style/nsLayoutStylesheetCache.cpp | 5 ++- 10 files changed, 131 insertions(+), 36 deletions(-) diff --git a/layout/style/Loader.cpp b/layout/style/Loader.cpp index 892beb9a38cd..50630806be9b 100644 --- a/layout/style/Loader.cpp +++ b/layout/style/Loader.cpp @@ -53,6 +53,7 @@ #include "mozilla/dom/ShadowRoot.h" #include "mozilla/dom/URL.h" #include "mozilla/AsyncEventDispatcher.h" +#include "mozilla/ServoBindings.h" #include "mozilla/StyleSheet.h" #include "mozilla/StyleSheetInlines.h" #include "mozilla/ConsoleReportCollector.h" @@ -1405,25 +1406,25 @@ Loader::InsertSheetInDoc(StyleSheet* aSheet, nsresult Loader::InsertChildSheet(StyleSheet* aSheet, StyleSheet* aParentSheet, - ImportRule* aParentRule) + ImportRule* aGeckoParentRule, + RawServoImportRule* aServoParentRule) { LOG(("css::Loader::InsertChildSheet")); - NS_PRECONDITION(aSheet, "Nothing to insert"); - NS_PRECONDITION(aParentSheet, "Need a parent to insert into"); - NS_PRECONDITION(aParentSheet, "How did we get imported?"); - - // XXXheycam The InsertChildSheet API doesn't work with ServoStyleSheets, - // since they won't have Gecko ImportRules in them. - if (aSheet->IsServo()) { - return NS_ERROR_FAILURE; + MOZ_ASSERT(aSheet, "Nothing to insert"); + MOZ_ASSERT(aParentSheet, "Need a parent to insert into"); + MOZ_ASSERT_IF(aSheet->IsGecko(), aGeckoParentRule && !aServoParentRule); + MOZ_ASSERT_IF(aSheet->IsServo(), aServoParentRule && !aGeckoParentRule); + if (aSheet->IsGecko()) { + // child sheets should always start out enabled, even if they got + // cloned off of top-level sheets which were disabled + aSheet->AsGecko()->SetEnabled(true); + aGeckoParentRule->SetSheet(aSheet->AsGecko()); // This sets the ownerRule on the sheet + } else { + RefPtr sheet = + Servo_ImportRule_GetSheet(aServoParentRule).Consume(); + aSheet->AsServo()->SetSheetForImport(sheet); } - - // child sheets should always start out enabled, even if they got - // cloned off of top-level sheets which were disabled - aSheet->AsGecko()->SetEnabled(true); - aParentSheet->AppendStyleSheet(aSheet); - aParentRule->SetSheet(aSheet->AsGecko()); // This sets the ownerRule on the sheet LOG((" Inserting into parent sheet")); return NS_OK; @@ -1773,7 +1774,8 @@ Loader::ParseSheet(const nsAString& aInput, aLoadData->mLineNumber); } else { rv = - aLoadData->mSheet->AsServo()->ParseSheet(aInput, sheetURI, baseURI, + aLoadData->mSheet->AsServo()->ParseSheet(this, + aInput, sheetURI, baseURI, aLoadData->mSheet->Principal(), aLoadData->mLineNumber); } @@ -2195,13 +2197,19 @@ nsresult Loader::LoadChildSheet(StyleSheet* aParentSheet, nsIURI* aURL, nsMediaList* aMedia, - ImportRule* aParentRule, + ImportRule* aGeckoParentRule, + RawServoImportRule* aServoParentRule, LoaderReusableStyleSheets* aReusableSheets) { LOG(("css::Loader::LoadChildSheet")); NS_PRECONDITION(aURL, "Must have a URI to load"); NS_PRECONDITION(aParentSheet, "Must have a parent sheet"); + // Servo doesn't support reusable sheets. + MOZ_ASSERT_IF(aReusableSheets, aParentSheet->IsGecko()); + MOZ_ASSERT_IF(aParentSheet->IsGecko(), aGeckoParentRule && !aServoParentRule); + MOZ_ASSERT_IF(aParentSheet->IsServo(), aServoParentRule && !aGeckoParentRule); + if (!mEnabled) { LOG_WARN((" Not enabled")); return NS_ERROR_NOT_AVAILABLE; @@ -2213,7 +2221,11 @@ Loader::LoadChildSheet(StyleSheet* aParentSheet, // check for an owning document: if none, don't bother walking up the parent // sheets - if (aParentSheet->GetOwningDocument()) { + // + // FIXME(emilio): Figure out whether this walk up is necessary (try seems + // green without it), and fix the parenting of stylesheets in the servo case + // if that's the case. + if (aParentSheet->GetOwningDocument() && aParentSheet->IsGecko()) { StyleSheet* topSheet = aParentSheet; while (StyleSheet* parent = topSheet->GetParentSheet()) { topSheet = parent; @@ -2264,7 +2276,7 @@ Loader::LoadChildSheet(StyleSheet* aParentSheet, StyleSheetState state; if (aReusableSheets && aReusableSheets->FindReusableStyleSheet(aURL, reusableSheet)) { sheet = reusableSheet; - aParentRule->SetSheet(reusableSheet); + aGeckoParentRule->SetSheet(reusableSheet); state = eSheetComplete; } else { bool isAlternate; @@ -2281,7 +2293,8 @@ Loader::LoadChildSheet(StyleSheet* aParentSheet, PrepareSheet(sheet, empty, empty, aMedia, nullptr, isAlternate); } - rv = InsertChildSheet(sheet, aParentSheet, aParentRule); + rv = InsertChildSheet(sheet, aParentSheet, aGeckoParentRule, + aServoParentRule); NS_ENSURE_SUCCESS(rv, rv); if (state == eSheetComplete) { diff --git a/layout/style/Loader.h b/layout/style/Loader.h index 209783a80422..583d88746438 100644 --- a/layout/style/Loader.h +++ b/layout/style/Loader.h @@ -285,15 +285,19 @@ public: * @param aParentSheet the parent of this child sheet * @param aURL the URL of the child sheet * @param aMedia the already-parsed media list for the child sheet - * @param aRule the @import rule importing this child. This is used to - * properly order the child sheet list of aParentSheet. + * @param aGeckoParentRule the @import rule importing this child, when using + * Gecko's style system. This is used to properly + * order the child sheet list of aParentSheet. + * @param aServoParentRule the @import rule importing this child, when using + * Servo's style system. * @param aSavedSheets any saved style sheets which could be reused * for this load */ nsresult LoadChildSheet(StyleSheet* aParentSheet, nsIURI* aURL, nsMediaList* aMedia, - ImportRule* aRule, + ImportRule* aGeckoParentRule, + RawServoImportRule* aServoParentRule, LoaderReusableStyleSheets* aSavedSheets); /** @@ -484,7 +488,8 @@ private: nsresult InsertChildSheet(StyleSheet* aSheet, StyleSheet* aParentSheet, - ImportRule* aParentRule); + ImportRule* aGeckoParentRule, + RawServoImportRule* aServoParentRule); nsresult InternalLoadNonDocumentSheet(nsIURI* aURL, bool aIsPreload, diff --git a/layout/style/ServoArcTypeList.h b/layout/style/ServoArcTypeList.h index ead8d80ef71e..8ebead199656 100644 --- a/layout/style/ServoArcTypeList.h +++ b/layout/style/ServoArcTypeList.h @@ -11,3 +11,4 @@ SERVO_ARC_TYPE(StyleSheet, RawServoStyleSheet) SERVO_ARC_TYPE(ComputedValues, ServoComputedValues) SERVO_ARC_TYPE(DeclarationBlock, RawServoDeclarationBlock) SERVO_ARC_TYPE(StyleRule, RawServoStyleRule) +SERVO_ARC_TYPE(ImportRule, RawServoImportRule) diff --git a/layout/style/ServoBindingList.h b/layout/style/ServoBindingList.h index 09280f6d1675..b7265df4deb7 100644 --- a/layout/style/ServoBindingList.h +++ b/layout/style/ServoBindingList.h @@ -26,12 +26,26 @@ SERVO_BINDING_FUNC(Servo_Element_ShouldTraverse, bool, RawGeckoElementBorrowed n SERVO_BINDING_FUNC(Servo_StyleSheet_Empty, RawServoStyleSheetStrong, mozilla::css::SheetParsingMode parsing_mode) SERVO_BINDING_FUNC(Servo_StyleSheet_FromUTF8Bytes, RawServoStyleSheetStrong, + mozilla::css::Loader* loader, + mozilla::ServoStyleSheet* gecko_stylesheet, const nsACString* data, mozilla::css::SheetParsingMode parsing_mode, const nsACString* base_url, ThreadSafeURIHolder* base, ThreadSafeURIHolder* referrer, ThreadSafePrincipalHolder* principal) +SERVO_BINDING_FUNC(Servo_ImportRule_GetSheet, + RawServoStyleSheetStrong, + const RawServoImportRuleBorrowed import_rule) +SERVO_BINDING_FUNC(Servo_StyleSheet_ClearAndUpdate, + void, + RawServoStyleSheetBorrowed stylesheet, + mozilla::css::Loader* loader, + mozilla::ServoStyleSheet* gecko_stylesheet, + const nsACString* data, + ThreadSafeURIHolder* base, + ThreadSafeURIHolder* referrer, + ThreadSafePrincipalHolder* principal) SERVO_BINDING_FUNC(Servo_StyleSheet_HasRules, bool, RawServoStyleSheetBorrowed sheet) SERVO_BINDING_FUNC(Servo_StyleSheet_GetRules, ServoCssRulesStrong, diff --git a/layout/style/ServoBindings.cpp b/layout/style/ServoBindings.cpp index 86299c8adfb2..edcb3ce5a10a 100644 --- a/layout/style/ServoBindings.cpp +++ b/layout/style/ServoBindings.cpp @@ -10,6 +10,7 @@ #include "StyleStructContext.h" #include "gfxFontFamilyList.h" #include "nsAttrValueInlines.h" +#include "nsCSSParser.h" #include "nsCSSRuleProcessor.h" #include "nsContentUtils.h" #include "nsDOMTokenList.h" @@ -20,6 +21,7 @@ #include "nsINode.h" #include "nsIPrincipal.h" #include "nsNameSpaceManager.h" +#include "nsNetUtil.h" #include "nsRuleNode.h" #include "nsString.h" #include "nsStyleStruct.h" @@ -1027,6 +1029,41 @@ Gecko_CSSValue_GetArrayItem(nsCSSValueBorrowedMut aCSSValue, int32_t aIndex) return &aCSSValue->GetArrayValue()->Item(aIndex); } +void +Gecko_LoadStyleSheet(css::Loader* aLoader, + ServoStyleSheet* aParent, + RawServoImportRuleStrong aImportRule, + const uint8_t* aURLString, + uint32_t aURLStringLength, + const uint8_t* aMediaString, + uint32_t aMediaStringLength) +{ + MOZ_ASSERT(aLoader, "Should've catched this before"); + MOZ_ASSERT(aParent, "Only used for @import, so parent should exist!"); + MOZ_ASSERT(aURLString, "Invalid URLs shouldn't be loaded!"); + RefPtr media = new nsMediaList(); + if (aMediaStringLength) { + MOZ_ASSERT(aMediaString); + // TODO(emilio, bug 1325878): This is not great, though this is going away + // soon anyway, when we can have a Servo-backed nsMediaList. + nsDependentCSubstring medium(reinterpret_cast(aMediaString), + aMediaStringLength); + nsCSSParser mediumParser(aLoader); + mediumParser.ParseMediaList( + NS_ConvertUTF8toUTF16(medium), nullptr, 0, media); + } + + nsDependentCSubstring urlSpec(reinterpret_cast(aURLString), + aURLStringLength); + + // Servo's loader guarantees that the URL is valid. + nsCOMPtr uri; + MOZ_ALWAYS_SUCCEEDS(NS_NewURI(getter_AddRefs(uri), urlSpec)); + + RefPtr import = aImportRule.Consume(); + aLoader->LoadChildSheet(aParent, uri, media, nullptr, import, nullptr); +} + NS_IMPL_THREADSAFE_FFI_REFCOUNTING(nsCSSValueSharedList, CSSValueSharedList); #define STYLE_STRUCT(name, checkdata_cb) \ diff --git a/layout/style/ServoBindings.h b/layout/style/ServoBindings.h index 3aa73933d847..5156803378ca 100644 --- a/layout/style/ServoBindings.h +++ b/layout/style/ServoBindings.h @@ -29,6 +29,7 @@ class nsIPrincipal; class nsIURI; struct nsFont; namespace mozilla { + class ServoStyleSheet; class FontFamilyList; enum FontFamilyType : uint32_t; } @@ -95,6 +96,13 @@ RawGeckoElementBorrowedOrNull Gecko_GetLastChildElement(RawGeckoElementBorrowed RawGeckoElementBorrowedOrNull Gecko_GetPrevSiblingElement(RawGeckoElementBorrowed element); RawGeckoElementBorrowedOrNull Gecko_GetNextSiblingElement(RawGeckoElementBorrowed element); RawGeckoElementBorrowedOrNull Gecko_GetDocumentElement(RawGeckoDocumentBorrowed document); +void Gecko_LoadStyleSheet(mozilla::css::Loader* loader, + mozilla::ServoStyleSheet* parent, + RawServoImportRuleStrong import_rule, + const uint8_t* url_bytes, + uint32_t url_length, + const uint8_t* media_bytes, + uint32_t media_length); // By default, Servo walks the DOM by traversing the siblings of the DOM-view // first child. This generally works, but misses anonymous children, which we diff --git a/layout/style/ServoStyleSheet.cpp b/layout/style/ServoStyleSheet.cpp index 0a689b9b2739..e6b72d7233f1 100644 --- a/layout/style/ServoStyleSheet.cpp +++ b/layout/style/ServoStyleSheet.cpp @@ -62,21 +62,17 @@ ServoStyleSheet::GetParentSheet() const void ServoStyleSheet::AppendStyleSheet(ServoStyleSheet* aSheet) { - // XXXheycam: When we implement support for child sheets, we'll have - // to fix SetOwningDocument to propagate the owning document down - // to the children. - MOZ_CRASH("stylo: not implemented"); + aSheet->mDocument = mDocument; } nsresult -ServoStyleSheet::ParseSheet(const nsAString& aInput, +ServoStyleSheet::ParseSheet(css::Loader* aLoader, + const nsAString& aInput, nsIURI* aSheetURI, nsIURI* aBaseURI, nsIPrincipal* aSheetPrincipal, uint32_t aLineNumber) { - DropSheet(); - RefPtr base = new ThreadSafeURIHolder(aBaseURI); RefPtr referrer = new ThreadSafeURIHolder(aSheetURI); RefPtr principal = @@ -87,8 +83,15 @@ ServoStyleSheet::ParseSheet(const nsAString& aInput, NS_ENSURE_SUCCESS(rv, rv); NS_ConvertUTF16toUTF8 input(aInput); - mSheet = Servo_StyleSheet_FromUTF8Bytes(&input, mParsingMode, &baseString, - base, referrer, principal).Consume(); + if (!mSheet) { + mSheet = + Servo_StyleSheet_FromUTF8Bytes(aLoader, this, &input, mParsingMode, + &baseString, base, referrer, + principal).Consume(); + } else { + Servo_StyleSheet_ClearAndUpdate(mSheet, aLoader, this, &input, base, + referrer, principal); + } return NS_OK; } diff --git a/layout/style/ServoStyleSheet.h b/layout/style/ServoStyleSheet.h index c86768b9dd0d..9b324355debc 100644 --- a/layout/style/ServoStyleSheet.h +++ b/layout/style/ServoStyleSheet.h @@ -18,6 +18,10 @@ namespace mozilla { class ServoCSSRuleList; +namespace css { +class Loader; +} + /** * CSS style sheet object that is a wrapper for a Servo Stylesheet. */ @@ -36,7 +40,8 @@ public: ServoStyleSheet* GetParentSheet() const; void AppendStyleSheet(ServoStyleSheet* aSheet); - MOZ_MUST_USE nsresult ParseSheet(const nsAString& aInput, + MOZ_MUST_USE nsresult ParseSheet(css::Loader* aLoader, + const nsAString& aInput, nsIURI* aSheetURI, nsIURI* aBaseURI, nsIPrincipal* aSheetPrincipal, @@ -56,6 +61,10 @@ public: #endif RawServoStyleSheet* RawSheet() const { return mSheet; } + void SetSheetForImport(RawServoStyleSheet* aSheet) { + MOZ_ASSERT(!mSheet); + mSheet = aSheet; + } // WebIDL StyleSheet API nsMediaList* Media() final; diff --git a/layout/style/nsCSSParser.cpp b/layout/style/nsCSSParser.cpp index 84203899fcaf..b91bdd35f5c0 100644 --- a/layout/style/nsCSSParser.cpp +++ b/layout/style/nsCSSParser.cpp @@ -3815,7 +3815,9 @@ CSSParserImpl::ProcessImport(const nsString& aURLSpec, } if (mChildLoader) { - mChildLoader->LoadChildSheet(mSheet, url, aMedia, rule, mReusableSheets); + mChildLoader->LoadChildSheet(mSheet, url, aMedia, rule, + /* aServoParentRule = */ nullptr, + mReusableSheets); } } diff --git a/layout/style/nsLayoutStylesheetCache.cpp b/layout/style/nsLayoutStylesheetCache.cpp index b259b1f121a9..99df44761756 100644 --- a/layout/style/nsLayoutStylesheetCache.cpp +++ b/layout/style/nsLayoutStylesheetCache.cpp @@ -971,7 +971,10 @@ nsLayoutStylesheetCache::BuildPreferenceSheet(RefPtr* aSheet, if (sheet->IsGecko()) { sheet->AsGecko()->ReparseSheet(sheetText); } else { - nsresult rv = sheet->AsServo()->ParseSheet(sheetText, uri, uri, nullptr, 0); + ServoStyleSheet* servoSheet = sheet->AsServo(); + // NB: The pref sheet never has @import rules. + nsresult rv = + servoSheet->ParseSheet(nullptr, sheetText, uri, uri, nullptr, 0); // Parsing the about:PreferenceStyleSheet URI can only fail on OOM. If we // are OOM before we parsed any documents we might as well abort. MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); From f5651bd75d78f523fb74c99799489cfc4ee7173e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Thu, 29 Dec 2016 18:33:47 +0100 Subject: [PATCH 121/229] Bug 1304792: Use borrowed types for ServoImportRule. r=Manishearth r=heycam MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MozReview-Commit-ID: HKjsOaE2qAp Signed-off-by: Emilio Cobos Álvarez --- layout/style/Loader.cpp | 4 ++-- layout/style/Loader.h | 4 ++-- layout/style/ServoBindings.cpp | 5 ++--- layout/style/ServoBindings.h | 2 +- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/layout/style/Loader.cpp b/layout/style/Loader.cpp index 50630806be9b..ccdf9ebd972d 100644 --- a/layout/style/Loader.cpp +++ b/layout/style/Loader.cpp @@ -1407,7 +1407,7 @@ nsresult Loader::InsertChildSheet(StyleSheet* aSheet, StyleSheet* aParentSheet, ImportRule* aGeckoParentRule, - RawServoImportRule* aServoParentRule) + const RawServoImportRule* aServoParentRule) { LOG(("css::Loader::InsertChildSheet")); MOZ_ASSERT(aSheet, "Nothing to insert"); @@ -2198,7 +2198,7 @@ Loader::LoadChildSheet(StyleSheet* aParentSheet, nsIURI* aURL, nsMediaList* aMedia, ImportRule* aGeckoParentRule, - RawServoImportRule* aServoParentRule, + const RawServoImportRule* aServoParentRule, LoaderReusableStyleSheets* aReusableSheets) { LOG(("css::Loader::LoadChildSheet")); diff --git a/layout/style/Loader.h b/layout/style/Loader.h index 583d88746438..a67498d67f65 100644 --- a/layout/style/Loader.h +++ b/layout/style/Loader.h @@ -297,7 +297,7 @@ public: nsIURI* aURL, nsMediaList* aMedia, ImportRule* aGeckoParentRule, - RawServoImportRule* aServoParentRule, + const RawServoImportRule* aServoParentRule, LoaderReusableStyleSheets* aSavedSheets); /** @@ -489,7 +489,7 @@ private: nsresult InsertChildSheet(StyleSheet* aSheet, StyleSheet* aParentSheet, ImportRule* aGeckoParentRule, - RawServoImportRule* aServoParentRule); + const RawServoImportRule* aServoParentRule); nsresult InternalLoadNonDocumentSheet(nsIURI* aURL, bool aIsPreload, diff --git a/layout/style/ServoBindings.cpp b/layout/style/ServoBindings.cpp index edcb3ce5a10a..352388a14afe 100644 --- a/layout/style/ServoBindings.cpp +++ b/layout/style/ServoBindings.cpp @@ -1032,7 +1032,7 @@ Gecko_CSSValue_GetArrayItem(nsCSSValueBorrowedMut aCSSValue, int32_t aIndex) void Gecko_LoadStyleSheet(css::Loader* aLoader, ServoStyleSheet* aParent, - RawServoImportRuleStrong aImportRule, + RawServoImportRuleBorrowed aImportRule, const uint8_t* aURLString, uint32_t aURLStringLength, const uint8_t* aMediaString, @@ -1060,8 +1060,7 @@ Gecko_LoadStyleSheet(css::Loader* aLoader, nsCOMPtr uri; MOZ_ALWAYS_SUCCEEDS(NS_NewURI(getter_AddRefs(uri), urlSpec)); - RefPtr import = aImportRule.Consume(); - aLoader->LoadChildSheet(aParent, uri, media, nullptr, import, nullptr); + aLoader->LoadChildSheet(aParent, uri, media, nullptr, aImportRule, nullptr); } NS_IMPL_THREADSAFE_FFI_REFCOUNTING(nsCSSValueSharedList, CSSValueSharedList); diff --git a/layout/style/ServoBindings.h b/layout/style/ServoBindings.h index 5156803378ca..37cccdff2783 100644 --- a/layout/style/ServoBindings.h +++ b/layout/style/ServoBindings.h @@ -98,7 +98,7 @@ RawGeckoElementBorrowedOrNull Gecko_GetNextSiblingElement(RawGeckoElementBorrowe RawGeckoElementBorrowedOrNull Gecko_GetDocumentElement(RawGeckoDocumentBorrowed document); void Gecko_LoadStyleSheet(mozilla::css::Loader* loader, mozilla::ServoStyleSheet* parent, - RawServoImportRuleStrong import_rule, + RawServoImportRuleBorrowed import_rule, const uint8_t* url_bytes, uint32_t url_length, const uint8_t* media_bytes, From a88f01d23a48faa40382074eedc9df03c32dd22f Mon Sep 17 00:00:00 2001 From: Robert Longson Date: Fri, 30 Dec 2016 16:36:05 +0000 Subject: [PATCH 122/229] Bug 1325858 - Redundant handles open for HKLM\SYSTEM\ControlSet001\Control\TimeZoneInformation r=andrebargull --- intl/icu-patches/bug-1325858-close-key.diff | 26 +++++++++++++++++++++ intl/icu/source/common/wintz.c | 2 ++ intl/update-icu.sh | 1 + 3 files changed, 29 insertions(+) create mode 100644 intl/icu-patches/bug-1325858-close-key.diff diff --git a/intl/icu-patches/bug-1325858-close-key.diff b/intl/icu-patches/bug-1325858-close-key.diff new file mode 100644 index 000000000000..8068f06182d7 --- /dev/null +++ b/intl/icu-patches/bug-1325858-close-key.diff @@ -0,0 +1,26 @@ +getTZKeyName in common/wintz.cpp leaks registry handle. + +https://ssl.icu-project.org/trac/ticket/12908 + +diff --git a/intl/icu/source/common/wintz.c b/intl/icu/source/common/wintz.c +--- a/intl/icu/source/common/wintz.c ++++ b/intl/icu/source/common/wintz.c +@@ -211,16 +211,18 @@ static LONG getTZKeyName(char* tzKeyName + hkey, + "TimeZoneKeyName", + NULL, + NULL, + (LPBYTE)tzKeyName, + &cbData); + } + ++ RegCloseKey(hkey); ++ + return result; + } + + /* + This code attempts to detect the Windows time zone, as set in the + Windows Date and Time control panel. It attempts to work on + multiple flavors of Windows (9x, Me, NT, 2000, XP) and on localized + installs. It works by directly interrogating the registry and diff --git a/intl/icu/source/common/wintz.c b/intl/icu/source/common/wintz.c index a8696af39d4a..14fc476040c7 100644 --- a/intl/icu/source/common/wintz.c +++ b/intl/icu/source/common/wintz.c @@ -216,6 +216,8 @@ static LONG getTZKeyName(char* tzKeyName, int32_t length) { &cbData); } + RegCloseKey(hkey); + return result; } diff --git a/intl/update-icu.sh b/intl/update-icu.sh index 8311dc6cc9fb..7dc54eb6f9d3 100755 --- a/intl/update-icu.sh +++ b/intl/update-icu.sh @@ -61,6 +61,7 @@ for patch in \ bug-1172609-timezone-recreateDefault.diff \ bug-1198952-workaround-make-3.82-bug.diff \ bug-1228227-bug-1263325-libc++-gcc_hidden.diff \ + bug-1325858-close-key.diff \ ucol_getKeywordValuesForLocale-ulist_resetList.diff \ unum_formatDoubleForFields.diff \ ; do From d771af8608ef9f9f87f0d565733ed382dc07462a Mon Sep 17 00:00:00 2001 From: Tom Schuster Date: Fri, 30 Dec 2016 17:38:08 +0100 Subject: [PATCH 123/229] Bug 1324566 - Port Baseline GlobalNameAccessor to CacheIR. r=jandem --- js/src/jit/BaselineCacheIRCompiler.cpp | 8 +- js/src/jit/BaselineDebugModeOSR.cpp | 1 - js/src/jit/BaselineIC.cpp | 213 ++++++---------------- js/src/jit/BaselineInspector.cpp | 38 +--- js/src/jit/CacheIR.cpp | 115 +++++++++--- js/src/jit/CacheIR.h | 1 + js/src/jit/SharedIC.cpp | 238 ------------------------- js/src/jit/SharedIC.h | 156 ---------------- js/src/jit/SharedICList.h | 1 - js/src/jit/VMFunctions.cpp | 18 ++ js/src/jit/VMFunctions.h | 5 + 11 files changed, 175 insertions(+), 619 deletions(-) diff --git a/js/src/jit/BaselineCacheIRCompiler.cpp b/js/src/jit/BaselineCacheIRCompiler.cpp index 9759226ec928..5e38dc101cd5 100644 --- a/js/src/jit/BaselineCacheIRCompiler.cpp +++ b/js/src/jit/BaselineCacheIRCompiler.cpp @@ -415,9 +415,9 @@ BaselineCacheIRCompiler::emitCallScriptedGetterResult() return true; } -typedef bool (*DoCallNativeGetterFn)(JSContext*, HandleFunction, HandleObject, MutableHandleValue); -static const VMFunction DoCallNativeGetterInfo = - FunctionInfo(DoCallNativeGetter, "DoCallNativeGetter"); +typedef bool (*CallNativeGetterFn)(JSContext*, HandleFunction, HandleObject, MutableHandleValue); +static const VMFunction CallNativeGetterInfo = + FunctionInfo(CallNativeGetter, "CallNativeGetter"); bool BaselineCacheIRCompiler::emitCallNativeGetterResult() @@ -439,7 +439,7 @@ BaselineCacheIRCompiler::emitCallNativeGetterResult() masm.Push(obj); masm.Push(scratch); - if (!callVM(masm, DoCallNativeGetterInfo)) + if (!callVM(masm, CallNativeGetterInfo)) return false; stubFrame.leave(masm); diff --git a/js/src/jit/BaselineDebugModeOSR.cpp b/js/src/jit/BaselineDebugModeOSR.cpp index eac27aa3a2da..d3e57ea76a4d 100644 --- a/js/src/jit/BaselineDebugModeOSR.cpp +++ b/js/src/jit/BaselineDebugModeOSR.cpp @@ -698,7 +698,6 @@ RecompileBaselineScriptForDebugMode(JSContext* cx, JSScript* script, _(Call_ScriptedApplyArray) \ _(Call_ScriptedApplyArguments) \ _(Call_ScriptedFunCall) \ - _(GetProp_CallNativeGlobal) \ _(GetProp_Generic) \ _(SetProp_CallScripted) \ _(SetProp_CallNative) diff --git a/js/src/jit/BaselineIC.cpp b/js/src/jit/BaselineIC.cpp index 3f5b67587a88..d901295fd268 100644 --- a/js/src/jit/BaselineIC.cpp +++ b/js/src/jit/BaselineIC.cpp @@ -435,10 +435,6 @@ ICTypeUpdate_ObjectGroup::Compiler::generateStubCode(MacroAssembler& masm) return true; } -typedef bool (*DoCallNativeGetterFn)(JSContext*, HandleFunction, HandleObject, MutableHandleValue); -static const VMFunction DoCallNativeGetterInfo = - FunctionInfo(DoCallNativeGetter, "DoCallNativeGetter"); - // // ToBool_Fallback // @@ -2357,133 +2353,6 @@ ICIn_Dense::Compiler::generateStubCode(MacroAssembler& masm) return true; } -// Try to update existing SetProp setter call stubs for the given holder in -// place with a new shape and setter. -static bool -UpdateExistingSetPropCallStubs(ICSetProp_Fallback* fallbackStub, - ICStub::Kind kind, - NativeObject* holder, - JSObject* receiver, - JSFunction* setter) -{ - MOZ_ASSERT(kind == ICStub::SetProp_CallScripted || - kind == ICStub::SetProp_CallNative); - MOZ_ASSERT(holder); - MOZ_ASSERT(receiver); - - bool isOwnSetter = (holder == receiver); - bool foundMatchingStub = false; - ReceiverGuard receiverGuard(receiver); - for (ICStubConstIterator iter = fallbackStub->beginChainConst(); !iter.atEnd(); iter++) { - if (iter->kind() == kind) { - ICSetPropCallSetter* setPropStub = static_cast(*iter); - if (setPropStub->holder() == holder && setPropStub->isOwnSetter() == isOwnSetter) { - // If this is an own setter, update the receiver guard as well, - // since that's the shape we'll be guarding on. Furthermore, - // isOwnSetter() relies on holderShape_ and receiverGuard_ being - // the same shape. - if (isOwnSetter) - setPropStub->receiverGuard().update(receiverGuard); - - MOZ_ASSERT(setPropStub->holderShape() != holder->lastProperty() || - !setPropStub->receiverGuard().matches(receiverGuard), - "Why didn't we end up using this stub?"); - - // We want to update the holder shape to match the new one no - // matter what, even if the receiver shape is different. - setPropStub->holderShape() = holder->lastProperty(); - - // Make sure to update the setter, since a shape change might - // have changed which setter we want to use. - setPropStub->setter() = setter; - if (setPropStub->receiverGuard().matches(receiverGuard)) - foundMatchingStub = true; - } - } - } - - return foundMatchingStub; -} - -// Attach an optimized stub for a GETGNAME/CALLGNAME getter op. -static bool -TryAttachGlobalNameAccessorStub(JSContext* cx, HandleScript script, jsbytecode* pc, - ICGetName_Fallback* stub, - Handle globalLexical, - HandlePropertyName name, bool* attached, - bool* isTemporarilyUnoptimizable) -{ - MOZ_ASSERT(globalLexical->isGlobal()); - RootedId id(cx, NameToId(name)); - - // There must not be a shadowing binding on the global lexical scope. - if (globalLexical->lookup(cx, id)) - return true; - - RootedGlobalObject global(cx, &globalLexical->global()); - - // The property must be found, and it must be found as a normal data property. - RootedShape shape(cx); - RootedNativeObject current(cx, global); - while (true) { - shape = current->lookup(cx, id); - if (shape) - break; - JSObject* proto = current->staticPrototype(); - if (!proto || !proto->is()) - return true; - current = &proto->as(); - } - - // Instantiate this global property, for use during Ion compilation. - if (IsIonEnabled(cx)) - EnsureTrackPropertyTypes(cx, current, id); - - // Try to add a getter stub. We don't handle scripted getters yet; if this - // changes we need to make sure IonBuilder::getPropTryCommonGetter (which - // requires a Baseline stub) handles non-outerized this objects correctly. - bool isScripted; - if (IsCacheableGetPropCall(cx, global, current, shape, &isScripted, isTemporarilyUnoptimizable) && - !isScripted) - { - ICStub* monitorStub = stub->fallbackMonitorStub()->firstMonitorStub(); - RootedFunction getter(cx, &shape->getterObject()->as()); - - // The CallNativeGlobal stub needs to generate 3 shape checks: - // - // 1. The global lexical scope shape check. - // 2. The global object shape check. - // 3. The holder shape check. - // - // 1 is done as the receiver check, as for GETNAME the global lexical scope is in the - // receiver position. 2 is done as a manual check that other GetProp stubs don't do. 3 is - // done as the holder check per normal. - // - // In the case the holder is the global object, check 2 is redundant but is not yet - // optimized away. - JitSpew(JitSpew_BaselineIC, " Generating GetName(GlobalName/NativeGetter) stub"); - if (UpdateExistingGetPropCallStubs(stub, ICStub::GetProp_CallNativeGlobal, current, - globalLexical, getter)) - { - *attached = true; - return true; - } - ICGetPropCallNativeCompiler compiler(cx, ICStub::GetProp_CallNativeGlobal, - ICStubCompiler::Engine::Baseline, - monitorStub, globalLexical, current, - getter, script->pcToOffset(pc), - /* inputDefinitelyObject = */ true); - - ICStub* newStub = compiler.getStub(compiler.getStubSpace(script)); - if (!newStub) - return false; - - stub->addNewStub(newStub); - *attached = true; - } - return true; -} - static bool DoGetNameFallback(JSContext* cx, BaselineFrame* frame, ICGetName_Fallback* stub_, HandleObject envChain, MutableHandleValue res) @@ -2502,7 +2371,6 @@ DoGetNameFallback(JSContext* cx, BaselineFrame* frame, ICGetName_Fallback* stub_ RootedPropertyName name(cx, script->getName(pc)); bool attached = false; - bool isTemporarilyUnoptimizable = false; // Attach new stub. if (stub->numOptimizedStubs() >= ICGetName_Fallback::MAX_OPTIMIZED_STUBS) { @@ -2510,12 +2378,16 @@ DoGetNameFallback(JSContext* cx, BaselineFrame* frame, ICGetName_Fallback* stub_ attached = true; } - if (!attached && IsGlobalOp(JSOp(*pc)) && !script->hasNonSyntacticScope()) { - if (!TryAttachGlobalNameAccessorStub(cx, script, pc, stub, - envChain.as(), - name, &attached, &isTemporarilyUnoptimizable)) - { - return false; + if (!attached && !JitOptions.disableCacheIR) { + ICStubEngine engine = ICStubEngine::Baseline; + GetNameIRGenerator gen(cx, pc, script, envChain, name); + if (gen.tryAttachStub()) { + ICStub* newStub = AttachBaselineCacheIRStub(cx, gen.writerRef(), gen.cacheKind(), + engine, info.outerScript(cx), stub); + if (newStub) { + JitSpew(JitSpew_BaselineIC, " Attached CacheIR stub"); + attached = true; + } } } @@ -2538,23 +2410,8 @@ DoGetNameFallback(JSContext* cx, BaselineFrame* frame, ICGetName_Fallback* stub_ // Add a type monitor stub for the resulting value. if (!stub->addMonitorStubForValue(cx, &info, res)) return false; - if (attached) - return true; - if (!JitOptions.disableCacheIR) { - ICStubEngine engine = ICStubEngine::Baseline; - GetNameIRGenerator gen(cx, pc, script, envChain, name); - if (gen.tryAttachStub()) { - ICStub* newStub = AttachBaselineCacheIRStub(cx, gen.writerRef(), gen.cacheKind(), - engine, info.outerScript(cx), stub); - if (newStub) { - JitSpew(JitSpew_BaselineIC, " Attached CacheIR stub"); - attached = true; - } - } - } - - if (!attached && !isTemporarilyUnoptimizable) + if (!attached) stub->noteUnoptimizableAccess(); return true; } @@ -2803,6 +2660,54 @@ TryAttachSetValuePropStub(JSContext* cx, HandleScript script, jsbytecode* pc, IC return true; } +// Try to update existing SetProp setter call stubs for the given holder in +// place with a new shape and setter. +static bool +UpdateExistingSetPropCallStubs(ICSetProp_Fallback* fallbackStub, + ICStub::Kind kind, + NativeObject* holder, + JSObject* receiver, + JSFunction* setter) +{ + MOZ_ASSERT(kind == ICStub::SetProp_CallScripted || + kind == ICStub::SetProp_CallNative); + MOZ_ASSERT(holder); + MOZ_ASSERT(receiver); + + bool isOwnSetter = (holder == receiver); + bool foundMatchingStub = false; + ReceiverGuard receiverGuard(receiver); + for (ICStubConstIterator iter = fallbackStub->beginChainConst(); !iter.atEnd(); iter++) { + if (iter->kind() == kind) { + ICSetPropCallSetter* setPropStub = static_cast(*iter); + if (setPropStub->holder() == holder && setPropStub->isOwnSetter() == isOwnSetter) { + // If this is an own setter, update the receiver guard as well, + // since that's the shape we'll be guarding on. Furthermore, + // isOwnSetter() relies on holderShape_ and receiverGuard_ being + // the same shape. + if (isOwnSetter) + setPropStub->receiverGuard().update(receiverGuard); + + MOZ_ASSERT(setPropStub->holderShape() != holder->lastProperty() || + !setPropStub->receiverGuard().matches(receiverGuard), + "Why didn't we end up using this stub?"); + + // We want to update the holder shape to match the new one no + // matter what, even if the receiver shape is different. + setPropStub->holderShape() = holder->lastProperty(); + + // Make sure to update the setter, since a shape change might + // have changed which setter we want to use. + setPropStub->setter() = setter; + if (setPropStub->receiverGuard().matches(receiverGuard)) + foundMatchingStub = true; + } + } + } + + return foundMatchingStub; +} + // Attach an optimized property set stub for a SETPROP/SETGNAME/SETNAME op on // an accessor property. static bool diff --git a/js/src/jit/BaselineInspector.cpp b/js/src/jit/BaselineInspector.cpp index 2d7fa53fe709..19ef458f4be2 100644 --- a/js/src/jit/BaselineInspector.cpp +++ b/js/src/jit/BaselineInspector.cpp @@ -670,22 +670,6 @@ BaselineInspector::templateCallObject() return &res->as(); } -static Shape* -GlobalShapeForGetPropFunction(ICStub* stub) -{ - if (stub->isGetProp_CallNativeGlobal()) { - ICGetProp_CallNativeGlobal* nstub = stub->toGetProp_CallNativeGlobal(); - if (nstub->isOwnGetter()) - return nullptr; - - Shape* shape = nstub->globalShape(); - MOZ_ASSERT(shape->getObjectClass()->flags & JSCLASS_IS_GLOBAL); - return shape; - } - - return nullptr; -} - static bool MatchCacheIRReceiverGuard(CacheIRReader& reader, ICCacheIR_Monitored* stub, ObjOperandId objId, ReceiverGuard* receiver) @@ -880,27 +864,7 @@ BaselineInspector::commonGetPropFunction(jsbytecode* pc, bool innerized, const ICEntry& entry = icEntryFromPC(pc); for (ICStub* stub = entry.firstStub(); stub; stub = stub->next()) { - if (stub->isGetProp_CallNativeGlobal()) { - ICGetPropCallGetter* nstub = static_cast(stub); - bool isOwn = nstub->isOwnGetter(); - if (!isOwn && !AddReceiver(nstub->receiverGuard(), receivers, convertUnboxedGroups)) - return false; - - if (!*commonGetter) { - *holder = isOwn ? nullptr : nstub->holder().get(); - *holderShape = nstub->holderShape(); - *commonGetter = nstub->getter(); - *globalShape = GlobalShapeForGetPropFunction(nstub); - *isOwnProperty = isOwn; - } else if (nstub->holderShape() != *holderShape || - GlobalShapeForGetPropFunction(nstub) != *globalShape || - isOwn != *isOwnProperty) - { - return false; - } else { - MOZ_ASSERT(*commonGetter == nstub->getter()); - } - } else if (stub->isCacheIR_Monitored()) { + if (stub->isCacheIR_Monitored()) { if (!AddCacheIRGetPropFunction(stub->toCacheIR_Monitored(), innerized, holder, holderShape, commonGetter, globalShape, isOwnProperty, receivers, diff --git a/js/src/jit/CacheIR.cpp b/js/src/jit/CacheIR.cpp index 91a71ddac79c..45c9dace8620 100644 --- a/js/src/jit/CacheIR.cpp +++ b/js/src/jit/CacheIR.cpp @@ -1161,12 +1161,44 @@ GetNameIRGenerator::tryAttachStub() if (tryAttachGlobalNameValue(envId, id)) return true; + if (tryAttachGlobalNameGetter(envId, id)) + return true; if (tryAttachEnvironmentName(envId, id)) return true; return false; } +bool +CanAttachGlobalName(JSContext* cx, Handle globalLexical, HandleId id, + MutableHandleNativeObject holder, MutableHandleShape shape) +{ + // The property must be found, and it must be found as a normal data property. + RootedNativeObject current(cx, globalLexical); + while (true) { + shape.set(current->lookup(cx, id)); + if (shape) + break; + + if (current == globalLexical) { + current = &globalLexical->global(); + } else { + // In the browser the global prototype chain should be immutable. + if (!current->staticPrototypeIsImmutable()) + return false; + + JSObject* proto = current->staticPrototype(); + if (!proto || !proto->is()) + return false; + + current = &proto->as(); + } + } + + holder.set(current); + return true; +} + bool GetNameIRGenerator::tryAttachGlobalNameValue(ObjOperandId objId, HandleId id) { @@ -1176,44 +1208,31 @@ GetNameIRGenerator::tryAttachGlobalNameValue(ObjOperandId objId, HandleId id) Handle globalLexical = env_.as(); MOZ_ASSERT(globalLexical->isGlobal()); - // The property must be found, and it must be found as a normal data property. - RootedShape shape(cx_); - RootedNativeObject current(cx_, globalLexical); - while (true) { - shape = current->lookup(cx_, id); - if (shape) - break; - if (current == globalLexical) { - current = &globalLexical->global(); - } else { - // In the browser the global prototype chain should be immutable. - if (!current->staticPrototypeIsImmutable()) - return false; - JSObject* proto = current->staticPrototype(); - if (!proto || !proto->is()) - return false; - current = &proto->as(); - } - } + RootedNativeObject holder(cx_); + RootedShape shape(cx_); + if (!CanAttachGlobalName(cx_, globalLexical, id, &holder, &shape)) + return false; + + // The property must be found, and it must be found as a normal data property. if (!shape->hasDefaultGetter() || !shape->hasSlot()) return false; // Instantiate this global property, for use during Ion compilation. if (IsIonEnabled(cx_)) - EnsureTrackPropertyTypes(cx_, current, id); + EnsureTrackPropertyTypes(cx_, holder, id); - if (current == globalLexical) { + if (holder == globalLexical) { // There is no need to guard on the shape. Lexical bindings are // non-configurable, and this stub cannot be shared across globals. - size_t dynamicSlotOffset = current->dynamicSlotIndex(shape->slot()) * sizeof(Value); + size_t dynamicSlotOffset = holder->dynamicSlotIndex(shape->slot()) * sizeof(Value); writer.loadDynamicSlotResult(objId, dynamicSlotOffset); } else { - // Check the prototype chain from the global to the current + // Check the prototype chain from the global to the holder // prototype. Ignore the global lexical scope as it doesn't figure // into the prototype chain. We guard on the global lexical // scope's shape independently. - if (!IsCacheableGetPropReadSlotForIonOrCacheIR(&globalLexical->global(), current, shape)) + if (!IsCacheableGetPropReadSlotForIonOrCacheIR(&globalLexical->global(), holder, shape)) return false; // Shape guard for global lexical. @@ -1224,19 +1243,59 @@ GetNameIRGenerator::tryAttachGlobalNameValue(ObjOperandId objId, HandleId id) writer.guardShape(globalId, globalLexical->global().lastProperty()); ObjOperandId holderId = globalId; - if (current != &globalLexical->global()) { + if (holder != &globalLexical->global()) { // Shape guard holder. - holderId = writer.loadObject(current); - writer.guardShape(holderId, current->lastProperty()); + holderId = writer.loadObject(holder); + writer.guardShape(holderId, holder->lastProperty()); } - EmitLoadSlotResult(writer, holderId, current, shape); + EmitLoadSlotResult(writer, holderId, holder, shape); } writer.typeMonitorResult(); return true; } +bool +GetNameIRGenerator::tryAttachGlobalNameGetter(ObjOperandId objId, HandleId id) +{ + if (!IsGlobalOp(JSOp(*pc_)) || script_->hasNonSyntacticScope()) + return false; + + Handle globalLexical = env_.as(); + MOZ_ASSERT(globalLexical->isGlobal()); + + RootedNativeObject holder(cx_); + RootedShape shape(cx_); + if (!CanAttachGlobalName(cx_, globalLexical, id, &holder, &shape)) + return false; + + if (holder == globalLexical) + return false; + + if (!IsCacheableGetPropCallNative(&globalLexical->global(), holder, shape)) + return false; + + if (IsIonEnabled(cx_)) + EnsureTrackPropertyTypes(cx_, holder, id); + + // Shape guard for global lexical. + writer.guardShape(objId, globalLexical->lastProperty()); + + // Guard on the shape of the GlobalObject. + ObjOperandId globalId = writer.loadEnclosingEnvironment(objId); + writer.guardShape(globalId, globalLexical->global().lastProperty()); + + if (holder != &globalLexical->global()) { + // Shape guard holder. + ObjOperandId holderId = writer.loadObject(holder); + writer.guardShape(holderId, holder->lastProperty()); + } + + EmitCallGetterResultNoGuards(writer, &globalLexical->global(), holder, shape, globalId); + return true; +} + bool GetNameIRGenerator::tryAttachEnvironmentName(ObjOperandId objId, HandleId id) { diff --git a/js/src/jit/CacheIR.h b/js/src/jit/CacheIR.h index 216ba3cff95c..8522d01d9a84 100644 --- a/js/src/jit/CacheIR.h +++ b/js/src/jit/CacheIR.h @@ -802,6 +802,7 @@ class MOZ_RAII GetNameIRGenerator : public IRGenerator HandlePropertyName name_; bool tryAttachGlobalNameValue(ObjOperandId objId, HandleId id); + bool tryAttachGlobalNameGetter(ObjOperandId objId, HandleId id); bool tryAttachEnvironmentName(ObjOperandId objId, HandleId id); public: diff --git a/js/src/jit/SharedIC.cpp b/js/src/jit/SharedIC.cpp index 3967b9288948..b6bade1cb00a 100644 --- a/js/src/jit/SharedIC.cpp +++ b/js/src/jit/SharedIC.cpp @@ -175,7 +175,6 @@ ICStub::NonCacheIRStubMakesGCCalls(Kind kind) case Call_ScriptedFunCall: case Call_StringSplit: case WarmUpCounter_Fallback: - case GetProp_CallNativeGlobal: case GetProp_Generic: case SetProp_CallScripted: case SetProp_CallNative: @@ -352,15 +351,6 @@ ICStub::trace(JSTracer* trc) TraceEdge(trc, &constantStub->value(), "baseline-getintrinsic-constant-value"); break; } - case ICStub::GetProp_CallNativeGlobal: { - ICGetProp_CallNativeGlobal* callStub = toGetProp_CallNativeGlobal(); - callStub->receiverGuard().trace(trc); - TraceEdge(trc, &callStub->holder(), "baseline-getpropcallnativeglobal-stub-holder"); - TraceEdge(trc, &callStub->holderShape(), "baseline-getpropcallnativeglobal-stub-holdershape"); - TraceEdge(trc, &callStub->globalShape(), "baseline-getpropcallnativeglobal-stub-globalshape"); - TraceEdge(trc, &callStub->getter(), "baseline-getpropcallnativeglobal-stub-getter"); - break; - } case ICStub::SetProp_Native: { ICSetProp_Native* propStub = toSetProp_Native(); TraceEdge(trc, &propStub->shape(), "baseline-setpropnative-stub-shape"); @@ -2108,68 +2098,6 @@ IsCacheableGetPropCall(JSContext* cx, JSObject* obj, JSObject* holder, Shape* sh return true; } -// Try to update all existing GetProp/GetName getter call stubs that match the -// given holder in place with a new shape and getter. fallbackStub can be -// either an ICGetProp_Fallback or an ICGetName_Fallback. -// -// If 'getter' is an own property, holder == receiver must be true. -bool -UpdateExistingGetPropCallStubs(ICFallbackStub* fallbackStub, - ICStub::Kind kind, - HandleNativeObject holder, - HandleObject receiver, - HandleFunction getter) -{ - MOZ_ASSERT(kind == ICStub::GetProp_CallNativeGlobal); - MOZ_ASSERT(fallbackStub->isGetName_Fallback() || - fallbackStub->isGetProp_Fallback()); - MOZ_ASSERT(holder); - MOZ_ASSERT(receiver); - - bool isOwnGetter = (holder == receiver); - bool foundMatchingStub = false; - ReceiverGuard receiverGuard(receiver); - for (ICStubConstIterator iter = fallbackStub->beginChainConst(); !iter.atEnd(); iter++) { - if (iter->kind() == kind) { - ICGetPropCallGetter* getPropStub = static_cast(*iter); - if (getPropStub->holder() == holder && getPropStub->isOwnGetter() == isOwnGetter) { - // If this is an own getter, update the receiver guard as well, - // since that's the shape we'll be guarding on. Furthermore, - // isOwnGetter() relies on holderShape_ and receiverGuard_ being - // the same shape. - if (isOwnGetter) - getPropStub->receiverGuard().update(receiverGuard); - - MOZ_ASSERT(getPropStub->holderShape() != holder->lastProperty() || - !getPropStub->receiverGuard().matches(receiverGuard) || - getPropStub->toGetProp_CallNativeGlobal()->globalShape() != - receiver->as().global().lastProperty(), - "Why didn't we end up using this stub?"); - - // We want to update the holder shape to match the new one no - // matter what, even if the receiver shape is different. - getPropStub->holderShape() = holder->lastProperty(); - - // Make sure to update the getter, since a shape change might - // have changed which getter we want to use. - getPropStub->getter() = getter; - - if (getPropStub->isGetProp_CallNativeGlobal()) { - ICGetProp_CallNativeGlobal* globalStub = - getPropStub->toGetProp_CallNativeGlobal(); - globalStub->globalShape() = - receiver->as().global().lastProperty(); - } - - if (getPropStub->receiverGuard().matches(receiverGuard)) - foundMatchingStub = true; - } - } - } - - return foundMatchingStub; -} - bool CheckHasNoSuchProperty(JSContext* cx, JSObject* obj, jsid id, JSObject** lastProto, size_t* protoChainDepthOut) @@ -2430,18 +2358,6 @@ GuardReceiverObject(MacroAssembler& masm, ReceiverGuard guard, } } -static void -GuardGlobalObject(MacroAssembler& masm, HandleObject holder, Register globalLexicalReg, - Register holderReg, Register scratch, size_t globalShapeOffset, Label* failure) -{ - if (holder->is()) - return; - masm.extractObject(Address(globalLexicalReg, EnvironmentObject::offsetOfEnclosingEnvironment()), - holderReg); - masm.loadPtr(Address(ICStubReg, globalShapeOffset), scratch); - masm.branchTestObjShape(Assembler::NotEqual, holderReg, scratch, failure); -} - bool GetProtoShapes(JSObject* obj, size_t protoChainDepth, MutableHandle shapes) { @@ -2457,135 +2373,6 @@ GetProtoShapes(JSObject* obj, size_t protoChainDepth, MutableHandle return true; } -// -// VM function to help call native getters. -// - -bool -DoCallNativeGetter(JSContext* cx, HandleFunction callee, HandleObject obj, - MutableHandleValue result) -{ - MOZ_ASSERT(callee->isNative()); - JSNative natfun = callee->native(); - - JS::AutoValueArray<2> vp(cx); - vp[0].setObject(*callee.get()); - vp[1].setObject(*obj.get()); - - if (!natfun(cx, 0, vp.begin())) - return false; - - result.set(vp[0]); - return true; -} - -typedef bool (*DoCallNativeGetterFn)(JSContext*, HandleFunction, HandleObject, MutableHandleValue); -static const VMFunction DoCallNativeGetterInfo = - FunctionInfo(DoCallNativeGetter, "DoCallNativeGetter"); - -bool -ICGetPropCallNativeCompiler::generateStubCode(MacroAssembler& masm) -{ - Label failure; - - AllocatableGeneralRegisterSet regs(availableGeneralRegs(1)); - Register objReg = InvalidReg; - - if (inputDefinitelyObject_) { - objReg = R0.scratchReg(); - } else { - // Guard input is an object and unbox. - masm.branchTestObject(Assembler::NotEqual, R0, &failure); - objReg = masm.extractObject(R0, ExtractTemp0); - } - - Register scratch = regs.takeAnyExcluding(ICTailCallReg); - - // Shape guard. - GuardReceiverObject(masm, ReceiverGuard(receiver_), objReg, scratch, - ICGetPropCallGetter::offsetOfReceiverGuard(), &failure); - - if (receiver_ != holder_) { - Register holderReg = regs.takeAny(); - - // If we are generating a non-lexical GETGNAME stub, we must also - // guard on the shape of the GlobalObject. - if (kind == ICStub::GetProp_CallNativeGlobal) { - MOZ_ASSERT(receiver_->is() && - receiver_->as().isGlobal()); - GuardGlobalObject(masm, holder_, objReg, holderReg, scratch, - ICGetProp_CallNativeGlobal::offsetOfGlobalShape(), &failure); - } - - masm.loadPtr(Address(ICStubReg, ICGetPropCallGetter::offsetOfHolder()), holderReg); - masm.loadPtr(Address(ICStubReg, ICGetPropCallGetter::offsetOfHolderShape()), scratch); - masm.branchTestObjShape(Assembler::NotEqual, holderReg, scratch, &failure); - regs.add(holderReg); - } - - // Box and push obj onto baseline frame stack for decompiler - if (engine_ == Engine::Baseline) { - if (inputDefinitelyObject_) - masm.tagValue(JSVAL_TYPE_OBJECT, objReg, R0); - EmitStowICValues(masm, 1); - if (inputDefinitelyObject_) - objReg = masm.extractObject(R0, ExtractTemp0); - } - - // Push a stub frame so that we can perform a non-tail call. - enterStubFrame(masm, scratch); - - // Load callee function. - Register callee = regs.takeAny(); - masm.loadPtr(Address(ICStubReg, ICGetPropCallGetter::offsetOfGetter()), callee); - - // If we're calling a getter on the global, inline the logic for the - // 'this' hook on the global lexical scope and manually push the global. - if (kind == ICStub::GetProp_CallNativeGlobal) - masm.extractObject(Address(objReg, EnvironmentObject::offsetOfEnclosingEnvironment()), - objReg); - - // Push args for vm call. - masm.Push(objReg); - masm.Push(callee); - - regs.add(R0); - - if (!callVM(DoCallNativeGetterInfo, masm)) - return false; - leaveStubFrame(masm); - - if (engine_ == Engine::Baseline) - EmitUnstowICValues(masm, 1, /* discard = */true); - - // Enter type monitor IC to type-check result. - EmitEnterTypeMonitorIC(masm); - - // Failure case - jump to next stub - masm.bind(&failure); - EmitStubGuardFailure(masm); - return true; -} - -ICStub* -ICGetPropCallNativeCompiler::getStub(ICStubSpace* space) -{ - ReceiverGuard guard(receiver_); - Shape* holderShape = holder_->as().lastProperty(); - - switch (kind) { - case ICStub::GetProp_CallNativeGlobal: { - Shape* globalShape = receiver_->as().global().lastProperty(); - return newStub(space, getStubCode(), firstMonitorStub_, - guard, holder_, holderShape, globalShape, - getter_, pcOffset_); - } - - default: - MOZ_CRASH("Bad stub kind"); - } -} - /* static */ ICGetProp_Generic* ICGetProp_Generic::Clone(JSContext* cx, ICStubSpace* space, ICStub* firstMonitorStub, ICGetProp_Generic& other) @@ -2678,31 +2465,6 @@ BaselineScript::noteAccessedGetter(uint32_t pcOffset) stub->toGetProp_Fallback()->noteAccessedGetter(); } -ICGetPropCallGetter::ICGetPropCallGetter(Kind kind, JitCode* stubCode, ICStub* firstMonitorStub, - ReceiverGuard receiverGuard, JSObject* holder, - Shape* holderShape, JSFunction* getter, - uint32_t pcOffset) - : ICMonitoredStub(kind, stubCode, firstMonitorStub), - receiverGuard_(receiverGuard), - holder_(holder), - holderShape_(holderShape), - getter_(getter), - pcOffset_(pcOffset) -{ - MOZ_ASSERT(kind == ICStub::GetProp_CallNativeGlobal); -} - -/* static */ ICGetProp_CallNativeGlobal* -ICGetProp_CallNativeGlobal::Clone(JSContext* cx, ICStubSpace* space, ICStub* firstMonitorStub, - ICGetProp_CallNativeGlobal& other) -{ - return New(cx, space, other.jitCode(), firstMonitorStub, - other.receiverGuard(), other.holder_, - other.holderShape_, other.globalShape_, - other.getter_, other.pcOffset_); -} - -// // TypeMonitor_Fallback // diff --git a/js/src/jit/SharedIC.h b/js/src/jit/SharedIC.h index 184ca2bb95d4..099bde8134a0 100644 --- a/js/src/jit/SharedIC.h +++ b/js/src/jit/SharedIC.h @@ -2256,10 +2256,6 @@ GetProtoShapes(JSObject* obj, size_t protoChainDepth, MutableHandle void CheckForTypedObjectWithDetachedStorage(JSContext* cx, MacroAssembler& masm, Label* failure); -MOZ_MUST_USE bool -DoCallNativeGetter(JSContext* cx, HandleFunction callee, HandleObject obj, - MutableHandleValue result); - void LoadTypedThingData(MacroAssembler& masm, TypedThingLayout layout, Register obj, Register result); @@ -2384,158 +2380,6 @@ ReferenceTypeFromSimpleTypeDescrKey(uint32_t key) return ReferenceTypeDescr::Type(key >> 1); } -class ICGetPropCallGetter : public ICMonitoredStub -{ - friend class ICStubSpace; - - protected: - // Shape/group of receiver object. Used for both own and proto getters. - // In the GetPropCallDOMProxyNative case, the receiver guard enforces - // the proxy handler, because Shape implies Class. - HeapReceiverGuard receiverGuard_; - - // Holder and holder shape. For own getters, guarding on receiverGuard_ is - // sufficient, although Ion may use holder_ and holderShape_ even for own - // getters. In this case holderShape_ == receiverGuard_.shape_ (isOwnGetter - // below relies on this). - GCPtrObject holder_; - - GCPtrShape holderShape_; - - // Function to call. - GCPtrFunction getter_; - - // PC offset of call - uint32_t pcOffset_; - - ICGetPropCallGetter(Kind kind, JitCode* stubCode, ICStub* firstMonitorStub, - ReceiverGuard receiverGuard, JSObject* holder, - Shape* holderShape, JSFunction* getter, uint32_t pcOffset); - - public: - GCPtrObject& holder() { - return holder_; - } - GCPtrShape& holderShape() { - return holderShape_; - } - GCPtrFunction& getter() { - return getter_; - } - HeapReceiverGuard& receiverGuard() { - return receiverGuard_; - } - - bool isOwnGetter() const { - MOZ_ASSERT(holder_->isNative()); - MOZ_ASSERT(holderShape_); - return receiverGuard_.shape() == holderShape_; - } - - static size_t offsetOfHolder() { - return offsetof(ICGetPropCallGetter, holder_); - } - static size_t offsetOfHolderShape() { - return offsetof(ICGetPropCallGetter, holderShape_); - } - static size_t offsetOfGetter() { - return offsetof(ICGetPropCallGetter, getter_); - } - static size_t offsetOfPCOffset() { - return offsetof(ICGetPropCallGetter, pcOffset_); - } - static size_t offsetOfReceiverGuard() { - return offsetof(ICGetPropCallGetter, receiverGuard_); - } - - class Compiler : public ICStubCompiler { - protected: - ICStub* firstMonitorStub_; - RootedObject receiver_; - RootedObject holder_; - RootedFunction getter_; - uint32_t pcOffset_; - - virtual int32_t getKey() const { - // ICGetPropCallNativeCompiler::getKey adds more bits to our - // return value, so be careful when making changes here. - return static_cast(engine_) | - (static_cast(kind) << 1) | - (HeapReceiverGuard::keyBits(receiver_) << 17) | - (static_cast(receiver_ != holder_) << 19); - } - - public: - Compiler(JSContext* cx, ICStub::Kind kind, Engine engine, ICStub* firstMonitorStub, - HandleObject receiver, HandleObject holder, HandleFunction getter, - uint32_t pcOffset) - : ICStubCompiler(cx, kind, engine), - firstMonitorStub_(firstMonitorStub), - receiver_(cx, receiver), - holder_(cx, holder), - getter_(cx, getter), - pcOffset_(pcOffset) - { - MOZ_ASSERT(kind == ICStub::GetProp_CallNativeGlobal); - } - }; -}; - -// Stub for calling a native getter on the GlobalObject. -class ICGetProp_CallNativeGlobal : public ICGetPropCallGetter -{ - friend class ICStubSpace; - - protected: - GCPtrShape globalShape_; - - ICGetProp_CallNativeGlobal(JitCode* stubCode, ICStub* firstMonitorStub, - ReceiverGuard receiverGuard, - JSObject* holder, Shape* holderShape, Shape* globalShape, - JSFunction* getter, uint32_t pcOffset) - : ICGetPropCallGetter(GetProp_CallNativeGlobal, stubCode, firstMonitorStub, - receiverGuard, holder, holderShape, getter, pcOffset), - globalShape_(globalShape) - { } - - public: - static ICGetProp_CallNativeGlobal* Clone(JSContext* cx, ICStubSpace* space, - ICStub* firstMonitorStub, - ICGetProp_CallNativeGlobal& other); - - GCPtrShape& globalShape() { - return globalShape_; - } - static size_t offsetOfGlobalShape() { - return offsetof(ICGetProp_CallNativeGlobal, globalShape_); - } -}; - -class ICGetPropCallNativeCompiler : public ICGetPropCallGetter::Compiler -{ - bool inputDefinitelyObject_; - protected: - MOZ_MUST_USE bool generateStubCode(MacroAssembler& masm); - - virtual int32_t getKey() const { - int32_t baseKey = ICGetPropCallGetter::Compiler::getKey(); - MOZ_ASSERT((baseKey >> 21) == 0); - return baseKey | (static_cast(inputDefinitelyObject_) << 21); - } - - public: - ICGetPropCallNativeCompiler(JSContext* cx, ICStub::Kind kind, ICStubCompiler::Engine engine, - ICStub* firstMonitorStub, HandleObject receiver, - HandleObject holder, HandleFunction getter, uint32_t pcOffset, - bool inputDefinitelyObject = false) - : ICGetPropCallGetter::Compiler(cx, kind, engine, firstMonitorStub, receiver, holder, - getter, pcOffset), - inputDefinitelyObject_(inputDefinitelyObject) - {} - - ICStub* getStub(ICStubSpace* space); -}; - // JSOP_NEWARRAY // JSOP_NEWINIT diff --git a/js/src/jit/SharedICList.h b/js/src/jit/SharedICList.h index 6bf41a0e3fb1..6a4b86eff9bd 100644 --- a/js/src/jit/SharedICList.h +++ b/js/src/jit/SharedICList.h @@ -35,7 +35,6 @@ namespace jit { _(Compare_Int32WithBoolean) \ \ _(GetProp_Fallback) \ - _(GetProp_CallNativeGlobal) \ _(GetProp_Generic) \ \ _(CacheIR_Monitored) \ diff --git a/js/src/jit/VMFunctions.cpp b/js/src/jit/VMFunctions.cpp index bb04a3b7c936..9ac0cb0b658d 100644 --- a/js/src/jit/VMFunctions.cpp +++ b/js/src/jit/VMFunctions.cpp @@ -1372,6 +1372,24 @@ ProxyGetPropertyByValue(JSContext* cx, HandleObject proxy, HandleValue idVal, return Proxy::get(cx, proxy, receiver, id, vp); } +bool +CallNativeGetter(JSContext* cx, HandleFunction callee, HandleObject obj, + MutableHandleValue result) +{ + MOZ_ASSERT(callee->isNative()); + JSNative natfun = callee->native(); + + JS::AutoValueArray<2> vp(cx); + vp[0].setObject(*callee.get()); + vp[1].setObject(*obj.get()); + + if (!natfun(cx, 0, vp.begin())) + return false; + + result.set(vp[0]); + return true; +} + bool EqualStringsHelper(JSString* str1, JSString* str2) { diff --git a/js/src/jit/VMFunctions.h b/js/src/jit/VMFunctions.h index a1f386905902..3fe1d71eac4b 100644 --- a/js/src/jit/VMFunctions.h +++ b/js/src/jit/VMFunctions.h @@ -818,6 +818,11 @@ MOZ_MUST_USE bool ProxyGetPropertyByValue(JSContext* cx, HandleObject proxy, HandleValue idVal, MutableHandleValue vp); +MOZ_MUST_USE bool +CallNativeGetter(JSContext* cx, HandleFunction callee, HandleObject obj, + MutableHandleValue result); + + MOZ_MUST_USE bool EqualStringsHelper(JSString* str1, JSString* str2); From 33ee1e8b6aca0d26ad987c290a9dd2170c106f51 Mon Sep 17 00:00:00 2001 From: Tom Schuster Date: Fri, 30 Dec 2016 17:38:08 +0100 Subject: [PATCH 124/229] Bug 1324566 - Inspector support for GlobalNameGetter. r=jandem --- js/src/jit/BaselineInspector.cpp | 90 ++++++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 4 deletions(-) diff --git a/js/src/jit/BaselineInspector.cpp b/js/src/jit/BaselineInspector.cpp index 19ef458f4be2..967718bda107 100644 --- a/js/src/jit/BaselineInspector.cpp +++ b/js/src/jit/BaselineInspector.cpp @@ -11,6 +11,8 @@ #include "jit/BaselineIC.h" #include "jit/CacheIRCompiler.h" +#include "jsscriptinlines.h" + #include "vm/EnvironmentObject-inl.h" #include "vm/ObjectGroup-inl.h" @@ -718,12 +720,89 @@ MatchCacheIRReceiverGuard(CacheIRReader& reader, ICCacheIR_Monitored* stub, ObjO return true; } +static bool +AddCacheIRGlobalGetter(ICCacheIR_Monitored* stub, bool innerized, + JSObject** holder_, Shape** holderShape_, + JSFunction** commonGetter, Shape** globalShape_, bool* isOwnProperty, + BaselineInspector::ReceiverVector& receivers, + BaselineInspector::ObjectGroupVector& convertUnboxedGroups, + JSScript* script) +{ + // We are matching on the IR generated by tryAttachGlobalNameGetter: + // + // GuardShape objId + // globalId = LoadEnclosingEnvironment objId + // GuardShape globalId + // > + // + // CallNativeGetterResult globalId + + CacheIRReader reader(stub->stubInfo()); + + ObjOperandId objId = ObjOperandId(0); + if (!reader.matchOp(CacheOp::GuardShape, objId)) + return false; + Shape* globalLexicalShape = stub->stubInfo()->getStubField(stub, reader.stubOffset()); + + if (!reader.matchOp(CacheOp::LoadEnclosingEnvironment, objId)) + return false; + ObjOperandId globalId = reader.objOperandId(); + + if (!reader.matchOp(CacheOp::GuardShape, globalId)) + return false; + Shape* globalShape = stub->stubInfo()->getStubField(stub, reader.stubOffset()); + MOZ_ASSERT(globalShape->getObjectClass()->flags & JSCLASS_IS_GLOBAL); + + JSObject* holder = &script->global(); + Shape* holderShape = globalShape; + if (reader.matchOp(CacheOp::LoadObject)) { + ObjOperandId holderId = reader.objOperandId(); + holder = stub->stubInfo()->getStubField(stub, reader.stubOffset()).get(); + + if (!reader.matchOp(CacheOp::GuardShape, holderId)) + return false; + holderShape = stub->stubInfo()->getStubField(stub, reader.stubOffset()); + } + + // This guard will always fail, try the next stub. + if (holder->as().lastProperty() != holderShape) + return true; + + if (!reader.matchOp(CacheOp::CallNativeGetterResult, globalId)) + return false; + size_t offset = reader.stubOffset(); + JSFunction* getter = + &stub->stubInfo()->getStubField(stub, offset)->as(); + + ReceiverGuard receiver; + receiver.shape = globalLexicalShape; + if (!AddReceiver(receiver, receivers, convertUnboxedGroups)) + return false; + + if (!*commonGetter) { + *holder_ = holder; + *holderShape_ = holderShape; + *commonGetter = getter; + *globalShape_ = globalShape; + + // This is always false, because the getters never live on the globalLexical. + *isOwnProperty = false; + } else if (*isOwnProperty || holderShape != *holderShape_ || globalShape != *globalShape_) { + return false; + } else { + MOZ_ASSERT(*commonGetter == getter); + } + + return true; +} + static bool AddCacheIRGetPropFunction(ICCacheIR_Monitored* stub, bool innerized, JSObject** holder, Shape** holderShape, JSFunction** commonGetter, Shape** globalShape, bool* isOwnProperty, BaselineInspector::ReceiverVector& receivers, - BaselineInspector::ObjectGroupVector& convertUnboxedGroups) + BaselineInspector::ObjectGroupVector& convertUnboxedGroups, + JSScript* script) { // We match either an own getter: // @@ -752,8 +831,11 @@ AddCacheIRGetPropFunction(ICCacheIR_Monitored* stub, bool innerized, CacheIRReader reader(stub->stubInfo()); ObjOperandId objId = ObjOperandId(0); - if (!reader.matchOp(CacheOp::GuardIsObject, objId)) - return false; + if (!reader.matchOp(CacheOp::GuardIsObject, objId)) { + return AddCacheIRGlobalGetter(stub, innerized, holder, holderShape, commonGetter, + globalShape, isOwnProperty, receivers, convertUnboxedGroups, + script); + } if (innerized) { if (!reader.matchOp(CacheOp::GuardClass, objId) || @@ -868,7 +950,7 @@ BaselineInspector::commonGetPropFunction(jsbytecode* pc, bool innerized, if (!AddCacheIRGetPropFunction(stub->toCacheIR_Monitored(), innerized, holder, holderShape, commonGetter, globalShape, isOwnProperty, receivers, - convertUnboxedGroups)) + convertUnboxedGroups, script)) { return false; } From 884f6d91cb10dcb785640ca42d3202f3a62f0715 Mon Sep 17 00:00:00 2001 From: Ehsan Akhgari Date: Sun, 18 Dec 2016 11:58:17 -0500 Subject: [PATCH 125/229] Bug 1324492 - Upgrade CMake to 3.7.1 in the desktop-build image; r=dustin Newer versions of LLVM require CMake 3.4, so we may as well upgrade to the latest version. --- taskcluster/docker/centos6-build-upd/Dockerfile | 2 +- taskcluster/docker/centos6-build-upd/VERSION | 2 +- taskcluster/docker/centos6-build/VERSION | 2 +- .../docker/centos6-build/system-setup.sh | 17 ++++++++++++++++- taskcluster/docker/desktop-build/Dockerfile | 2 +- 5 files changed, 20 insertions(+), 5 deletions(-) diff --git a/taskcluster/docker/centos6-build-upd/Dockerfile b/taskcluster/docker/centos6-build-upd/Dockerfile index a245bcbe54b5..0b8800bb64c8 100644 --- a/taskcluster/docker/centos6-build-upd/Dockerfile +++ b/taskcluster/docker/centos6-build-upd/Dockerfile @@ -1,4 +1,4 @@ -FROM taskcluster/centos6-build:0.1.6 +FROM taskcluster/centos6-build:0.1.7 MAINTAINER Dustin J. Mitchell ### update to latest from upstream repositories diff --git a/taskcluster/docker/centos6-build-upd/VERSION b/taskcluster/docker/centos6-build-upd/VERSION index 01ae56f9e52a..eb4d30ac6b70 100644 --- a/taskcluster/docker/centos6-build-upd/VERSION +++ b/taskcluster/docker/centos6-build-upd/VERSION @@ -1 +1 @@ -0.1.6.20160329195300 +0.1.7.20161229150900 diff --git a/taskcluster/docker/centos6-build/VERSION b/taskcluster/docker/centos6-build/VERSION index c946ee6160c2..11808190d4b9 100644 --- a/taskcluster/docker/centos6-build/VERSION +++ b/taskcluster/docker/centos6-build/VERSION @@ -1 +1 @@ -0.1.6 +0.1.7 diff --git a/taskcluster/docker/centos6-build/system-setup.sh b/taskcluster/docker/centos6-build/system-setup.sh index ddb529eed735..0353768056aa 100644 --- a/taskcluster/docker/centos6-build/system-setup.sh +++ b/taskcluster/docker/centos6-build/system-setup.sh @@ -268,7 +268,6 @@ install xvinfo install patch install libuuid-devel install openssl-static -install cmake install subversion run EOF @@ -429,6 +428,22 @@ peep install -r requirements.txt # TC-VCS npm install -g taskcluster-vcs@2.3.18 +# CMake 3.7.1 +cd $BUILD +tooltool_fetch <<'EOF' +[ +{ + "size": 7361172, + "digest": "0539d70ce3ac77042a45d638443b09fbf368e253622db980bc6fb15988743eacd031ab850a45c821ec3e9f0f5f886b9c9cb0668aeda184cd457b78abbfe7b629", + "algorithm": "sha512", + "filename": "cmake-3.7.1.tar.gz", + "unpack": true +} +] +EOF +cd cmake-3.7.1 +./bootstrap && make install + # Ninja cd $BUILD tooltool_fetch <<'EOF' diff --git a/taskcluster/docker/desktop-build/Dockerfile b/taskcluster/docker/desktop-build/Dockerfile index 66fe30ff0c3e..037495be5795 100644 --- a/taskcluster/docker/desktop-build/Dockerfile +++ b/taskcluster/docker/desktop-build/Dockerfile @@ -1,5 +1,5 @@ # TODO remove VOLUME below when the base image is updated next. -FROM taskcluster/centos6-build-upd:0.1.6.20160329195300 +FROM taskcluster/centos6-build-upd:0.1.7.20161229150900 MAINTAINER Dustin J. Mitchell # TODO remove when base image is updated From 9fc596c6c1c643437499892714d3f307e94e915d Mon Sep 17 00:00:00 2001 From: Ehsan Akhgari Date: Fri, 23 Dec 2016 18:28:39 -0500 Subject: [PATCH 126/229] Bug 1325651 - Assume failure in case of early returns in a couple of places; r=bzbarsky --- dom/ipc/ContentParent.cpp | 1 + dom/ipc/URLClassifierParent.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/dom/ipc/ContentParent.cpp b/dom/ipc/ContentParent.cpp index 86d09cfd8bef..a43571de96d3 100644 --- a/dom/ipc/ContentParent.cpp +++ b/dom/ipc/ContentParent.cpp @@ -4793,6 +4793,7 @@ ContentParent::RecvPURLClassifierConstructor(PURLClassifierParent* aActor, { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(aActor); + *aSuccess = false; auto* actor = static_cast(aActor); nsCOMPtr principal(aPrincipal); diff --git a/dom/ipc/URLClassifierParent.cpp b/dom/ipc/URLClassifierParent.cpp index 816802e9b962..987ee59395f5 100644 --- a/dom/ipc/URLClassifierParent.cpp +++ b/dom/ipc/URLClassifierParent.cpp @@ -18,6 +18,7 @@ URLClassifierParent::StartClassify(nsIPrincipal* aPrincipal, bool aUseTrackingProtection, bool* aSuccess) { + *aSuccess = false; nsresult rv = NS_OK; // Note that in safe mode, the URL classifier service isn't available, so we // should handle the service not being present gracefully. @@ -34,6 +35,7 @@ URLClassifierParent::StartClassify(nsIPrincipal* aPrincipal, // without ever calling out callback in both cases. // This means that code using this in the child process will only get a hit // on its callback if some classification actually happens. + *aSuccess = false; ClassificationFailed(); } return IPC_OK(); From 9a3fcec28cff7e557ade715aa28736e7a8fc087c Mon Sep 17 00:00:00 2001 From: Ehsan Akhgari Date: Sun, 18 Dec 2016 01:04:11 -0500 Subject: [PATCH 127/229] Bug 1324488 - Add a TaskCluster job to build clang-tidy on Linux; r=dustin --- build/build-clang/clang-tidy-linux64.json | 18 +++++++++++ taskcluster/ci/toolchain/linux.yml | 22 ++++++++++++++ .../scripts/misc/build-clang-tidy-linux.sh | 30 +++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 build/build-clang/clang-tidy-linux64.json create mode 100755 taskcluster/scripts/misc/build-clang-tidy-linux.sh diff --git a/build/build-clang/clang-tidy-linux64.json b/build/build-clang/clang-tidy-linux64.json new file mode 100644 index 000000000000..626a4259dabb --- /dev/null +++ b/build/build-clang/clang-tidy-linux64.json @@ -0,0 +1,18 @@ +{ + "llvm_revision": "290055", + "stages": "1", + "build_libcxx": true, + "build_type": "Release", + "assertions": false, + "import_clang_tidy": true, + "llvm_repo": "https://llvm.org/svn/llvm-project/llvm/trunk", + "clang_repo": "https://llvm.org/svn/llvm-project/cfe/trunk", + "extra_repo": "https://llvm.org/svn/llvm-project/clang-tools-extra/trunk", + "compiler_repo": "https://llvm.org/svn/llvm-project/compiler-rt/trunk", + "libcxx_repo": "https://llvm.org/svn/llvm-project/libcxx/trunk", + "libcxxabi_repo": "https://llvm.org/svn/llvm-project/libcxxabi/trunk", + "python_path": "/usr/bin/python2.7", + "gcc_dir": "/home/worker/workspace/build/src/gcc", + "cc": "/home/worker/workspace/build/src/gcc/bin/gcc", + "cxx": "/home/worker/workspace/build/src/gcc/bin/g++" +} diff --git a/taskcluster/ci/toolchain/linux.yml b/taskcluster/ci/toolchain/linux.yml index 9eeadf3ef31d..9169a290a524 100644 --- a/taskcluster/ci/toolchain/linux.yml +++ b/taskcluster/ci/toolchain/linux.yml @@ -23,6 +23,28 @@ linux64-clang/opt: - 'taskcluster/scripts/misc/build-clang-linux.sh' - 'taskcluster/taskgraph/transforms/job/toolchain.py' +linux64-clang-tidy/opt: + description: "Clang-tidy build" + treeherder: + kind: build + platform: linux64/opt + symbol: Cc(Clang-Tidy) + tier: 1 + run: + using: toolchain-script + script: build-clang-tidy-linux.sh + worker-type: aws-provisioner-v1/gecko-{level}-b-linux + worker: + implementation: docker-worker + docker-image: {in-tree: desktop-build} + max-run-time: 36000 + when: + files-changed: + - 'build/clang-plugin/**' + - 'build/build-clang/**' + - 'taskcluster/scripts/misc/build-clang-tidy-linux.sh' + - 'taskcluster/taskgraph/transforms/job/toolchain.py' + linux64-gcc/opt: description: "GCC toolchain build" treeherder: diff --git a/taskcluster/scripts/misc/build-clang-tidy-linux.sh b/taskcluster/scripts/misc/build-clang-tidy-linux.sh new file mode 100755 index 000000000000..8e6a1803fcbf --- /dev/null +++ b/taskcluster/scripts/misc/build-clang-tidy-linux.sh @@ -0,0 +1,30 @@ +#!/bin/bash +set -x -e -v + +# This script is for building clang for Linux. + +WORKSPACE=$HOME/workspace +HOME_DIR=$WORKSPACE/build +UPLOAD_DIR=$WORKSPACE/artifacts + +# Fetch our toolchain from tooltool +cd $HOME_DIR +wget -O tooltool.py https://raw.githubusercontent.com/mozilla/build-tooltool/master/tooltool.py +chmod +x tooltool.py +: TOOLTOOL_CACHE ${TOOLTOOL_CACHE:=/home/worker/tooltool-cache} +export TOOLTOOL_CACHE +cd src +$HOME_DIR/tooltool.py -m browser/config/tooltool-manifests/linux64/releng.manifest fetch + +# gets a bit too verbose here +set +x + +cd build/build-clang +# |mach python| sets up a virtualenv for us! +../../mach python ./build-clang.py -c clang-tidy-linux64.json + +set -x + +# Put a tarball in the artifacts dir +mkdir -p $UPLOAD_DIR +cp clang.tar.* $UPLOAD_DIR From d69a4426a7f36f5546d2778713dc0cf504efc293 Mon Sep 17 00:00:00 2001 From: Luke Wagner Date: Fri, 30 Dec 2016 10:49:54 -0600 Subject: [PATCH 128/229] Bug 1326280 - Baldr: use .wasm as bytecode file format (r=bbouvier) MozReview-Commit-ID: 5nmuLDswfWU --HG-- extra : rebase_source : eb0839326f65c58bd51521bc6bcdca9a4cec846a --- .../test/unit/wasm_recompile_profile.zip | Bin 5447 -> 5446 bytes js/src/wasm/AsmJS.cpp | 32 +++++++----------- js/src/wasm/WasmCompile.h | 3 +- js/src/wasm/WasmModule.cpp | 30 ++++++++-------- js/src/wasm/WasmSerialize.h | 2 +- 5 files changed, 29 insertions(+), 38 deletions(-) diff --git a/dom/indexedDB/test/unit/wasm_recompile_profile.zip b/dom/indexedDB/test/unit/wasm_recompile_profile.zip index 5e1144db47be8c85f4545c978a5eb90d3f8293ec..50ca3ef898de2706d42e0019c923838502302225 100644 GIT binary patch delta 1070 zcmX@Ebxdn=Ij_E`$u*sbHyNoBr4`%^j4Ush85n@X=H0wc7$*y}OH7m!6s^0e6EQ6v zO~ph9bFjn=ObMBZE0n-;v#`ibe#oe%0y1$9x+DWbfHyM>7Xt{$B?f8%mi1M&ytO zYC=LnPG&|%LV^#FmB+MM;)ax?33IsmjN3fV42qa1+cKwvy|n_}<(qdh$1qQx#hwV3 z2005gFa!U$<~Ys*!4}`z$iVLkyjUotTV6K17p%hOja)gJKoM5tAJScZS=|z_6t;o&{$2~hZK%veHgi}}<80G+VGB5xD DDn=M} delta 1066 zcmX@6bzE!mEoQ074orfge8oBu%|KjQ!Og(P@|BT+fklL2@(pI0$xTescx2BpDT!m% z%fK+%hR+qOQxU`5X?zJ_8CeV&Zhq;>_n5^dD>AF$v9*HP+X#oP0p83&moqSMFdVKc z@Kn@NV^#<9On}&V@&^w4$p-}4Chuoqvju6#u%3azIDw(*$fKAzg`+nvUAS=Iz>EV2 z4%}f$Gu&X>l)<*n&tSXcnZze-lNnjlv3p>1Eo%%j&<9yKL**(*Dh{pwoWEHn8}KWG zrR6b#CWGH>B9pG@VW0#Eqr}ukmnV#qKk#cP0sYBPT#{dun4YR18p6uJ4Du(6(#anM z zxV^BZD|VA%F2|8f;HEJ!ENPsDFm3XEAvP=?`X;2qXg9f0&{Z6_N8~2|669kRWQV(K zvY!yPz^ND3VV(w8r94@mlLNcAZ;9xr|K)*4wO(;yPG(6eR_{)p$**fy&db1%T$Gwv ik{X|qq?c6;R*8{{Kmo(b28u>rAe_R=z%Z8|!~+0G0`)Th diff --git a/js/src/wasm/AsmJS.cpp b/js/src/wasm/AsmJS.cpp index 372b63322274..a5b3c691bebe 100644 --- a/js/src/wasm/AsmJS.cpp +++ b/js/src/wasm/AsmJS.cpp @@ -8436,9 +8436,11 @@ StoreAsmJSModuleInCache(AsmJSParser& parser, Module& module, ExclusiveContext* c size_t bytecodeSize, compiledSize; module.serializedSize(&bytecodeSize, &compiledSize); + MOZ_RELEASE_ASSERT(bytecodeSize == 0); + MOZ_RELEASE_ASSERT(compiledSize <= UINT32_MAX); - size_t serializedSize = 2 * sizeof(uint32_t) + - bytecodeSize + compiledSize + + size_t serializedSize = sizeof(uint32_t) + + compiledSize + moduleChars.serializedSize(); JS::OpenAsmJSCacheEntryForWriteOp open = cx->asmJSCacheOps().openEntryForWrite; @@ -8461,16 +8463,10 @@ StoreAsmJSModuleInCache(AsmJSParser& parser, Module& module, ExclusiveContext* c // between any two builds (regardless of platform, architecture, ...). // (The Module::assumptionsMatch() guard everything in the Module and // afterwards.) - MOZ_RELEASE_ASSERT(bytecodeSize <= UINT32_MAX); - MOZ_RELEASE_ASSERT(compiledSize <= UINT32_MAX); - cursor = WriteScalar(cursor, bytecodeSize); cursor = WriteScalar(cursor, compiledSize); - uint8_t* compiledBegin = cursor; - uint8_t* bytecodeBegin = compiledBegin + compiledSize;; - - module.serialize(bytecodeBegin, bytecodeSize, compiledBegin, compiledSize); - cursor = bytecodeBegin + bytecodeSize; + module.serialize(/* bytecodeBegin = */ nullptr, /* bytecodeSize = */ 0, cursor, compiledSize); + cursor += compiledSize; cursor = moduleChars.serialize(cursor); @@ -8501,33 +8497,29 @@ LookupAsmJSModuleInCache(ExclusiveContext* cx, AsmJSParser& parser, bool* loaded size_t remain = entry.serializedSize; const uint8_t* cursor = entry.memory; - uint32_t bytecodeSize, compiledSize; - (cursor = ReadScalarChecked(cursor, &remain, &bytecodeSize)) && - (cursor = ReadScalarChecked(cursor, &remain, &compiledSize)); + uint32_t compiledSize; + cursor = ReadScalarChecked(cursor, &remain, &compiledSize); if (!cursor) return true; - const uint8_t* compiledBegin = cursor; - const uint8_t* bytecodeBegin = compiledBegin + compiledSize; - Assumptions assumptions; if (!assumptions.initBuildIdFromContext(cx)) return false; - if (!Module::assumptionsMatch(assumptions, compiledBegin, remain)) + if (!Module::assumptionsMatch(assumptions, cursor, remain)) return true; MutableAsmJSMetadata asmJSMetadata = cx->new_(); if (!asmJSMetadata) return false; - *module = Module::deserialize(bytecodeBegin, bytecodeSize, compiledBegin, compiledSize, - asmJSMetadata.get()); + *module = Module::deserialize(/* bytecodeBegin = */ nullptr, /* bytecodeSize = */ 0, + cursor, compiledSize, asmJSMetadata.get()); if (!*module) { ReportOutOfMemory(cx); return false; } - cursor = bytecodeBegin + bytecodeSize; + cursor += compiledSize; // Due to the hash comparison made by openEntryForRead, this should succeed // with high probability. diff --git a/js/src/wasm/WasmCompile.h b/js/src/wasm/WasmCompile.h index d5a19da97a08..87f2b16c675f 100644 --- a/js/src/wasm/WasmCompile.h +++ b/js/src/wasm/WasmCompile.h @@ -19,7 +19,6 @@ #ifndef wasm_compile_h #define wasm_compile_h -#include "wasm/WasmJS.h" #include "wasm/WasmModule.h" namespace js { @@ -40,7 +39,7 @@ struct CompileArgs { Assumptions assumptions; ScriptedCaller scriptedCaller; - MOZ_INIT_OUTSIDE_CTOR bool alwaysBaseline; + bool alwaysBaseline; CompileArgs(Assumptions&& assumptions, ScriptedCaller&& scriptedCaller) : assumptions(Move(assumptions)), diff --git a/js/src/wasm/WasmModule.cpp b/js/src/wasm/WasmModule.cpp index 69b60f5f80b4..5a530860f79d 100644 --- a/js/src/wasm/WasmModule.cpp +++ b/js/src/wasm/WasmModule.cpp @@ -141,7 +141,7 @@ LinkData::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const Module::serializedSize(size_t* maybeBytecodeSize, size_t* maybeCompiledSize) const { if (maybeBytecodeSize) - *maybeBytecodeSize = SerializedPodVectorSize(bytecode_->bytes); + *maybeBytecodeSize = bytecode_->bytes.length(); if (maybeCompiledSize) { *maybeCompiledSize = assumptions_.serializedSize() + @@ -164,9 +164,13 @@ Module::serialize(uint8_t* maybeBytecodeBegin, size_t maybeBytecodeSize, if (maybeBytecodeBegin) { // Bytecode deserialization is not guarded by Assumptions and thus must not - // change incompatibly between builds. + // change incompatibly between builds. Thus, for simplicity, the format + // of the bytecode file is simply a .wasm file (thus, backwards + // compatibility is ensured by backwards compatibility of the wasm + // binary format). - uint8_t* bytecodeEnd = SerializePodVector(maybeBytecodeBegin, bytecode_->bytes); + const Bytes& bytes = bytecode_->bytes; + uint8_t* bytecodeEnd = WriteBytes(maybeBytecodeBegin, bytes.begin(), bytes.length()); MOZ_RELEASE_ASSERT(bytecodeEnd == maybeBytecodeBegin + maybeBytecodeSize); } @@ -204,14 +208,10 @@ Module::deserialize(const uint8_t* bytecodeBegin, size_t bytecodeSize, Metadata* maybeMetadata) { MutableBytes bytecode = js_new(); - if (!bytecode) + if (!bytecode || !bytecode->bytes.initLengthUninitialized(bytecodeSize)) return nullptr; - const uint8_t* bytecodeEnd = DeserializePodVector(bytecodeBegin, &bytecode->bytes); - if (!bytecodeEnd) - return nullptr; - - MOZ_RELEASE_ASSERT(bytecodeEnd == bytecodeBegin + bytecodeSize); + memcpy(bytecode->bytes.begin(), bytecodeBegin, bytecodeSize); Assumptions assumptions; const uint8_t* cursor = assumptions.deserialize(compiledBegin, compiledSize); @@ -344,15 +344,15 @@ wasm::DeserializeModule(PRFileDesc* bytecodeFile, PRFileDesc* maybeCompiledFile, compiledMapping.get(), compiledInfo.size); } + // Since the compiled file's assumptions don't match, we must recompile from + // bytecode. The bytecode file format is simply that of a .wasm (see + // Module::serialize). + MutableBytes bytecode = js_new(); - if (!bytecode) + if (!bytecode || !bytecode->bytes.initLengthUninitialized(bytecodeInfo.size)) return nullptr; - const uint8_t* bytecodeEnd = DeserializePodVector(bytecodeMapping.get(), &bytecode->bytes); - if (!bytecodeEnd) - return nullptr; - - MOZ_RELEASE_ASSERT(bytecodeEnd == bytecodeMapping.get() + bytecodeInfo.size); + memcpy(bytecode->bytes.begin(), bytecodeMapping.get(), bytecodeInfo.size); ScriptedCaller scriptedCaller; scriptedCaller.filename = Move(filename); diff --git a/js/src/wasm/WasmSerialize.h b/js/src/wasm/WasmSerialize.h index 71c67d5abc1b..79d759b27cb5 100644 --- a/js/src/wasm/WasmSerialize.h +++ b/js/src/wasm/WasmSerialize.h @@ -137,7 +137,7 @@ static inline uint8_t* SerializePodVector(uint8_t* cursor, const mozilla::Vector& vec) { // This binary format must not change without taking into consideration the - // constraints in Assumptions::serialize and Module::serialize. + // constraints in Assumptions::serialize. cursor = WriteScalar(cursor, vec.length()); cursor = WriteBytes(cursor, vec.begin(), vec.length() * sizeof(T)); From a3f03e52741b7bba2577f18e1bb2c185094cdb61 Mon Sep 17 00:00:00 2001 From: Ryan VanderMeulen Date: Thu, 29 Dec 2016 22:08:13 -0500 Subject: [PATCH 129/229] Bug 1326340 - Update pdf.js to version 1.6.418. r=bdahl, r=Mossop --- .../test/general/browser_parsable_css.js | 4 + browser/extensions/pdfjs/README.mozilla | 2 +- browser/extensions/pdfjs/content/PdfJs.jsm | 1 - .../pdfjs/content/PdfJsTelemetry.jsm | 2 +- .../pdfjs/content/PdfStreamConverter.jsm | 1 - .../pdfjs/content/PdfjsChromeUtils.jsm | 1 - .../pdfjs/content/PdfjsContentUtils.jsm | 1 - browser/extensions/pdfjs/content/build/pdf.js | 52 +++++++++- .../pdfjs/content/build/pdf.worker.js | 94 ++++++++++++++++--- .../pdfjs/content/pdfjschildbootstrap.js | 1 - browser/extensions/pdfjs/content/web/l10n.js | 1 - .../extensions/pdfjs/content/web/viewer.css | 18 +++- .../extensions/pdfjs/content/web/viewer.js | 24 +++-- 13 files changed, 166 insertions(+), 36 deletions(-) diff --git a/browser/base/content/test/general/browser_parsable_css.js b/browser/base/content/test/general/browser_parsable_css.js index 559e25b73812..518dad8afc33 100644 --- a/browser/base/content/test/general/browser_parsable_css.js +++ b/browser/base/content/test/general/browser_parsable_css.js @@ -20,6 +20,10 @@ let whitelist = [ {sourceName: /web\/viewer\.css$/i, errorMessage: /Unknown pseudo-class.*(fullscreen|selection)/i, isFromDevTools: false}, + // PDFjs rules needed for compat with other UAs. + {sourceName: /web\/viewer\.css$/i, + errorMessage: /Unknown property.*appearance/i, + isFromDevTools: false}, // Tracked in bug 1004428. {sourceName: /aboutaccounts\/(main|normalize)\.css$/i, isFromDevTools: false}, diff --git a/browser/extensions/pdfjs/README.mozilla b/browser/extensions/pdfjs/README.mozilla index b849113a5a09..2e82c74f2c6a 100644 --- a/browser/extensions/pdfjs/README.mozilla +++ b/browser/extensions/pdfjs/README.mozilla @@ -1,3 +1,3 @@ This is the pdf.js project output, https://github.com/mozilla/pdf.js -Current extension version is: 1.6.401 +Current extension version is: 1.6.418 diff --git a/browser/extensions/pdfjs/content/PdfJs.jsm b/browser/extensions/pdfjs/content/PdfJs.jsm index c25804cdec48..d67a6c5f8486 100644 --- a/browser/extensions/pdfjs/content/PdfJs.jsm +++ b/browser/extensions/pdfjs/content/PdfJs.jsm @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils, PdfjsChromeUtils, PdfjsContentUtils, PdfStreamConverter */ diff --git a/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm b/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm index 275da9d87b31..0d34cd50e67c 100644 --- a/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm +++ b/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true, maxlen: 100 */ +/* eslint max-len: ["error", 100] */ /* globals Components, Services */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/PdfStreamConverter.jsm b/browser/extensions/pdfjs/content/PdfStreamConverter.jsm index 3b9f9de26788..128d8aad2ab0 100644 --- a/browser/extensions/pdfjs/content/PdfStreamConverter.jsm +++ b/browser/extensions/pdfjs/content/PdfStreamConverter.jsm @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils, NetUtil, PrivateBrowsingUtils, dump, NetworkManager, PdfJsTelemetry, PdfjsContentUtils */ diff --git a/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm b/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm index 57f07af92ccd..2d97206f967e 100644 --- a/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm +++ b/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm b/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm index 3dec5f38902d..4318fbfdf96e 100644 --- a/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm +++ b/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/build/pdf.js b/browser/extensions/pdfjs/content/build/pdf.js index d5b17e9b3359..3183afb10e30 100644 --- a/browser/extensions/pdfjs/content/build/pdf.js +++ b/browser/extensions/pdfjs/content/build/pdf.js @@ -23,8 +23,8 @@ } }(this, function (exports) { 'use strict'; - var pdfjsVersion = '1.6.401'; - var pdfjsBuild = 'b629be05'; + var pdfjsVersion = '1.6.418'; + var pdfjsBuild = '59afb4b9'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { @@ -1808,6 +1808,15 @@ switch (fieldType) { case 'Tx': return new TextWidgetAnnotationElement(parameters); + case 'Btn': + if (parameters.data.radioButton) { + return new RadioButtonWidgetAnnotationElement(parameters); + } else if (parameters.data.checkBox) { + return new CheckboxWidgetAnnotationElement(parameters); + } else { + warn('Unimplemented button widget annotation: pushbutton'); + } + break; case 'Ch': return new ChoiceWidgetAnnotationElement(parameters); } @@ -2075,6 +2084,45 @@ }); return TextWidgetAnnotationElement; }(); + var CheckboxWidgetAnnotationElement = function CheckboxWidgetAnnotationElementClosure() { + function CheckboxWidgetAnnotationElement(parameters) { + WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); + } + Util.inherit(CheckboxWidgetAnnotationElement, WidgetAnnotationElement, { + render: function CheckboxWidgetAnnotationElement_render() { + this.container.className = 'buttonWidgetAnnotation checkBox'; + var element = document.createElement('input'); + element.disabled = this.data.readOnly; + element.type = 'checkbox'; + if (this.data.fieldValue && this.data.fieldValue !== 'Off') { + element.setAttribute('checked', true); + } + this.container.appendChild(element); + return this.container; + } + }); + return CheckboxWidgetAnnotationElement; + }(); + var RadioButtonWidgetAnnotationElement = function RadioButtonWidgetAnnotationElementClosure() { + function RadioButtonWidgetAnnotationElement(parameters) { + WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); + } + Util.inherit(RadioButtonWidgetAnnotationElement, WidgetAnnotationElement, { + render: function RadioButtonWidgetAnnotationElement_render() { + this.container.className = 'buttonWidgetAnnotation radioButton'; + var element = document.createElement('input'); + element.disabled = this.data.readOnly; + element.type = 'radio'; + element.name = this.data.fieldName; + if (this.data.fieldValue === this.data.buttonValue) { + element.setAttribute('checked', true); + } + this.container.appendChild(element); + return this.container; + } + }); + return RadioButtonWidgetAnnotationElement; + }(); var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() { function ChoiceWidgetAnnotationElement(parameters) { WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); diff --git a/browser/extensions/pdfjs/content/build/pdf.worker.js b/browser/extensions/pdfjs/content/build/pdf.worker.js index 14746010d357..53587e11b279 100644 --- a/browser/extensions/pdfjs/content/build/pdf.worker.js +++ b/browser/extensions/pdfjs/content/build/pdf.worker.js @@ -23,8 +23,8 @@ } }(this, function (exports) { 'use strict'; - var pdfjsVersion = '1.6.401'; - var pdfjsBuild = 'b629be05'; + var pdfjsVersion = '1.6.418'; + var pdfjsBuild = '59afb4b9'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { @@ -45245,10 +45245,10 @@ } if (!font.vertical) { textChunk.lastAdvanceWidth = width; - textChunk.width += width * textChunk.textAdvanceScale; + textChunk.width += width; } else { textChunk.lastAdvanceHeight = height; - textChunk.height += Math.abs(height * textChunk.textAdvanceScale); + textChunk.height += Math.abs(height); } return textChunk; } @@ -45269,6 +45269,8 @@ if (!textContentItem.initialized) { return; } + textContentItem.width *= textContentItem.textAdvanceScale; + textContentItem.height *= textContentItem.textAdvanceScale; textContent.items.push(runBidiTransform(textContentItem)); textContentItem.initialized = false; textContentItem.str.length = 0; @@ -45381,16 +45383,16 @@ advance = items[j] * textState.fontSize / 1000; var breakTextRun = false; if (textState.font.vertical) { - offset = advance * (textState.textHScale * textState.textMatrix[2] + textState.textMatrix[3]); - textState.translateTextMatrix(0, advance); + offset = advance; + textState.translateTextMatrix(0, offset); breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax; if (!breakTextRun) { textContentItem.height += offset; } } else { advance = -advance; - offset = advance * (textState.textHScale * textState.textMatrix[0] + textState.textMatrix[1]); - textState.translateTextMatrix(advance, 0); + offset = advance * textState.textHScale; + textState.translateTextMatrix(offset, 0); breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax; if (!breakTextRun) { textContentItem.width += offset; @@ -45884,7 +45886,16 @@ } else if (isRef(entry)) { hash.update(entry.toString()); } else if (isArray(entry)) { - hash.update(entry.length.toString()); + var diffLength = entry.length, diffBuf = new Array(diffLength); + for (var j = 0; j < diffLength; j++) { + var diffEntry = entry[j]; + if (isName(diffEntry)) { + diffBuf[j] = diffEntry.name; + } else if (isNum(diffEntry) || isRef(diffEntry)) { + diffBuf[j] = diffEntry.toString(); + } + } + hash.update(diffBuf.join()); } } } @@ -47160,6 +47171,8 @@ switch (fieldType) { case 'Tx': return new TextWidgetAnnotation(parameters); + case 'Btn': + return new ButtonWidgetAnnotation(parameters); case 'Ch': return new ChoiceWidgetAnnotation(parameters); } @@ -47587,17 +47600,72 @@ }); return TextWidgetAnnotation; }(); + var ButtonWidgetAnnotation = function ButtonWidgetAnnotationClosure() { + function ButtonWidgetAnnotation(params) { + WidgetAnnotation.call(this, params); + this.data.checkBox = !this.hasFieldFlag(AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); + if (this.data.checkBox) { + if (!isName(this.data.fieldValue)) { + return; + } + this.data.fieldValue = this.data.fieldValue.name; + } + this.data.radioButton = this.hasFieldFlag(AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); + if (this.data.radioButton) { + this.data.fieldValue = this.data.buttonValue = null; + var fieldParent = params.dict.get('Parent'); + if (!isDict(fieldParent) || !fieldParent.has('V')) { + return; + } + var fieldParentValue = fieldParent.get('V'); + if (!isName(fieldParentValue)) { + return; + } + this.data.fieldValue = fieldParentValue.name; + var appearanceStates = params.dict.get('AP'); + if (!isDict(appearanceStates)) { + return; + } + var normalAppearanceState = appearanceStates.get('N'); + if (!isDict(normalAppearanceState)) { + return; + } + var keys = normalAppearanceState.getKeys(); + for (var i = 0, ii = keys.length; i < ii; i++) { + if (keys[i] !== 'Off') { + this.data.buttonValue = keys[i]; + break; + } + } + } + } + Util.inherit(ButtonWidgetAnnotation, WidgetAnnotation, { + getOperatorList: function ButtonWidgetAnnotation_getOperatorList(evaluator, task, renderForms) { + var operatorList = new OperatorList(); + if (renderForms) { + return Promise.resolve(operatorList); + } + if (this.appearance) { + return Annotation.prototype.getOperatorList.call(this, evaluator, task, renderForms); + } + return Promise.resolve(operatorList); + } + }); + return ButtonWidgetAnnotation; + }(); var ChoiceWidgetAnnotation = function ChoiceWidgetAnnotationClosure() { function ChoiceWidgetAnnotation(params) { WidgetAnnotation.call(this, params); this.data.options = []; - var options = params.dict.getArray('Opt'); + var options = params.dict.get('Opt'); if (isArray(options)) { + var xref = params.xref; for (var i = 0, ii = options.length; i < ii; i++) { - var option = options[i]; + var option = xref.fetchIfRef(options[i]); + var isOptionArray = isArray(option); this.data.options[i] = { - exportValue: isArray(option) ? option[0] : option, - displayValue: isArray(option) ? option[1] : option + exportValue: isOptionArray ? xref.fetchIfRef(option[0]) : option, + displayValue: isOptionArray ? xref.fetchIfRef(option[1]) : option }; } } diff --git a/browser/extensions/pdfjs/content/pdfjschildbootstrap.js b/browser/extensions/pdfjs/content/pdfjschildbootstrap.js index 1f44b9c2e8d8..2051e3055d56 100644 --- a/browser/extensions/pdfjs/content/pdfjschildbootstrap.js +++ b/browser/extensions/pdfjs/content/pdfjschildbootstrap.js @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint esnext:true */ /* globals Components, PdfjsContentUtils, PdfJs, Services */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/web/l10n.js b/browser/extensions/pdfjs/content/web/l10n.js index 04346ee1d650..e45cf200a5b9 100644 --- a/browser/extensions/pdfjs/content/web/l10n.js +++ b/browser/extensions/pdfjs/content/web/l10n.js @@ -1,4 +1,3 @@ - 'use strict'; // Small subset of the webL10n API by Fabien Cazenave for pdf.js extension. diff --git a/browser/extensions/pdfjs/content/web/viewer.css b/browser/extensions/pdfjs/content/web/viewer.css index cafa90738577..158842ac69fe 100644 --- a/browser/extensions/pdfjs/content/web/viewer.css +++ b/browser/extensions/pdfjs/content/web/viewer.css @@ -103,7 +103,9 @@ .annotationLayer .textWidgetAnnotation input, .annotationLayer .textWidgetAnnotation textarea, -.annotationLayer .choiceWidgetAnnotation select { +.annotationLayer .choiceWidgetAnnotation select, +.annotationLayer .buttonWidgetAnnotation.checkBox input, +.annotationLayer .buttonWidgetAnnotation.radioButton input { background-color: rgba(0, 54, 255, 0.13); border: 1px solid transparent; box-sizing: border-box; @@ -122,7 +124,9 @@ .annotationLayer .textWidgetAnnotation input[disabled], .annotationLayer .textWidgetAnnotation textarea[disabled], -.annotationLayer .choiceWidgetAnnotation select[disabled] { +.annotationLayer .choiceWidgetAnnotation select[disabled], +.annotationLayer .buttonWidgetAnnotation.checkBox input[disabled], +.annotationLayer .buttonWidgetAnnotation.radioButton input[disabled] { background: none; border: 1px solid transparent; cursor: not-allowed; @@ -130,7 +134,9 @@ .annotationLayer .textWidgetAnnotation input:hover, .annotationLayer .textWidgetAnnotation textarea:hover, -.annotationLayer .choiceWidgetAnnotation select:hover { +.annotationLayer .choiceWidgetAnnotation select:hover, +.annotationLayer .buttonWidgetAnnotation.checkBox input:hover, +.annotationLayer .buttonWidgetAnnotation.radioButton input:hover { border: 1px solid #000; } @@ -157,6 +163,12 @@ width: 115%; } +.annotationLayer .buttonWidgetAnnotation.checkBox input, +.annotationLayer .buttonWidgetAnnotation.radioButton input { + -moz-appearance: none; + appearance: none; +} + .annotationLayer .popupWrapper { position: absolute; width: 20em; diff --git a/browser/extensions/pdfjs/content/web/viewer.js b/browser/extensions/pdfjs/content/web/viewer.js index f853da16b7b9..1ee979322a8a 100644 --- a/browser/extensions/pdfjs/content/web/viewer.js +++ b/browser/extensions/pdfjs/content/web/viewer.js @@ -4119,7 +4119,7 @@ var pdfjsWebLibs; } if (error === 'cancelled') { self.error = null; - return; + return Promise.resolve(undefined); } self.renderingState = RenderingStates.FINISHED; if (self.loadingIconDiv) { @@ -4145,21 +4145,25 @@ var pdfjsWebLibs; pageNumber: self.id, cssTransform: false }); + if (error) { + return Promise.reject(error); + } + return Promise.resolve(undefined); }; var paintTask = this.renderer === RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper); paintTask.onRenderContinue = renderContinueCallback; this.paintTask = paintTask; var resultPromise = paintTask.promise.then(function () { - finishPaintTask(null); - if (textLayer) { - pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) { - textLayer.setTextContent(textContent); - textLayer.render(TEXT_LAYER_RENDER_DELAY); - }); - } + return finishPaintTask(null).then(function () { + if (textLayer) { + pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) { + textLayer.setTextContent(textContent); + textLayer.render(TEXT_LAYER_RENDER_DELAY); + }); + } + }); }, function (reason) { - finishPaintTask(reason); - throw reason; + return finishPaintTask(reason); }); if (this.annotationLayerFactory) { if (!this.annotationLayer) { From 7e7b9330e3a91f9a3c08ff9548aa03d4fbad9fbf Mon Sep 17 00:00:00 2001 From: Haik Aftandilian Date: Mon, 19 Dec 2016 18:16:31 -0800 Subject: [PATCH 130/229] Bug 1322716 - Remove /private/var regex from GMP sandbox rules. r=jesup, r=cpearce, r=gcp MozReview-Commit-ID: I1Y2MOum5T3 --- dom/media/gmp/GMPChild.cpp | 3 +++ security/sandbox/mac/Sandbox.mm | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/dom/media/gmp/GMPChild.cpp b/dom/media/gmp/GMPChild.cpp index 2eddc1c808dd..daea4f52b7c0 100644 --- a/dom/media/gmp/GMPChild.cpp +++ b/dom/media/gmp/GMPChild.cpp @@ -168,7 +168,10 @@ GetPluginPaths(const nsAString& aPluginPath, // Mac sandbox rules expect paths to actual files and directories -- not // soft links. + libDirectory->Normalize(); aPluginDirectoryPath = GetNativeTarget(libDirectory); + + libFile->Normalize(); aPluginFilePath = GetNativeTarget(libFile); return true; diff --git a/security/sandbox/mac/Sandbox.mm b/security/sandbox/mac/Sandbox.mm index d7f8e5cb162a..40048935e4c3 100644 --- a/security/sandbox/mac/Sandbox.mm +++ b/security/sandbox/mac/Sandbox.mm @@ -135,7 +135,6 @@ static const char pluginSandboxRules[] = "(allow file-read*\n" " (regex #\"^/etc$\")\n" " (regex #\"^/dev/u?random$\")\n" - " (regex #\"^/(private/)?var($|/)\")\n" " (literal \"/usr/share/icu/icudt51l.dat\")\n" " (regex #\"^/System/Library/Displays/Overrides/*\")\n" " (regex #\"^/System/Library/CoreServices/CoreTypes.bundle/*\")\n" From dee0c78211e033e28e1f3e0c7a5aec0e11a2e98a Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 17:57:07 +0100 Subject: [PATCH 131/229] Bug 1323100 - Stop double-registering the Socket Transport thread. r=froydnj MozReview-Commit-ID: 7YEC79PwUGg --HG-- extra : rebase_source : 17b5fa5358507d0cd87e07068434472967f317e1 --- netwerk/base/nsSocketTransportService2.cpp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/netwerk/base/nsSocketTransportService2.cpp b/netwerk/base/nsSocketTransportService2.cpp index 4705a6055d94..b47eee88e6c4 100644 --- a/netwerk/base/nsSocketTransportService2.cpp +++ b/netwerk/base/nsSocketTransportService2.cpp @@ -833,11 +833,6 @@ nsSocketTransportService::MarkTheLastElementOfPendingQueue() NS_IMETHODIMP nsSocketTransportService::Run() { -#ifdef MOZ_ENABLE_PROFILER_SPS - char stackBaseGuess; // Need to be the first variable of main loop function. - profiler_register_thread(PR_GetThreadName(PR_GetCurrentThread()), &stackBaseGuess); -#endif // MOZ_ENABLE_PROFILER_SPS - SOCKET_LOG(("STS thread init %d sockets\n", gMaxCount)); psm::InitializeSSLServerCertVerificationThreads(); @@ -1019,10 +1014,6 @@ nsSocketTransportService::Run() SOCKET_LOG(("STS thread exit\n")); -#ifdef MOZ_ENABLE_PROFILER_SPS - profiler_unregister_thread(); -#endif // MOZ_ENABLE_PROFILER_SPS - return NS_OK; } From 4e6ca03c5d255bc69653cb19f143575576311ed2 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 23:06:45 +0100 Subject: [PATCH 132/229] Bug 1323100 - Stop double-registering the MediaStreamGraph thread with the profiler. r=froydnj MozReview-Commit-ID: 7WxNLZpBWL4 --HG-- extra : rebase_source : ce8fe0481c8e3c3d3efd3d1c15480490943ee202 --- dom/media/GraphDriver.cpp | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/dom/media/GraphDriver.cpp b/dom/media/GraphDriver.cpp index 33001cd332cc..ecb0acaecd49 100644 --- a/dom/media/GraphDriver.cpp +++ b/dom/media/GraphDriver.cpp @@ -39,19 +39,6 @@ namespace mozilla { StaticRefPtr AsyncCubebTask::sThreadPool; -struct AutoProfilerUnregisterThread -{ - // The empty ctor is used to silence a pre-4.8.0 GCC unused variable warning. - AutoProfilerUnregisterThread() - { - } - - ~AutoProfilerUnregisterThread() - { - profiler_unregister_thread(); - } -}; - GraphDriver::GraphDriver(MediaStreamGraphImpl* aGraphImpl) : mIterationStart(0), mIterationEnd(0), @@ -196,9 +183,7 @@ public: } NS_IMETHOD Run() override { - char aLocal; STREAM_LOG(LogLevel::Debug, ("Starting system thread")); - profiler_register_thread("MediaStreamGraph", &aLocal); LIFECYCLE_LOG("Starting a new system driver for graph %p\n", mDriver->mGraphImpl); @@ -316,8 +301,6 @@ SystemClockDriver::IsFallback() void ThreadedDriver::RunThread() { - AutoProfilerUnregisterThread autoUnregister; - bool stillProcessing = true; while (stillProcessing) { mIterationStart = IterationEnd(); From 11eb304af28e941ebb4b9bb318396c68da30762b Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 23:06:56 +0100 Subject: [PATCH 133/229] Bug 1323100 - Stop double-registering the Media_Encoder thread with the profiler. r=froydnj MozReview-Commit-ID: 8TQMVhbw13s --HG-- extra : rebase_source : 6ebeba2b28f643a4b555e889b2f4f99a55e68485 --- dom/media/MediaRecorder.cpp | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/dom/media/MediaRecorder.cpp b/dom/media/MediaRecorder.cpp index 2deeb906d86b..4b4070257ccb 100644 --- a/dom/media/MediaRecorder.cpp +++ b/dom/media/MediaRecorder.cpp @@ -283,8 +283,6 @@ class MediaRecorder::Session: public nsIObserver, } else { // Flush out remaining encoded data. mSession->Extract(true); - if (mSession->mIsRegisterProfiler) - profiler_unregister_thread(); if (NS_FAILED(NS_DispatchToMainThread( new DestroyRunnable(mSession)))) { MOZ_ASSERT(false, "NS_DispatchToMainThread DestroyRunnable failed"); @@ -419,7 +417,6 @@ public: , mTimeSlice(aTimeSlice) , mStopIssued(false) , mIsStartEventFired(false) - , mIsRegisterProfiler(false) , mNeedSessionEndTask(true) , mSelectedVideoTrackID(TRACK_NONE) { @@ -607,12 +604,6 @@ private: MOZ_ASSERT(NS_GetCurrentThread() == mReadThread); LOG(LogLevel::Debug, ("Session.Extract %p", this)); - if (!mIsRegisterProfiler) { - char aLocal; - profiler_register_thread("Media_Encoder", &aLocal); - mIsRegisterProfiler = true; - } - PROFILER_LABEL("MediaRecorder", "Session Extract", js::ProfileEntry::Category::OTHER); @@ -922,8 +913,6 @@ private: bool mStopIssued; // Indicate the session had fire start event. Encoding thread only. bool mIsStartEventFired; - // The register flag for "Media_Encoder" thread to profiler - bool mIsRegisterProfiler; // False if the InitEncoder called successfully, ensure the // ExtractRunnable/DestroyRunnable will end the session. // Main thread only. From 452381048206a5f63d8c732238225c968e15b24d Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 23:07:10 +0100 Subject: [PATCH 134/229] Bug 1323100 - Stop double-registering the IPDL Background thread with the profiler. r=froydnj MozReview-Commit-ID: 2BlEhqrxdUz --HG-- extra : rebase_source : c74067a284337374188ff408406232a90171b828 --- ipc/glue/BackgroundImpl.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/ipc/glue/BackgroundImpl.cpp b/ipc/glue/BackgroundImpl.cpp index 2f8e073f8397..86b619f8f2f0 100644 --- a/ipc/glue/BackgroundImpl.cpp +++ b/ipc/glue/BackgroundImpl.cpp @@ -1344,8 +1344,6 @@ ParentImpl::RequestMessageLoopRunnable::Run() AssertIsInMainProcess(); MOZ_ASSERT(mTargetThread); - char stackBaseGuess; - if (NS_IsMainThread()) { MOZ_ASSERT(mMessageLoop); @@ -1375,8 +1373,6 @@ ParentImpl::RequestMessageLoopRunnable::Run() return NS_OK; } - profiler_register_thread("IPDL Background", &stackBaseGuess); - #ifdef DEBUG { bool correctThread; @@ -1414,8 +1410,6 @@ ParentImpl::ShutdownBackgroundThreadRunnable::Run() // sBackgroundPRThread and we should not modify it here. sBackgroundPRThread.compareExchange(PR_GetCurrentThread(), nullptr); - profiler_unregister_thread(); - return NS_OK; } From 38bf16074f8bb2cb0be1f1c97bc86dce65a537fc Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Wed, 21 Dec 2016 23:07:26 +0100 Subject: [PATCH 135/229] Bug 1323100 - Stop double-registering the LazyIdleThread with the profiler. r=froydnj MozReview-Commit-ID: 2vdcgCcdOYJ --HG-- extra : rebase_source : 2a42caebc2a80b4d634eb741bbc196a718379e22 --- xpcom/threads/LazyIdleThread.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/xpcom/threads/LazyIdleThread.cpp b/xpcom/threads/LazyIdleThread.cpp index b6218e959292..be3acfa61fc5 100644 --- a/xpcom/threads/LazyIdleThread.cpp +++ b/xpcom/threads/LazyIdleThread.cpp @@ -180,11 +180,6 @@ LazyIdleThread::EnsureThread() void LazyIdleThread::InitThread() { - char aLocal; - profiler_register_thread(mName.get(), &aLocal); - - PR_SetCurrentThreadName(mName.get()); - // Happens on mThread but mThread may not be set yet... nsCOMPtr thread(do_QueryInterface(NS_GetCurrentThread())); @@ -211,8 +206,6 @@ LazyIdleThread::CleanupThread() MOZ_ASSERT(!mThreadIsShuttingDown, "Shouldn't be true ever!"); mThreadIsShuttingDown = true; } - - profiler_unregister_thread(); } void From 48513de60f2455e6b6316681149ee3bb41e209d0 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 29 Dec 2016 22:32:52 +0100 Subject: [PATCH 136/229] Bug 1323100 - Register most of the remaining threadfunc threads with the profiler. r=froydnj As far as I can tell, this covers all the remaining threads which we start using PR_CreateThread, except the ones that are created inside NSPR or NSS. This adds a AutoProfilerRegister stack class for easy registering and unregistering. There are a few places where we still call profiler_register_thread() and profiler_unregister_thread() manually, either because registration happens conditionally, or because there is a variable that gets put on the stack before the AutoProfilerRegister (e.g. a dynamically generated thread name). AutoProfilerRegister needs to be the first object on the stack because it uses its own `this` pointer as the stack top address. MozReview-Commit-ID: 3vwhS55Yzt --HG-- extra : rebase_source : dffab11abf7d4b57fa54475fd22e71b84375cd7b --- .../webaudio/blink/HRTFDatabaseLoader.cpp | 2 ++ dom/storage/DOMStorageDBThread.cpp | 2 ++ js/xpconnect/src/XPCJSContext.cpp | 1 + netwerk/cache2/CacheIOThread.cpp | 2 ++ netwerk/dns/nsHostResolver.cpp | 6 ++++++ security/manager/ssl/nsKeygenThread.cpp | 2 ++ .../manager/ssl/nsProtectedAuthThread.cpp | 2 ++ security/manager/ssl/nsSmartCardMonitor.cpp | 2 ++ startupcache/StartupCache.cpp | 2 ++ .../components/terminator/nsTerminator.cpp | 3 +++ toolkit/xre/EventTracer.cpp | 1 + tools/profiler/public/GeckoProfiler.h | 8 ++++++++ tools/profiler/public/GeckoProfilerImpl.h | 20 +++++++++++++++++++ xpcom/build/MainThreadIOLogger.cpp | 1 + xpcom/threads/BackgroundHangMonitor.cpp | 2 ++ xpcom/threads/HangMonitor.cpp | 2 ++ xpcom/threads/nsProcessCommon.cpp | 8 ++++++++ 17 files changed, 66 insertions(+) diff --git a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp index 090e1b2172af..41be2c2daa5d 100644 --- a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp +++ b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp @@ -28,6 +28,7 @@ #include "HRTFDatabaseLoader.h" #include "HRTFDatabase.h" +#include "GeckoProfiler.h" using namespace mozilla; @@ -151,6 +152,7 @@ void HRTFDatabaseLoader::MainThreadRelease() // Asynchronously load the database in this thread. static void databaseLoaderEntry(void* threadData) { + AutoProfilerRegister registerThread("HRTFDatabaseLdr"); PR_SetCurrentThreadName("HRTFDatabaseLdr"); HRTFDatabaseLoader* loader = reinterpret_cast(threadData); diff --git a/dom/storage/DOMStorageDBThread.cpp b/dom/storage/DOMStorageDBThread.cpp index d479fbb783f4..7f9039484d82 100644 --- a/dom/storage/DOMStorageDBThread.cpp +++ b/dom/storage/DOMStorageDBThread.cpp @@ -27,6 +27,7 @@ #include "mozilla/IOInterposer.h" #include "mozilla/Services.h" #include "mozilla/Tokenizer.h" +#include "GeckoProfiler.h" // How long we collect write oprerations // before they are flushed to the database @@ -337,6 +338,7 @@ DOMStorageDBThread::SetDefaultPriority() void DOMStorageDBThread::ThreadFunc(void* aArg) { + AutoProfilerRegister registerThread("localStorage DB"); PR_SetCurrentThreadName("localStorage DB"); mozilla::IOInterposer::RegisterCurrentThread(); diff --git a/js/xpconnect/src/XPCJSContext.cpp b/js/xpconnect/src/XPCJSContext.cpp index 5b4d184ea2f8..0393ae9ef498 100644 --- a/js/xpconnect/src/XPCJSContext.cpp +++ b/js/xpconnect/src/XPCJSContext.cpp @@ -1166,6 +1166,7 @@ AutoLockWatchdog::~AutoLockWatchdog() static void WatchdogMain(void* arg) { + mozilla::AutoProfilerRegister registerThread("JS Watchdog"); PR_SetCurrentThreadName("JS Watchdog"); Watchdog* self = static_cast(arg); diff --git a/netwerk/cache2/CacheIOThread.cpp b/netwerk/cache2/CacheIOThread.cpp index 66742679c9ac..be5092a6d09c 100644 --- a/netwerk/cache2/CacheIOThread.cpp +++ b/netwerk/cache2/CacheIOThread.cpp @@ -10,6 +10,7 @@ #include "nsPrintfCString.h" #include "nsThreadUtils.h" #include "mozilla/IOInterposer.h" +#include "GeckoProfiler.h" #ifdef XP_WIN #include @@ -437,6 +438,7 @@ already_AddRefed CacheIOThread::Target() // static void CacheIOThread::ThreadFunc(void* aClosure) { + AutoProfilerRegister registerThread("Cache2 I/O"); PR_SetCurrentThreadName("Cache2 I/O"); mozilla::IOInterposer::RegisterCurrentThread(); CacheIOThread* thread = static_cast(aClosure); diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index 78cdfebf0909..8924ed7e4d10 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -29,6 +29,7 @@ #include "nsURLHelper.h" #include "nsThreadUtils.h" #include "GetAddrInfo.h" +#include "GeckoProfiler.h" #include "mozilla/HashFunctions.h" #include "mozilla/TimeStamp.h" @@ -1435,12 +1436,15 @@ nsHostResolver::SizeOfIncludingThis(MallocSizeOf mallocSizeOf) const void nsHostResolver::ThreadFunc(void *arg) { + char stackTop; + LOG(("DNS lookup thread - starting execution.\n")); static nsThreadPoolNaming naming; nsCString name = naming.GetNextThreadName("DNS Resolver"); PR_SetCurrentThreadName(name.BeginReading()); + profiler_register_thread(name.BeginReading(), &stackTop); #if defined(RES_RETRY_ON_FAILURE) nsResState rs; @@ -1511,6 +1515,8 @@ nsHostResolver::ThreadFunc(void *arg) resolver->mThreadCount--; NS_RELEASE(resolver); LOG(("DNS lookup thread - queue empty, thread finished.\n")); + + profiler_unregister_thread(); } nsresult diff --git a/security/manager/ssl/nsKeygenThread.cpp b/security/manager/ssl/nsKeygenThread.cpp index b295c4f36895..4ff0304e229a 100644 --- a/security/manager/ssl/nsKeygenThread.cpp +++ b/security/manager/ssl/nsKeygenThread.cpp @@ -12,6 +12,7 @@ #include "nsNSSShutDown.h" #include "PSMRunnable.h" #include "mozilla/DebugOnly.h" +#include "GeckoProfiler.h" using namespace mozilla; using namespace mozilla::psm; @@ -114,6 +115,7 @@ nsresult nsKeygenThread::ConsumeResult( static void nsKeygenThreadRunner(void *arg) { + AutoProfilerRegister registerThread("Keygen"); PR_SetCurrentThreadName("Keygen"); nsKeygenThread *self = static_cast(arg); self->Run(); diff --git a/security/manager/ssl/nsProtectedAuthThread.cpp b/security/manager/ssl/nsProtectedAuthThread.cpp index ea511b24a63d..bb930188b874 100644 --- a/security/manager/ssl/nsProtectedAuthThread.cpp +++ b/security/manager/ssl/nsProtectedAuthThread.cpp @@ -11,6 +11,7 @@ #include "nsReadableUtils.h" #include "nsPKCS11Slot.h" #include "nsProtectedAuthThread.h" +#include "GeckoProfiler.h" using namespace mozilla; using namespace mozilla::psm; @@ -19,6 +20,7 @@ NS_IMPL_ISUPPORTS(nsProtectedAuthThread, nsIProtectedAuthThread) static void nsProtectedAuthThreadRunner(void *arg) { + AutoProfilerRegister registerThread("Protected Auth"); PR_SetCurrentThreadName("Protected Auth"); nsProtectedAuthThread *self = static_cast(arg); diff --git a/security/manager/ssl/nsSmartCardMonitor.cpp b/security/manager/ssl/nsSmartCardMonitor.cpp index 3423d4f5f5f1..a5cb8610aef2 100644 --- a/security/manager/ssl/nsSmartCardMonitor.cpp +++ b/security/manager/ssl/nsSmartCardMonitor.cpp @@ -10,6 +10,7 @@ #include "nsIObserverService.h" #include "nsServiceManagerUtils.h" #include "nsThreadUtils.h" +#include "GeckoProfiler.h" #include "nspr.h" #include "pk11func.h" @@ -390,6 +391,7 @@ const SECMODModule* SmartCardMonitoringThread::GetModule() // C-like calling sequence to glue into PR_CreateThread. void SmartCardMonitoringThread::LaunchExecute(void* arg) { + AutoProfilerRegister registerThread("SmartCard"); PR_SetCurrentThreadName("SmartCard"); ((SmartCardMonitoringThread*)arg)->Execute(); diff --git a/startupcache/StartupCache.cpp b/startupcache/StartupCache.cpp index 6d1dd7a3a3ff..f698187170a5 100644 --- a/startupcache/StartupCache.cpp +++ b/startupcache/StartupCache.cpp @@ -36,6 +36,7 @@ #include "nsThreadUtils.h" #include "nsXULAppAPI.h" #include "nsIProtocolHandler.h" +#include "GeckoProfiler.h" #ifdef IS_BIG_ENDIAN #define SC_ENDIAN "big" @@ -503,6 +504,7 @@ StartupCache::WaitOnWriteThread() void StartupCache::ThreadedWrite(void *aClosure) { + AutoProfilerRegister registerThread("StartupCache"); PR_SetCurrentThreadName("StartupCache"); mozilla::IOInterposer::RegisterCurrentThread(); /* diff --git a/toolkit/components/terminator/nsTerminator.cpp b/toolkit/components/terminator/nsTerminator.cpp index e3d958a8807f..ff9b03132922 100644 --- a/toolkit/components/terminator/nsTerminator.cpp +++ b/toolkit/components/terminator/nsTerminator.cpp @@ -32,6 +32,7 @@ #if defined(MOZ_CRASHREPORTER) #include "nsExceptionHandler.h" #endif +#include "GeckoProfiler.h" #if defined(XP_WIN) #include @@ -124,6 +125,7 @@ struct Options { void RunWatchdog(void* arg) { + AutoProfilerRegister registerThread("Shutdown Hang Terminator"); PR_SetCurrentThreadName("Shutdown Hang Terminator"); // Let's copy and deallocate options, that's one less leak to worry @@ -214,6 +216,7 @@ PRMonitor* gWriteReady = nullptr; void RunWriter(void* arg) { + AutoProfilerRegister registerThread("Shutdown Statistics Writer"); PR_SetCurrentThreadName("Shutdown Statistics Writer"); MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(arg); diff --git a/toolkit/xre/EventTracer.cpp b/toolkit/xre/EventTracer.cpp index cb0d88524db4..622334f43eda 100644 --- a/toolkit/xre/EventTracer.cpp +++ b/toolkit/xre/EventTracer.cpp @@ -122,6 +122,7 @@ class EventLoopLagDispatcher : public Runnable */ void TracerThread(void *arg) { + AutoProfilerRegister registerThread("Event Tracer"); PR_SetCurrentThreadName("Event Tracer"); TracerStartClosure* threadArgs = static_cast(arg); diff --git a/tools/profiler/public/GeckoProfiler.h b/tools/profiler/public/GeckoProfiler.h index bef017d11558..81452dd6563c 100644 --- a/tools/profiler/public/GeckoProfiler.h +++ b/tools/profiler/public/GeckoProfiler.h @@ -248,6 +248,14 @@ static inline bool profiler_in_privacy_mode() { return false; } static inline void profiler_log(const char *str) {} static inline void profiler_log(const char *fmt, va_list args) {} +class AutoProfilerRegister final MOZ_STACK_CLASS +{ + AutoProfilerRegister(const char* aName) {} +private: + AutoProfilerRegister(const AutoProfilerRegister&) = delete; + AutoProfilerRegister& operator=(const AutoProfilerRegister&) = delete; +}; + #else #include "GeckoProfilerImpl.h" diff --git a/tools/profiler/public/GeckoProfilerImpl.h b/tools/profiler/public/GeckoProfilerImpl.h index a32096b94315..2522400fff62 100644 --- a/tools/profiler/public/GeckoProfilerImpl.h +++ b/tools/profiler/public/GeckoProfilerImpl.h @@ -461,6 +461,26 @@ private: void* mHandle; }; +/** + * Convenience class to register and unregister a thread with the profiler. + * Needs to be the first object on the stack of the thread. + */ +class MOZ_STACK_CLASS AutoProfilerRegister final +{ +public: + explicit AutoProfilerRegister(const char* aName) + { + profiler_register_thread(aName, this); + } + ~AutoProfilerRegister() + { + profiler_unregister_thread(); + } +private: + AutoProfilerRegister(const AutoProfilerRegister&) = delete; + AutoProfilerRegister& operator=(const AutoProfilerRegister&) = delete; +}; + } // namespace mozilla inline PseudoStack* mozilla_get_pseudo_stack(void) diff --git a/xpcom/build/MainThreadIOLogger.cpp b/xpcom/build/MainThreadIOLogger.cpp index 0ca942cb9f76..95e469899fbd 100644 --- a/xpcom/build/MainThreadIOLogger.cpp +++ b/xpcom/build/MainThreadIOLogger.cpp @@ -114,6 +114,7 @@ MainThreadIOLoggerImpl::Init() /* static */ void MainThreadIOLoggerImpl::sIOThreadFunc(void* aArg) { + AutoProfilerRegister registerThread("MainThreadIOLogger"); PR_SetCurrentThreadName("MainThreadIOLogger"); MainThreadIOLoggerImpl* obj = static_cast(aArg); obj->IOThreadFunc(); diff --git a/xpcom/threads/BackgroundHangMonitor.cpp b/xpcom/threads/BackgroundHangMonitor.cpp index ac65d9f37162..cc16973752fa 100644 --- a/xpcom/threads/BackgroundHangMonitor.cpp +++ b/xpcom/threads/BackgroundHangMonitor.cpp @@ -22,6 +22,7 @@ #include "nsIObserver.h" #include "mozilla/Services.h" #include "nsXULAppAPI.h" +#include "GeckoProfiler.h" #include @@ -54,6 +55,7 @@ private: // Background hang monitor thread function static void MonitorThread(void* aData) { + AutoProfilerRegister registerThread("BgHangMonitor"); PR_SetCurrentThreadName("BgHangManager"); /* We do not hold a reference to BackgroundHangManager here diff --git a/xpcom/threads/HangMonitor.cpp b/xpcom/threads/HangMonitor.cpp index cde8052f33c4..ab402eb68f58 100644 --- a/xpcom/threads/HangMonitor.cpp +++ b/xpcom/threads/HangMonitor.cpp @@ -21,6 +21,7 @@ #endif #include "nsThreadUtils.h" #include "nsXULAppAPI.h" +#include "GeckoProfiler.h" #ifdef MOZ_CRASHREPORTER #include "nsExceptionHandler.h" @@ -209,6 +210,7 @@ GetChromeHangReport(Telemetry::ProcessedStack& aStack, void ThreadMain(void*) { + AutoProfilerRegister registerThread("Hang Monitor"); PR_SetCurrentThreadName("Hang Monitor"); MonitorAutoLock lock(*gMonitor); diff --git a/xpcom/threads/nsProcessCommon.cpp b/xpcom/threads/nsProcessCommon.cpp index 709865a09d8b..37071b58c95f 100644 --- a/xpcom/threads/nsProcessCommon.cpp +++ b/xpcom/threads/nsProcessCommon.cpp @@ -25,6 +25,7 @@ #include "nsIObserverService.h" #include "nsXULAppAPI.h" #include "mozilla/Services.h" +#include "GeckoProfiler.h" #include @@ -235,10 +236,13 @@ assembleCmdLine(char* const* aArgv, wchar_t** aWideCmdLine, UINT aCodePage) void nsProcess::Monitor(void* aArg) { + char stackBaseGuess; + RefPtr process = dont_AddRef(static_cast(aArg)); if (!process->mBlocking) { PR_SetCurrentThreadName("RunProcess"); + profiler_register_thread("RunProcess", &stackBaseGuess); } #if defined(PROCESSMODEL_WINAPI) @@ -304,6 +308,10 @@ nsProcess::Monitor(void* aArg) } else { NS_DispatchToMainThread(NewRunnableMethod(process, &nsProcess::ProcessComplete)); } + + if (!process->mBlocking) { + profiler_unregister_thread(); + } } void From f4527282564f885a411ede37546d377bd849402e Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Thu, 22 Dec 2016 00:48:55 +0100 Subject: [PATCH 137/229] Bug 1323100 - Use AutoProfilerRegister to register chromium threads with the profiler. r=froydnj MozReview-Commit-ID: 12LS5hqCA2c --HG-- extra : rebase_source : 9b5e44b5710b7758c998601f1da79429956ae4c7 --- ipc/chromium/src/base/thread.cc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ipc/chromium/src/base/thread.cc b/ipc/chromium/src/base/thread.cc index feec3aedf797..05463aecac18 100644 --- a/ipc/chromium/src/base/thread.cc +++ b/ipc/chromium/src/base/thread.cc @@ -153,8 +153,7 @@ void Thread::StopSoon() { } void Thread::ThreadMain() { - char aLocal; - profiler_register_thread(name_.c_str(), &aLocal); + mozilla::AutoProfilerRegister registerThread(name_.c_str()); mozilla::IOInterposer::RegisterCurrentThread(); // The message loop for this thread. @@ -186,7 +185,6 @@ void Thread::ThreadMain() { DCHECK(GetThreadWasQuitProperly()); mozilla::IOInterposer::UnregisterCurrentThread(); - profiler_unregister_thread(); #ifdef MOZ_TASK_TRACER mozilla::tasktracer::FreeTraceInfo(); From 2941566445967e89987ea2c6e62caa6d365974a3 Mon Sep 17 00:00:00 2001 From: Jan Beich Date: Sat, 31 Dec 2016 08:27:27 +0000 Subject: [PATCH 138/229] Bug 1326524 - Unbreak build without SPS profiler after bug 1324941. r=mstange MozReview-Commit-ID: 2E4MlCLQ9lf --HG-- extra : rebase_source : 2e7644176d0c478a5876b5d2e6604f341c13ea5b --- dom/events/EventListenerManager.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/dom/events/EventListenerManager.cpp b/dom/events/EventListenerManager.cpp index efbb2b003322..cf24c7b231bb 100644 --- a/dom/events/EventListenerManager.cpp +++ b/dom/events/EventListenerManager.cpp @@ -33,7 +33,9 @@ #include "EventListenerService.h" #include "GeckoProfiler.h" +#ifdef MOZ_ENABLE_PROFILER_SPS #include "ProfilerMarkers.h" +#endif #include "nsCOMArray.h" #include "nsCOMPtr.h" #include "nsContentUtils.h" @@ -1287,6 +1289,7 @@ EventListenerManager::HandleEventInternal(nsPresContext* aPresContext, nsresult rv = NS_OK; if (profiler_is_active()) { +#ifdef MOZ_ENABLE_PROFILER_SPS // Add a profiler label and a profiler marker for the actual // dispatch of the event. // This is a very hot code path, so we need to make sure not to @@ -1308,6 +1311,9 @@ EventListenerManager::HandleEventInternal(nsPresContext* aPresContext, new DOMEventMarkerPayload(typeStr, phase, startTime, endTime)); +#else + MOZ_CRASH("SPS profiler is N/A but profiler_is_active() returned true"); +#endif } else { rv = HandleEventSubType(listener, *aDOMEvent, aCurrentTarget); } From 3c057d1a7561177d1b9fb6877d61075b308ee819 Mon Sep 17 00:00:00 2001 From: Cameron McCormack Date: Mon, 2 Jan 2017 15:44:23 +0800 Subject: [PATCH 139/229] Bug 1323717 - Re-enable 1290994-4.html. r=manishearth MozReview-Commit-ID: 1LRTnuK0ulh --HG-- extra : rebase_source : da27637bb01b0946c759e52bd3ea01560f959b55 --- layout/style/crashtests/crashtests.list | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/layout/style/crashtests/crashtests.list b/layout/style/crashtests/crashtests.list index 9d7c3c9050c8..2d1d62fcd378 100644 --- a/layout/style/crashtests/crashtests.list +++ b/layout/style/crashtests/crashtests.list @@ -159,7 +159,7 @@ asserts-if(stylo,4-64) pref(dom.animations-api.core.enabled,true) load 1282076-2 asserts-if(stylo,2) pref(dom.animations-api.core.enabled,true) load 1290994-1.html # bug 1324690 asserts-if(stylo,2) pref(dom.animations-api.core.enabled,true) load 1290994-2.html # bug 1324690 asserts-if(stylo,1) pref(dom.animations-api.core.enabled,true) load 1290994-3.html # bug 1324690 -skip-if(stylo) load 1290994-4.html # bug 1323717 +load 1290994-4.html load 1314531.html load 1315889-1.html load 1315894-1.html From 7b71dd0944b9e088443b17ba944511afe20f0259 Mon Sep 17 00:00:00 2001 From: JW Wang Date: Thu, 22 Dec 2016 16:48:54 +0800 Subject: [PATCH 140/229] Bug 1325317. Part 1 - move StopMediaSink() out of MediaDecoderStateMachine::Reset(). r=kikuo MozReview-Commit-ID: 6Bso8uxM7Ee --HG-- extra : rebase_source : e255128028e33b2aad3566f5a3a3a09a07ac2d68 extra : intermediate-source : a3be598566377928746b5e37800d788cdcab6942 extra : source : f46b24e31cbb07243ca74206bd2e05e99b070286 --- dom/media/MediaDecoderStateMachine.cpp | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/dom/media/MediaDecoderStateMachine.cpp b/dom/media/MediaDecoderStateMachine.cpp index 356ac26e7eb9..0c4f28ceab64 100644 --- a/dom/media/MediaDecoderStateMachine.cpp +++ b/dom/media/MediaDecoderStateMachine.cpp @@ -433,6 +433,7 @@ public: RefPtr x = mPendingSeek.mPromise.Ensure(__func__); mMaster->Reset(); + mMaster->StopMediaSink(); mMaster->mReader->ReleaseResources(); } @@ -979,6 +980,7 @@ private: mMaster->Reset(TrackInfo::kVideoTrack); } else { mMaster->Reset(); + mMaster->StopMediaSink(); } DemuxerSeek(); @@ -2285,7 +2287,7 @@ ShutdownState::Enter() master->mVideoWaitRequest.DisconnectIfExists(); master->Reset(); - + master->StopMediaSink(); master->mMediaSink->Shutdown(); // Prevent dangling pointers by disconnecting the listeners. @@ -3393,14 +3395,6 @@ MediaDecoderStateMachine::Reset(TrackSet aTracks) // don't currently support resetting just the audio track. MOZ_ASSERT(aTracks.contains(TrackInfo::kVideoTrack)); - if (aTracks.contains(TrackInfo::kAudioTrack) && - aTracks.contains(TrackInfo::kVideoTrack)) { - // Stop the audio thread. Otherwise, MediaSink might be accessing AudioQueue - // outside of the decoder monitor while we are clearing the queue and causes - // crash for no samples to be popped. - StopMediaSink(); - } - if (aTracks.contains(TrackInfo::kVideoTrack)) { mDecodedVideoEndTime = 0; mVideoCompleted = false; From dae2fad2189c6e484a19ea854d65c94379694140 Mon Sep 17 00:00:00 2001 From: JW Wang Date: Thu, 22 Dec 2016 16:56:59 +0800 Subject: [PATCH 141/229] Bug 1325317. Part 2 - rename the function and fix comments. r=kikuo MozReview-Commit-ID: 3GUkH5OpSmJ --HG-- extra : rebase_source : 421c16cf75bde625b158571439fb9b4d29e8046f extra : intermediate-source : 22b22702bafca7da4f12e3abdb08cabcf9eff20c extra : source : e7b0f09a40bf5f148496470bb019c11dc5431856 --- dom/media/MediaDecoderStateMachine.cpp | 10 +++++----- dom/media/MediaDecoderStateMachine.h | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/dom/media/MediaDecoderStateMachine.cpp b/dom/media/MediaDecoderStateMachine.cpp index 0c4f28ceab64..8b4785e0fc35 100644 --- a/dom/media/MediaDecoderStateMachine.cpp +++ b/dom/media/MediaDecoderStateMachine.cpp @@ -432,7 +432,7 @@ public: // need to create the promise even it is not used at all. RefPtr x = mPendingSeek.mPromise.Ensure(__func__); - mMaster->Reset(); + mMaster->ResetDecode(); mMaster->StopMediaSink(); mMaster->mReader->ReleaseResources(); } @@ -977,9 +977,9 @@ private: mDoneVideoSeeking = !Info().HasVideo(); if (mSeekJob.mTarget->IsVideoOnly()) { - mMaster->Reset(TrackInfo::kVideoTrack); + mMaster->ResetDecode(TrackInfo::kVideoTrack); } else { - mMaster->Reset(); + mMaster->ResetDecode(); mMaster->StopMediaSink(); } @@ -2286,7 +2286,7 @@ ShutdownState::Enter() master->mAudioWaitRequest.DisconnectIfExists(); master->mVideoWaitRequest.DisconnectIfExists(); - master->Reset(); + master->ResetDecode(); master->StopMediaSink(); master->mMediaSink->Shutdown(); @@ -3378,7 +3378,7 @@ MediaDecoderStateMachine::RunStateMachine() } void -MediaDecoderStateMachine::Reset(TrackSet aTracks) +MediaDecoderStateMachine::ResetDecode(TrackSet aTracks) { MOZ_ASSERT(OnTaskQueue()); DECODER_LOG("MediaDecoderStateMachine::Reset"); diff --git a/dom/media/MediaDecoderStateMachine.h b/dom/media/MediaDecoderStateMachine.h index feef469c64c3..0644c2b6011f 100644 --- a/dom/media/MediaDecoderStateMachine.h +++ b/dom/media/MediaDecoderStateMachine.h @@ -324,10 +324,10 @@ private: // be held. bool IsPlaying() const; - // Resets all state related to decoding and playback, emptying all buffers - // and aborting all pending operations on the decode task queue. - void Reset(TrackSet aTracks = TrackSet(TrackInfo::kAudioTrack, - TrackInfo::kVideoTrack)); + // Resets all states related to decoding and aborts all pending requests + // to the decoders. + void ResetDecode(TrackSet aTracks = TrackSet(TrackInfo::kAudioTrack, + TrackInfo::kVideoTrack)); protected: virtual ~MediaDecoderStateMachine(); From 2319d2881ddbb4cb30270370c10036b5effacac3 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Fri, 23 Dec 2016 12:44:35 +0100 Subject: [PATCH 142/229] Bug 1324941 - Add a profiler label and a profiler marker for DOMEvent dispatch. r=smaug MozReview-Commit-ID: 9nyftWPKRVe --HG-- extra : rebase_source : 0ef900fa5c7749dd5bcec32da6b37aad91f0a518 --- dom/events/EventListenerManager.cpp | 33 ++++++++++++++++++++++++- tools/profiler/core/ProfilerMarkers.cpp | 21 ++++++++++++++++ tools/profiler/public/ProfilerMarkers.h | 16 ++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) diff --git a/dom/events/EventListenerManager.cpp b/dom/events/EventListenerManager.cpp index f11e2b20ba8c..efbb2b003322 100644 --- a/dom/events/EventListenerManager.cpp +++ b/dom/events/EventListenerManager.cpp @@ -29,8 +29,11 @@ #include "mozilla/dom/TouchEvent.h" #include "mozilla/TimelineConsumers.h" #include "mozilla/EventTimelineMarker.h" +#include "mozilla/TimeStamp.h" #include "EventListenerService.h" +#include "GeckoProfiler.h" +#include "ProfilerMarkers.h" #include "nsCOMArray.h" #include "nsCOMPtr.h" #include "nsContentUtils.h" @@ -1281,7 +1284,35 @@ EventListenerManager::HandleEventInternal(nsPresContext* aPresContext, listener = listenerHolder.ptr(); hasRemovedListener = true; } - if (NS_FAILED(HandleEventSubType(listener, *aDOMEvent, aCurrentTarget))) { + + nsresult rv = NS_OK; + if (profiler_is_active()) { + // Add a profiler label and a profiler marker for the actual + // dispatch of the event. + // This is a very hot code path, so we need to make sure not to + // do this extra work when we're not profiling. + nsAutoString typeStr; + (*aDOMEvent)->GetType(typeStr); + PROFILER_LABEL_PRINTF("EventListenerManager", "HandleEventInternal", + js::ProfileEntry::Category::EVENTS, + "%s", + NS_LossyConvertUTF16toASCII(typeStr).get()); + TimeStamp startTime = TimeStamp::Now(); + + rv = HandleEventSubType(listener, *aDOMEvent, aCurrentTarget); + + TimeStamp endTime = TimeStamp::Now(); + uint16_t phase; + (*aDOMEvent)->GetEventPhase(&phase); + PROFILER_MARKER_PAYLOAD("DOMEvent", + new DOMEventMarkerPayload(typeStr, phase, + startTime, + endTime)); + } else { + rv = HandleEventSubType(listener, *aDOMEvent, aCurrentTarget); + } + + if (NS_FAILED(rv)) { aEvent->mFlags.mExceptionWasRaised = true; } aEvent->mFlags.mInPassiveListener = false; diff --git a/tools/profiler/core/ProfilerMarkers.cpp b/tools/profiler/core/ProfilerMarkers.cpp index 3cb47de4870f..6937ee420921 100644 --- a/tools/profiler/core/ProfilerMarkers.cpp +++ b/tools/profiler/core/ProfilerMarkers.cpp @@ -154,6 +154,27 @@ IOMarkerPayload::StreamPayload(SpliceableJSONWriter& aWriter, UniqueStacks& aUni } } +DOMEventMarkerPayload::DOMEventMarkerPayload(const nsAString& aType, uint16_t aPhase, + const mozilla::TimeStamp& aStartTime, + const mozilla::TimeStamp& aEndTime) + : ProfilerMarkerPayload(aStartTime, aEndTime, nullptr) + , mType(aType) + , mPhase(aPhase) +{ +} + +DOMEventMarkerPayload::~DOMEventMarkerPayload() +{ +} + +void +DOMEventMarkerPayload::StreamPayload(SpliceableJSONWriter& aWriter, UniqueStacks& aUniqueStacks) +{ + streamCommonProps("DOMEvent", aWriter, aUniqueStacks); + aWriter.StringProperty("type", NS_ConvertUTF16toUTF8(mType).get()); + aWriter.IntProperty("phase", mPhase); +} + void ProfilerJSEventMarker(const char *event) { diff --git a/tools/profiler/public/ProfilerMarkers.h b/tools/profiler/public/ProfilerMarkers.h index 29711f210c16..e1cb6ed61dfd 100644 --- a/tools/profiler/public/ProfilerMarkers.h +++ b/tools/profiler/public/ProfilerMarkers.h @@ -117,6 +117,22 @@ private: char* mFilename; }; +class DOMEventMarkerPayload : public ProfilerMarkerPayload +{ +public: + DOMEventMarkerPayload(const nsAString& aType, uint16_t aPhase, + const mozilla::TimeStamp& aStartTime, + const mozilla::TimeStamp& aEndTime); + ~DOMEventMarkerPayload(); + + virtual void StreamPayload(SpliceableJSONWriter& aWriter, + UniqueStacks& aUniqueStacks) override; + +private: + nsString mType; + uint16_t mPhase; +}; + /** * Contains the translation applied to a 2d layer so we can * track the layer position at each frame. From 26a1ba5c14d2d8cfb68b40f913620220d4a1bc33 Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Thu, 29 Dec 2016 16:28:36 -0800 Subject: [PATCH 143/229] Backed out 27 changesets (bug 1323100) for clipboard leaktest failures a=backout Backed out changeset 84fb749698ab (bug 1323100) Backed out changeset d6d25e8bd001 (bug 1323100) Backed out changeset 1b0855bb0c38 (bug 1323100) Backed out changeset b6953e3f5739 (bug 1323100) Backed out changeset 5572f3b63215 (bug 1323100) Backed out changeset 12fb4c533659 (bug 1323100) Backed out changeset c36524e4e919 (bug 1323100) Backed out changeset 1e3b3eddbe26 (bug 1323100) Backed out changeset 061110f1ae12 (bug 1323100) Backed out changeset 413dbd31725b (bug 1323100) Backed out changeset 06550f7eca62 (bug 1323100) Backed out changeset 940933b13b36 (bug 1323100) Backed out changeset a6d75c1cd724 (bug 1323100) Backed out changeset 681cacbbaa3b (bug 1323100) Backed out changeset 3d53787293f6 (bug 1323100) Backed out changeset c0340dfe4766 (bug 1323100) Backed out changeset 9f554991549d (bug 1323100) Backed out changeset 757539e7039a (bug 1323100) Backed out changeset a3c9b45aa917 (bug 1323100) Backed out changeset 23d69df98a66 (bug 1323100) Backed out changeset 1297ded6a01d (bug 1323100) Backed out changeset f4235b97257f (bug 1323100) Backed out changeset 93419cb4f29f (bug 1323100) Backed out changeset 865d1b81c804 (bug 1323100) Backed out changeset 54acf4ef8e84 (bug 1323100) Backed out changeset 88d17bcd8205 (bug 1323100) Backed out changeset 0c466e5e8933 (bug 1323100) --- dom/gamepad/cocoa/CocoaGamepad.cpp | 5 +- dom/gamepad/windows/WindowsGamepad.cpp | 2 +- dom/indexedDB/ActorsParent.cpp | 30 +++++-- dom/media/FileBlockCache.cpp | 7 +- dom/media/GraphDriver.cpp | 17 ++++ dom/media/MediaRecorder.cpp | 11 +++ .../android/AndroidMediaResourceServer.cpp | 2 +- dom/media/gtest/TestMP4Reader.cpp | 2 +- .../webaudio/blink/HRTFDatabaseLoader.cpp | 2 - dom/plugins/base/android/ANPAudio.cpp | 4 +- dom/storage/DOMStorageDBThread.cpp | 2 - .../gonk/GonkGPSGeolocationProvider.cpp | 2 +- gfx/layers/LayerScope.cpp | 2 +- hal/gonk/GonkHal.cpp | 2 +- image/DecodePool.cpp | 27 ++++-- image/test/gtest/TestDecodeToSurface.cpp | 3 +- ipc/chromium/src/base/thread.cc | 4 +- ipc/glue/BackgroundImpl.cpp | 6 ++ js/xpconnect/src/XPCJSContext.cpp | 1 - media/mtransport/nr_socket_prsock.cpp | 3 +- netwerk/base/BackgroundFileSaver.cpp | 2 +- netwerk/base/nsPACMan.cpp | 18 +++- netwerk/base/nsPACMan.h | 1 + netwerk/base/nsSocketTransportService2.cpp | 9 ++ netwerk/cache2/CacheIOThread.cpp | 2 - netwerk/dns/nsHostResolver.cpp | 10 +-- netwerk/sctp/datachannel/DataChannel.cpp | 5 +- netwerk/system/win32/nsNotifyAddrListener.cpp | 4 +- netwerk/test/TestFileInput2.cpp | 61 +++++++------ netwerk/wifi/nsWifiMonitor.cpp | 4 +- security/manager/ssl/CryptoTask.cpp | 6 +- security/manager/ssl/nsKeygenThread.cpp | 2 - .../manager/ssl/nsProtectedAuthThread.cpp | 2 - security/manager/ssl/nsSmartCardMonitor.cpp | 2 - startupcache/StartupCache.cpp | 2 - storage/mozStorageConnection.cpp | 7 +- .../test_service_init_background_thread.cpp | 2 +- .../filewatcher/NativeFileWatcherWin.cpp | 6 +- .../components/terminator/nsTerminator.cpp | 3 - .../url-classifier/tests/gtest/Common.cpp | 3 +- toolkit/crashreporter/nsExceptionHandler.cpp | 2 +- toolkit/identity/IdentityCryptoService.cpp | 5 +- toolkit/xre/EventTracer.cpp | 1 - toolkit/xre/nsUpdateDriver.cpp | 3 +- tools/profiler/public/GeckoProfiler.h | 8 -- tools/profiler/public/GeckoProfilerImpl.h | 20 ----- widget/windows/LSPAnnotator.cpp | 2 +- widget/windows/nsSound.cpp | 7 +- xpcom/build/MainThreadIOLogger.cpp | 1 - xpcom/glue/nsThreadUtils.cpp | 85 +++++++++++++++---- xpcom/glue/nsThreadUtils.h | 56 ++++++++---- xpcom/tests/gtest/TestPipes.cpp | 10 +-- .../tests/gtest/TestRacingServiceManager.cpp | 2 +- xpcom/tests/gtest/TestThreads.cpp | 11 +-- xpcom/tests/gtest/TestTimers.cpp | 2 +- xpcom/threads/BackgroundHangMonitor.cpp | 2 - xpcom/threads/HangMonitor.cpp | 2 - xpcom/threads/LazyIdleThread.cpp | 9 +- xpcom/threads/TimerThread.cpp | 3 +- xpcom/threads/nsIThreadManager.idl | 14 --- xpcom/threads/nsProcessCommon.cpp | 8 -- xpcom/threads/nsThread.cpp | 33 +------ xpcom/threads/nsThread.h | 4 +- xpcom/threads/nsThreadManager.cpp | 10 +-- xpcom/threads/nsThreadPool.cpp | 7 +- 65 files changed, 314 insertions(+), 278 deletions(-) diff --git a/dom/gamepad/cocoa/CocoaGamepad.cpp b/dom/gamepad/cocoa/CocoaGamepad.cpp index 0000d616e223..e7c986e22a60 100644 --- a/dom/gamepad/cocoa/CocoaGamepad.cpp +++ b/dom/gamepad/cocoa/CocoaGamepad.cpp @@ -541,9 +541,8 @@ DarwinGamepadService::StartupInternal() void DarwinGamepadService::Startup() { - Unused << NS_NewNamedThread("Gamepad", - getter_AddRefs(mMonitorThread), - new DarwinGamepadServiceStartupRunnable(this)); + Unused << NS_NewThread(getter_AddRefs(mMonitorThread), + new DarwinGamepadServiceStartupRunnable(this)); } void DarwinGamepadService::Shutdown() diff --git a/dom/gamepad/windows/WindowsGamepad.cpp b/dom/gamepad/windows/WindowsGamepad.cpp index 7c2819ed05df..5f60fd0b79d8 100644 --- a/dom/gamepad/windows/WindowsGamepad.cpp +++ b/dom/gamepad/windows/WindowsGamepad.cpp @@ -1065,7 +1065,7 @@ StartGamepadMonitoring() return; } sIsShutdown = false; - NS_NewNamedThread("Gamepad", getter_AddRefs(gMonitorThread)); + NS_NewThread(getter_AddRefs(gMonitorThread)); gMonitorThread->Dispatch(new StartWindowsGamepadServiceRunnable(), NS_DISPATCH_NORMAL); } diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp index 1f84a832a0f0..fc70257c2b81 100644 --- a/dom/indexedDB/ActorsParent.cpp +++ b/dom/indexedDB/ActorsParent.cpp @@ -5720,11 +5720,6 @@ public: return mSerialNumber; } - nsCString GetThreadName() const - { - return nsPrintfCString("IndexedDB #%lu", mSerialNumber); - } - private: ~ThreadRunnable() override; @@ -12576,10 +12571,7 @@ ConnectionPool::ScheduleTransaction(TransactionInfo* aTransactionInfo, RefPtr runnable = new ThreadRunnable(); nsCOMPtr newThread; - nsresult rv = - NS_NewNamedThread(runnable->GetThreadName(), - getter_AddRefs(newThread), runnable); - if (NS_SUCCEEDED(rv)) { + if (NS_SUCCEEDED(NS_NewThread(getter_AddRefs(newThread), runnable))) { MOZ_ASSERT(newThread); IDB_DEBUG_LOG(("ConnectionPool created thread %lu", @@ -13292,6 +13284,10 @@ nsresult ConnectionPool:: ThreadRunnable::Run() { +#ifdef MOZ_ENABLE_PROFILER_SPS + char stackTopGuess; +#endif // MOZ_ENABLE_PROFILER_SPS + MOZ_ASSERT(!IsOnBackgroundThread()); MOZ_ASSERT(mContinueRunning); @@ -13302,6 +13298,18 @@ ThreadRunnable::Run() mFirstRun = false; + { + // Scope for the thread name. Both PR_SetCurrentThreadName() and + // profiler_register_thread() copy the string so we don't need to keep it. + const nsPrintfCString threadName("IndexedDB #%lu", mSerialNumber); + + PR_SetCurrentThreadName(threadName.get()); + +#ifdef MOZ_ENABLE_PROFILER_SPS + profiler_register_thread(threadName.get(), &stackTopGuess); +#endif // MOZ_ENABLE_PROFILER_SPS + } + { // Scope for the profiler label. PROFILER_LABEL("IndexedDB", @@ -13343,6 +13351,10 @@ ThreadRunnable::Run() } } +#ifdef MOZ_ENABLE_PROFILER_SPS + profiler_unregister_thread(); +#endif // MOZ_ENABLE_PROFILER_SPS + return NS_OK; } diff --git a/dom/media/FileBlockCache.cpp b/dom/media/FileBlockCache.cpp index 16a3a0043f39..d85e6cd016de 100644 --- a/dom/media/FileBlockCache.cpp +++ b/dom/media/FileBlockCache.cpp @@ -22,10 +22,9 @@ nsresult FileBlockCache::Open(PRFileDesc* aFD) } { MonitorAutoLock mon(mDataMonitor); - nsresult res = NS_NewNamedThread("FileBlockCache", - getter_AddRefs(mThread), - nullptr, - SharedThreadPool::kStackSize); + nsresult res = NS_NewThread(getter_AddRefs(mThread), + nullptr, + SharedThreadPool::kStackSize); mIsOpen = NS_SUCCEEDED(res); return res; } diff --git a/dom/media/GraphDriver.cpp b/dom/media/GraphDriver.cpp index ecb0acaecd49..33001cd332cc 100644 --- a/dom/media/GraphDriver.cpp +++ b/dom/media/GraphDriver.cpp @@ -39,6 +39,19 @@ namespace mozilla { StaticRefPtr AsyncCubebTask::sThreadPool; +struct AutoProfilerUnregisterThread +{ + // The empty ctor is used to silence a pre-4.8.0 GCC unused variable warning. + AutoProfilerUnregisterThread() + { + } + + ~AutoProfilerUnregisterThread() + { + profiler_unregister_thread(); + } +}; + GraphDriver::GraphDriver(MediaStreamGraphImpl* aGraphImpl) : mIterationStart(0), mIterationEnd(0), @@ -183,7 +196,9 @@ public: } NS_IMETHOD Run() override { + char aLocal; STREAM_LOG(LogLevel::Debug, ("Starting system thread")); + profiler_register_thread("MediaStreamGraph", &aLocal); LIFECYCLE_LOG("Starting a new system driver for graph %p\n", mDriver->mGraphImpl); @@ -301,6 +316,8 @@ SystemClockDriver::IsFallback() void ThreadedDriver::RunThread() { + AutoProfilerUnregisterThread autoUnregister; + bool stillProcessing = true; while (stillProcessing) { mIterationStart = IterationEnd(); diff --git a/dom/media/MediaRecorder.cpp b/dom/media/MediaRecorder.cpp index 4b4070257ccb..2deeb906d86b 100644 --- a/dom/media/MediaRecorder.cpp +++ b/dom/media/MediaRecorder.cpp @@ -283,6 +283,8 @@ class MediaRecorder::Session: public nsIObserver, } else { // Flush out remaining encoded data. mSession->Extract(true); + if (mSession->mIsRegisterProfiler) + profiler_unregister_thread(); if (NS_FAILED(NS_DispatchToMainThread( new DestroyRunnable(mSession)))) { MOZ_ASSERT(false, "NS_DispatchToMainThread DestroyRunnable failed"); @@ -417,6 +419,7 @@ public: , mTimeSlice(aTimeSlice) , mStopIssued(false) , mIsStartEventFired(false) + , mIsRegisterProfiler(false) , mNeedSessionEndTask(true) , mSelectedVideoTrackID(TRACK_NONE) { @@ -604,6 +607,12 @@ private: MOZ_ASSERT(NS_GetCurrentThread() == mReadThread); LOG(LogLevel::Debug, ("Session.Extract %p", this)); + if (!mIsRegisterProfiler) { + char aLocal; + profiler_register_thread("Media_Encoder", &aLocal); + mIsRegisterProfiler = true; + } + PROFILER_LABEL("MediaRecorder", "Session Extract", js::ProfileEntry::Category::OTHER); @@ -913,6 +922,8 @@ private: bool mStopIssued; // Indicate the session had fire start event. Encoding thread only. bool mIsStartEventFired; + // The register flag for "Media_Encoder" thread to profiler + bool mIsRegisterProfiler; // False if the InitEncoder called successfully, ensure the // ExtractRunnable/DestroyRunnable will end the session. // Main thread only. diff --git a/dom/media/android/AndroidMediaResourceServer.cpp b/dom/media/android/AndroidMediaResourceServer.cpp index f6ca13f5aa61..bd76a8c68c49 100644 --- a/dom/media/android/AndroidMediaResourceServer.cpp +++ b/dom/media/android/AndroidMediaResourceServer.cpp @@ -375,7 +375,7 @@ ResourceSocketListener::OnSocketAccepted(nsIServerSocket* aServ, if (NS_FAILED(rv)) return rv; nsCOMPtr thread; - rv = NS_NewNamedThread("ServeResource", getter_AddRefs(thread)); + rv = NS_NewThread(getter_AddRefs(thread)); if (NS_FAILED(rv)) return rv; nsCOMPtr event = new ServeResourceEvent(input.get(), output.get(), mServer); diff --git a/dom/media/gtest/TestMP4Reader.cpp b/dom/media/gtest/TestMP4Reader.cpp index 2cf72681585c..f08f7a40da3c 100644 --- a/dom/media/gtest/TestMP4Reader.cpp +++ b/dom/media/gtest/TestMP4Reader.cpp @@ -44,7 +44,7 @@ public: void Init() { nsCOMPtr thread; nsCOMPtr r = NewRunnableMethod(this, &TestBinding::ReadMetadata); - nsresult rv = NS_NewNamedThread("ReadMetadata", getter_AddRefs(thread), r); + nsresult rv = NS_NewThread(getter_AddRefs(thread), r); EXPECT_EQ(NS_OK, rv); thread->Shutdown(); } diff --git a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp index 41be2c2daa5d..090e1b2172af 100644 --- a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp +++ b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp @@ -28,7 +28,6 @@ #include "HRTFDatabaseLoader.h" #include "HRTFDatabase.h" -#include "GeckoProfiler.h" using namespace mozilla; @@ -152,7 +151,6 @@ void HRTFDatabaseLoader::MainThreadRelease() // Asynchronously load the database in this thread. static void databaseLoaderEntry(void* threadData) { - AutoProfilerRegister registerThread("HRTFDatabaseLdr"); PR_SetCurrentThreadName("HRTFDatabaseLdr"); HRTFDatabaseLoader* loader = reinterpret_cast(threadData); diff --git a/dom/plugins/base/android/ANPAudio.cpp b/dom/plugins/base/android/ANPAudio.cpp index dd4f0b29cdbe..bc47e8999e7a 100644 --- a/dom/plugins/base/android/ANPAudio.cpp +++ b/dom/plugins/base/android/ANPAudio.cpp @@ -122,6 +122,8 @@ public: NS_IMETHODIMP AudioRunnable::Run() { + PR_SetCurrentThreadName("Android Audio"); + JNIEnv* const jenv = mozilla::jni::GetEnvForThread(); mozilla::AutoLocalJNIFrame autoFrame(jenv, 2); @@ -319,7 +321,7 @@ anp_audio_start(ANPAudioTrack* s) RefPtr runnable = new AudioRunnable(s); nsCOMPtr thread; - NS_NewNamedThread("Android Audio", getter_AddRefs(thread), runnable); + NS_NewThread(getter_AddRefs(thread), runnable); } void diff --git a/dom/storage/DOMStorageDBThread.cpp b/dom/storage/DOMStorageDBThread.cpp index 7f9039484d82..d479fbb783f4 100644 --- a/dom/storage/DOMStorageDBThread.cpp +++ b/dom/storage/DOMStorageDBThread.cpp @@ -27,7 +27,6 @@ #include "mozilla/IOInterposer.h" #include "mozilla/Services.h" #include "mozilla/Tokenizer.h" -#include "GeckoProfiler.h" // How long we collect write oprerations // before they are flushed to the database @@ -338,7 +337,6 @@ DOMStorageDBThread::SetDefaultPriority() void DOMStorageDBThread::ThreadFunc(void* aArg) { - AutoProfilerRegister registerThread("localStorage DB"); PR_SetCurrentThreadName("localStorage DB"); mozilla::IOInterposer::RegisterCurrentThread(); diff --git a/dom/system/gonk/GonkGPSGeolocationProvider.cpp b/dom/system/gonk/GonkGPSGeolocationProvider.cpp index b3336f02af12..9ce6ce2e5a30 100644 --- a/dom/system/gonk/GonkGPSGeolocationProvider.cpp +++ b/dom/system/gonk/GonkGPSGeolocationProvider.cpp @@ -556,7 +556,7 @@ GonkGPSGeolocationProvider::Startup() } if (!mInitThread) { - nsresult rv = NS_NewNamedThread("Gonk GPS", getter_AddRefs(mInitThread)); + nsresult rv = NS_NewThread(getter_AddRefs(mInitThread)); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/gfx/layers/LayerScope.cpp b/gfx/layers/LayerScope.cpp index 55f87023d6d7..a3b7778ef40f 100644 --- a/gfx/layers/LayerScope.cpp +++ b/gfx/layers/LayerScope.cpp @@ -1569,7 +1569,7 @@ LayerScopeWebSocketManager::SocketHandler::CloseConnection() LayerScopeWebSocketManager::LayerScopeWebSocketManager() : mHandlerMutex("LayerScopeWebSocketManager::mHandlerMutex") { - NS_NewNamedThread("LayerScope", getter_AddRefs(mDebugSenderThread)); + NS_NewThread(getter_AddRefs(mDebugSenderThread)); mServerSocket = do_CreateInstance(NS_SERVERSOCKET_CONTRACTID); int port = gfxPrefs::LayerScopePort(); diff --git a/hal/gonk/GonkHal.cpp b/hal/gonk/GonkHal.cpp index e2ca40fbbac6..05d9295a225d 100644 --- a/hal/gonk/GonkHal.cpp +++ b/hal/gonk/GonkHal.cpp @@ -395,7 +395,7 @@ EnsureVibratorThreadInitialized() sVibratorRunnable = new VibratorRunnable(); nsCOMPtr thread; - NS_NewNamedThread("Gonk Vibrator", getter_AddRefs(thread), sVibratorRunnable); + NS_NewThread(getter_AddRefs(thread), sVibratorRunnable); } } // namespace diff --git a/image/DecodePool.cpp b/image/DecodePool.cpp index 8053b2f9d19d..9aa3d58229f4 100644 --- a/image/DecodePool.cpp +++ b/image/DecodePool.cpp @@ -60,6 +60,14 @@ public: , mShuttingDown(false) { } + /// Initialize the current thread for use by the decode pool. + void InitCurrentThread() + { + MOZ_ASSERT(!NS_IsMainThread()); + + mThreadNaming.SetThreadPoolName(NS_LITERAL_CSTRING("ImgDecoder")); + } + /// Shut down the provided decode pool thread. static void ShutdownThread(nsIThread* aThisThread) { @@ -127,12 +135,6 @@ public: } while (true); } - nsresult CreateThread(nsIThread** aThread, nsIRunnable* aInitialEvent) - { - return NS_NewNamedThread(mThreadNaming.GetNextThreadName("ImgDecoder"), - aThread, aInitialEvent); - } - private: ~DecodePoolImpl() { } @@ -164,11 +166,22 @@ public: NS_IMETHOD Run() override { +#ifdef MOZ_ENABLE_PROFILER_SPS + char stackBaseGuess; // Need to be the first variable of main loop function. +#endif // MOZ_ENABLE_PROFILER_SPS + MOZ_ASSERT(!NS_IsMainThread()); + mImpl->InitCurrentThread(); + nsCOMPtr thisThread; nsThreadManager::get().GetCurrentThread(getter_AddRefs(thisThread)); +#ifdef MOZ_ENABLE_PROFILER_SPS + // InitCurrentThread() has assigned the thread name. + profiler_register_thread(PR_GetThreadName(PR_GetCurrentThread()), &stackBaseGuess); +#endif // MOZ_ENABLE_PROFILER_SPS + do { Work work = mImpl->PopWork(); switch (work.mType) { @@ -259,7 +272,7 @@ DecodePool::DecodePool() for (uint32_t i = 0 ; i < limit ; ++i) { nsCOMPtr worker = new DecodePoolWorker(mImpl); nsCOMPtr thread; - nsresult rv = mImpl->CreateThread(getter_AddRefs(thread), worker); + nsresult rv = NS_NewThread(getter_AddRefs(thread), worker); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && thread, "Should successfully create image decoding threads"); mThreads.AppendElement(Move(thread)); diff --git a/image/test/gtest/TestDecodeToSurface.cpp b/image/test/gtest/TestDecodeToSurface.cpp index 278cdb1fdc89..bd52e75901c8 100644 --- a/image/test/gtest/TestDecodeToSurface.cpp +++ b/image/test/gtest/TestDecodeToSurface.cpp @@ -69,8 +69,7 @@ RunDecodeToSurface(const ImageTestCase& aTestCase) ASSERT_TRUE(inputStream != nullptr); nsCOMPtr thread; - nsresult rv = - NS_NewNamedThread("DecodeToSurface", getter_AddRefs(thread), nullptr); + nsresult rv = NS_NewThread(getter_AddRefs(thread), nullptr); ASSERT_TRUE(NS_SUCCEEDED(rv)); // We run the DecodeToSurface tests off-main-thread to ensure that diff --git a/ipc/chromium/src/base/thread.cc b/ipc/chromium/src/base/thread.cc index 05463aecac18..feec3aedf797 100644 --- a/ipc/chromium/src/base/thread.cc +++ b/ipc/chromium/src/base/thread.cc @@ -153,7 +153,8 @@ void Thread::StopSoon() { } void Thread::ThreadMain() { - mozilla::AutoProfilerRegister registerThread(name_.c_str()); + char aLocal; + profiler_register_thread(name_.c_str(), &aLocal); mozilla::IOInterposer::RegisterCurrentThread(); // The message loop for this thread. @@ -185,6 +186,7 @@ void Thread::ThreadMain() { DCHECK(GetThreadWasQuitProperly()); mozilla::IOInterposer::UnregisterCurrentThread(); + profiler_unregister_thread(); #ifdef MOZ_TASK_TRACER mozilla::tasktracer::FreeTraceInfo(); diff --git a/ipc/glue/BackgroundImpl.cpp b/ipc/glue/BackgroundImpl.cpp index 86b619f8f2f0..2f8e073f8397 100644 --- a/ipc/glue/BackgroundImpl.cpp +++ b/ipc/glue/BackgroundImpl.cpp @@ -1344,6 +1344,8 @@ ParentImpl::RequestMessageLoopRunnable::Run() AssertIsInMainProcess(); MOZ_ASSERT(mTargetThread); + char stackBaseGuess; + if (NS_IsMainThread()) { MOZ_ASSERT(mMessageLoop); @@ -1373,6 +1375,8 @@ ParentImpl::RequestMessageLoopRunnable::Run() return NS_OK; } + profiler_register_thread("IPDL Background", &stackBaseGuess); + #ifdef DEBUG { bool correctThread; @@ -1410,6 +1414,8 @@ ParentImpl::ShutdownBackgroundThreadRunnable::Run() // sBackgroundPRThread and we should not modify it here. sBackgroundPRThread.compareExchange(PR_GetCurrentThread(), nullptr); + profiler_unregister_thread(); + return NS_OK; } diff --git a/js/xpconnect/src/XPCJSContext.cpp b/js/xpconnect/src/XPCJSContext.cpp index 0393ae9ef498..5b4d184ea2f8 100644 --- a/js/xpconnect/src/XPCJSContext.cpp +++ b/js/xpconnect/src/XPCJSContext.cpp @@ -1166,7 +1166,6 @@ AutoLockWatchdog::~AutoLockWatchdog() static void WatchdogMain(void* arg) { - mozilla::AutoProfilerRegister registerThread("JS Watchdog"); PR_SetCurrentThreadName("JS Watchdog"); Watchdog* self = static_cast(arg); diff --git a/media/mtransport/nr_socket_prsock.cpp b/media/mtransport/nr_socket_prsock.cpp index 1aab40f8b478..f22229df86f5 100644 --- a/media/mtransport/nr_socket_prsock.cpp +++ b/media/mtransport/nr_socket_prsock.cpp @@ -212,9 +212,10 @@ public: nsrefcnt count = ++mUseCount; if (count == 1) { // idle -> in-use - nsresult rv = NS_NewNamedThread(mName, getter_AddRefs(mThread)); + nsresult rv = NS_NewThread(getter_AddRefs(mThread)); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && mThread, "Should successfully create mtransport I/O thread"); + NS_SetThreadName(mThread, mName); r_log(LOG_GENERIC,LOG_DEBUG,"Created wrapped SingletonThread %p", mThread.get()); } diff --git a/netwerk/base/BackgroundFileSaver.cpp b/netwerk/base/BackgroundFileSaver.cpp index ee81113006b3..e4bc05826249 100644 --- a/netwerk/base/BackgroundFileSaver.cpp +++ b/netwerk/base/BackgroundFileSaver.cpp @@ -152,7 +152,7 @@ BackgroundFileSaver::Init() rv = NS_GetCurrentThread(getter_AddRefs(mControlThread)); NS_ENSURE_SUCCESS(rv, rv); - rv = NS_NewNamedThread("BgFileSaver", getter_AddRefs(mWorkerThread)); + rv = NS_NewThread(getter_AddRefs(mWorkerThread)); NS_ENSURE_SUCCESS(rv, rv); sThreadCount++; diff --git a/netwerk/base/nsPACMan.cpp b/netwerk/base/nsPACMan.cpp index 43c569d8b3fd..37d3e8b6bba2 100644 --- a/netwerk/base/nsPACMan.cpp +++ b/netwerk/base/nsPACMan.cpp @@ -742,15 +742,27 @@ nsPACMan::AsyncOnChannelRedirect(nsIChannel *oldChannel, nsIChannel *newChannel, return NS_OK; } +void +nsPACMan::NamePACThread() +{ + MOZ_ASSERT(!NS_IsMainThread(), "wrong thread"); + PR_SetCurrentThreadName("Proxy Resolution"); +} + nsresult nsPACMan::Init(nsISystemProxySettings *systemProxySettings) { mSystemProxySettings = systemProxySettings; - nsresult rv = - NS_NewNamedThread("ProxyResolution", getter_AddRefs(mPACThread)); + nsresult rv = NS_NewThread(getter_AddRefs(mPACThread), nullptr); + if (NS_FAILED(rv)) + return rv; - return rv; + // don't check return value as it is not a big deal for this to fail. + mPACThread->Dispatch(NewRunnableMethod(this, &nsPACMan::NamePACThread), + nsIEventTarget::DISPATCH_NORMAL); + + return NS_OK; } } // namespace net diff --git a/netwerk/base/nsPACMan.h b/netwerk/base/nsPACMan.h index df952ff9ee25..def0843cb80a 100644 --- a/netwerk/base/nsPACMan.h +++ b/netwerk/base/nsPACMan.h @@ -214,6 +214,7 @@ private: void PostProcessPendingQ(); void PostCancelPendingQ(nsresult); bool ProcessPending(); + void NamePACThread(); private: ProxyAutoConfig mPAC; diff --git a/netwerk/base/nsSocketTransportService2.cpp b/netwerk/base/nsSocketTransportService2.cpp index b47eee88e6c4..4705a6055d94 100644 --- a/netwerk/base/nsSocketTransportService2.cpp +++ b/netwerk/base/nsSocketTransportService2.cpp @@ -833,6 +833,11 @@ nsSocketTransportService::MarkTheLastElementOfPendingQueue() NS_IMETHODIMP nsSocketTransportService::Run() { +#ifdef MOZ_ENABLE_PROFILER_SPS + char stackBaseGuess; // Need to be the first variable of main loop function. + profiler_register_thread(PR_GetThreadName(PR_GetCurrentThread()), &stackBaseGuess); +#endif // MOZ_ENABLE_PROFILER_SPS + SOCKET_LOG(("STS thread init %d sockets\n", gMaxCount)); psm::InitializeSSLServerCertVerificationThreads(); @@ -1014,6 +1019,10 @@ nsSocketTransportService::Run() SOCKET_LOG(("STS thread exit\n")); +#ifdef MOZ_ENABLE_PROFILER_SPS + profiler_unregister_thread(); +#endif // MOZ_ENABLE_PROFILER_SPS + return NS_OK; } diff --git a/netwerk/cache2/CacheIOThread.cpp b/netwerk/cache2/CacheIOThread.cpp index be5092a6d09c..66742679c9ac 100644 --- a/netwerk/cache2/CacheIOThread.cpp +++ b/netwerk/cache2/CacheIOThread.cpp @@ -10,7 +10,6 @@ #include "nsPrintfCString.h" #include "nsThreadUtils.h" #include "mozilla/IOInterposer.h" -#include "GeckoProfiler.h" #ifdef XP_WIN #include @@ -438,7 +437,6 @@ already_AddRefed CacheIOThread::Target() // static void CacheIOThread::ThreadFunc(void* aClosure) { - AutoProfilerRegister registerThread("Cache2 I/O"); PR_SetCurrentThreadName("Cache2 I/O"); mozilla::IOInterposer::RegisterCurrentThread(); CacheIOThread* thread = static_cast(aClosure); diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index 8924ed7e4d10..f2e26cadd4eb 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -29,7 +29,6 @@ #include "nsURLHelper.h" #include "nsThreadUtils.h" #include "GetAddrInfo.h" -#include "GeckoProfiler.h" #include "mozilla/HashFunctions.h" #include "mozilla/TimeStamp.h" @@ -1436,15 +1435,10 @@ nsHostResolver::SizeOfIncludingThis(MallocSizeOf mallocSizeOf) const void nsHostResolver::ThreadFunc(void *arg) { - char stackTop; - LOG(("DNS lookup thread - starting execution.\n")); static nsThreadPoolNaming naming; - nsCString name = naming.GetNextThreadName("DNS Resolver"); - - PR_SetCurrentThreadName(name.BeginReading()); - profiler_register_thread(name.BeginReading(), &stackTop); + naming.SetThreadPoolName(NS_LITERAL_CSTRING("DNS Resolver")); #if defined(RES_RETRY_ON_FAILURE) nsResState rs; @@ -1515,8 +1509,6 @@ nsHostResolver::ThreadFunc(void *arg) resolver->mThreadCount--; NS_RELEASE(resolver); LOG(("DNS lookup thread - queue empty, thread finished.\n")); - - profiler_unregister_thread(); } nsresult diff --git a/netwerk/sctp/datachannel/DataChannel.cpp b/netwerk/sctp/datachannel/DataChannel.cpp index b5adef05ab66..98810061bb24 100644 --- a/netwerk/sctp/datachannel/DataChannel.cpp +++ b/netwerk/sctp/datachannel/DataChannel.cpp @@ -2326,9 +2326,8 @@ DataChannelConnection::SendBlob(uint16_t stream, nsIInputStream *aBlob) NS_ENSURE_TRUE(channel, 0); // Spawn a thread to send the data if (!mInternalIOThread) { - nsresult rv = NS_NewNamedThread("DataChannel IO", - getter_AddRefs(mInternalIOThread)); - if (NS_FAILED(rv)) { + nsresult res = NS_NewThread(getter_AddRefs(mInternalIOThread)); + if (NS_FAILED(res)) { return -1; } } diff --git a/netwerk/system/win32/nsNotifyAddrListener.cpp b/netwerk/system/win32/nsNotifyAddrListener.cpp index bebbf4d0efc9..5d1ec3a61fe1 100644 --- a/netwerk/system/win32/nsNotifyAddrListener.cpp +++ b/netwerk/system/win32/nsNotifyAddrListener.cpp @@ -323,6 +323,8 @@ nsNotifyAddrListener::nextCoalesceWaitTime() NS_IMETHODIMP nsNotifyAddrListener::Run() { + PR_SetCurrentThreadName("Link Monitor"); + mStartTime = TimeStamp::Now(); calculateNetworkId(); @@ -419,7 +421,7 @@ nsNotifyAddrListener::Init(void) mCheckEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); NS_ENSURE_TRUE(mCheckEvent, NS_ERROR_OUT_OF_MEMORY); - rv = NS_NewNamedThread("Link Monitor", getter_AddRefs(mThread), this); + rv = NS_NewThread(getter_AddRefs(mThread), this); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; diff --git a/netwerk/test/TestFileInput2.cpp b/netwerk/test/TestFileInput2.cpp index a23437891b9d..f51988010e20 100644 --- a/netwerk/test/TestFileInput2.cpp +++ b/netwerk/test/TestFileInput2.cpp @@ -315,7 +315,7 @@ NS_IMPL_ISUPPORTS(FileChannelWorker, nsIRunnable) //////////////////////////////////////////////////////////////////////////////// void -Test(CreateFun create, const char* name, uint32_t count, +Test(CreateFun create, uint32_t count, nsIFile* inDirSpec, nsIFile* outDirSpec, uint32_t bufSize) { nsresult rv; @@ -375,8 +375,7 @@ Test(CreateFun create, const char* name, uint32_t count, bufSize); if (NS_FAILED(rv)) goto done; - rv = NS_NewNamedThread(name, getter_AddRefs(thread), - worker, 0, PR_JOINABLE_THREAD); + rv = NS_NewThread(getter_AddRefs(thread), worker, 0, PR_JOINABLE_THREAD); if (NS_FAILED(rv)) goto done; bool inserted = threads.InsertObjectAt(thread, i); @@ -434,44 +433,42 @@ main(int argc, char* argv[]) if (NS_FAILED(rv)) return rv; CreateFun create = FileChannelWorker::Create; - const char* name = "FileChannelWorker"; Test(create, 1, inDirFile, outDirFile, 16 * 1024); #if 1 printf("FileChannelWorker *****************************\n"); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); #endif create = FileSpecWorker::Create; - name = "FileSpecWorker"; printf("FileSpecWorker ********************************\n"); #if 1 - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); + Test(create, 20, inDirFile, outDirFile, 16 * 1024); #endif #if 1 - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); - Test(create, name, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); + Test(create, 20, inDirFile, outDirFile, 4 * 1024); #endif } // this scopes the nsCOMPtrs // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM diff --git a/netwerk/wifi/nsWifiMonitor.cpp b/netwerk/wifi/nsWifiMonitor.cpp index 2c1885f2be78..4613a107dc61 100644 --- a/netwerk/wifi/nsWifiMonitor.cpp +++ b/netwerk/wifi/nsWifiMonitor.cpp @@ -84,7 +84,7 @@ NS_IMETHODIMP nsWifiMonitor::StartWatching(nsIWifiListener *aListener) } if (!mThread) { - rv = NS_NewNamedThread("Wifi Monitor", getter_AddRefs(mThread), this); + rv = NS_NewThread(getter_AddRefs(mThread), this); if (NS_FAILED(rv)) return rv; } @@ -155,6 +155,8 @@ NS_IMETHODIMP nsWifiMonitor::Run() { LOG(("@@@@@ wifi monitor run called\n")); + PR_SetCurrentThreadName("Wifi Monitor"); + nsresult rv = DoScan(); LOG(("@@@@@ wifi monitor run::doscan complete %x\n", rv)); diff --git a/security/manager/ssl/CryptoTask.cpp b/security/manager/ssl/CryptoTask.cpp index 2ffc1d93159a..71b8ac88d5b3 100644 --- a/security/manager/ssl/CryptoTask.cpp +++ b/security/manager/ssl/CryptoTask.cpp @@ -31,13 +31,13 @@ CryptoTask::Dispatch(const nsACString& taskThreadName) } // Can't add 'this' as the event to run, since mThread may not be set yet - nsresult rv = NS_NewNamedThread(taskThreadName, getter_AddRefs(mThread), - nullptr, - nsIThreadManager::DEFAULT_STACK_SIZE); + nsresult rv = NS_NewThread(getter_AddRefs(mThread), nullptr, + nsIThreadManager::DEFAULT_STACK_SIZE); if (NS_FAILED(rv)) { return rv; } + NS_SetThreadName(mThread, taskThreadName); // Note: event must not null out mThread! return mThread->Dispatch(this, NS_DISPATCH_NORMAL); } diff --git a/security/manager/ssl/nsKeygenThread.cpp b/security/manager/ssl/nsKeygenThread.cpp index 4ff0304e229a..b295c4f36895 100644 --- a/security/manager/ssl/nsKeygenThread.cpp +++ b/security/manager/ssl/nsKeygenThread.cpp @@ -12,7 +12,6 @@ #include "nsNSSShutDown.h" #include "PSMRunnable.h" #include "mozilla/DebugOnly.h" -#include "GeckoProfiler.h" using namespace mozilla; using namespace mozilla::psm; @@ -115,7 +114,6 @@ nsresult nsKeygenThread::ConsumeResult( static void nsKeygenThreadRunner(void *arg) { - AutoProfilerRegister registerThread("Keygen"); PR_SetCurrentThreadName("Keygen"); nsKeygenThread *self = static_cast(arg); self->Run(); diff --git a/security/manager/ssl/nsProtectedAuthThread.cpp b/security/manager/ssl/nsProtectedAuthThread.cpp index bb930188b874..ea511b24a63d 100644 --- a/security/manager/ssl/nsProtectedAuthThread.cpp +++ b/security/manager/ssl/nsProtectedAuthThread.cpp @@ -11,7 +11,6 @@ #include "nsReadableUtils.h" #include "nsPKCS11Slot.h" #include "nsProtectedAuthThread.h" -#include "GeckoProfiler.h" using namespace mozilla; using namespace mozilla::psm; @@ -20,7 +19,6 @@ NS_IMPL_ISUPPORTS(nsProtectedAuthThread, nsIProtectedAuthThread) static void nsProtectedAuthThreadRunner(void *arg) { - AutoProfilerRegister registerThread("Protected Auth"); PR_SetCurrentThreadName("Protected Auth"); nsProtectedAuthThread *self = static_cast(arg); diff --git a/security/manager/ssl/nsSmartCardMonitor.cpp b/security/manager/ssl/nsSmartCardMonitor.cpp index a5cb8610aef2..3423d4f5f5f1 100644 --- a/security/manager/ssl/nsSmartCardMonitor.cpp +++ b/security/manager/ssl/nsSmartCardMonitor.cpp @@ -10,7 +10,6 @@ #include "nsIObserverService.h" #include "nsServiceManagerUtils.h" #include "nsThreadUtils.h" -#include "GeckoProfiler.h" #include "nspr.h" #include "pk11func.h" @@ -391,7 +390,6 @@ const SECMODModule* SmartCardMonitoringThread::GetModule() // C-like calling sequence to glue into PR_CreateThread. void SmartCardMonitoringThread::LaunchExecute(void* arg) { - AutoProfilerRegister registerThread("SmartCard"); PR_SetCurrentThreadName("SmartCard"); ((SmartCardMonitoringThread*)arg)->Execute(); diff --git a/startupcache/StartupCache.cpp b/startupcache/StartupCache.cpp index f698187170a5..6d1dd7a3a3ff 100644 --- a/startupcache/StartupCache.cpp +++ b/startupcache/StartupCache.cpp @@ -36,7 +36,6 @@ #include "nsThreadUtils.h" #include "nsXULAppAPI.h" #include "nsIProtocolHandler.h" -#include "GeckoProfiler.h" #ifdef IS_BIG_ENDIAN #define SC_ENDIAN "big" @@ -504,7 +503,6 @@ StartupCache::WaitOnWriteThread() void StartupCache::ThreadedWrite(void *aClosure) { - AutoProfilerRegister registerThread("StartupCache"); PR_SetCurrentThreadName("StartupCache"); mozilla::IOInterposer::RegisterCurrentThread(); /* diff --git a/storage/mozStorageConnection.cpp b/storage/mozStorageConnection.cpp index 6129ac4442a1..2ad50fb51d21 100644 --- a/storage/mozStorageConnection.cpp +++ b/storage/mozStorageConnection.cpp @@ -589,13 +589,14 @@ Connection::getAsyncExecutionTarget() return nullptr; if (!mAsyncExecutionThread) { - static nsThreadPoolNaming naming; - nsresult rv = NS_NewNamedThread(naming.GetNextThreadName("mozStorage"), - getter_AddRefs(mAsyncExecutionThread)); + nsresult rv = ::NS_NewThread(getter_AddRefs(mAsyncExecutionThread)); if (NS_FAILED(rv)) { NS_WARNING("Failed to create async thread."); return nullptr; } + static nsThreadPoolNaming naming; + naming.SetThreadPoolName(NS_LITERAL_CSTRING("mozStorage"), + mAsyncExecutionThread); } #ifdef DEBUG diff --git a/storage/test/gtest/test_service_init_background_thread.cpp b/storage/test/gtest/test_service_init_background_thread.cpp index e811e249702b..022026cbaefd 100644 --- a/storage/test/gtest/test_service_init_background_thread.cpp +++ b/storage/test/gtest/test_service_init_background_thread.cpp @@ -46,7 +46,7 @@ TEST(storage_service_init_background_thread_DeathTest, Test) do_check_true(event); nsCOMPtr thread; - do_check_success(NS_NewNamedThread("StorageService", getter_AddRefs(thread))); + do_check_success(NS_NewThread(getter_AddRefs(thread))); do_check_success(thread->Dispatch(event, NS_DISPATCH_NORMAL)); diff --git a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp index 8e2ed8a7278e..8bb40bfd4d89 100644 --- a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp +++ b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp @@ -1253,8 +1253,7 @@ NativeFileWatcherService::Init() // Start the IO worker thread. mWorkerIORunnable = new NativeFileWatcherIOTask(completionPort); - nsresult rv = NS_NewNamedThread("FileWatcher IO", getter_AddRefs(mIOThread), - mWorkerIORunnable); + nsresult rv = NS_NewThread(getter_AddRefs(mIOThread), mWorkerIORunnable); if (NS_FAILED(rv)) { FILEWATCHERLOG( "NativeFileWatcherIOTask::Init - Unable to create and dispatch the worker thread (%x).", @@ -1262,6 +1261,9 @@ NativeFileWatcherService::Init() return rv; } + // Set the name for the worker thread. + NS_SetThreadName(mIOThread, "FileWatcher IO"); + mIOCompletionPort = completionPort.forget(); return NS_OK; diff --git a/toolkit/components/terminator/nsTerminator.cpp b/toolkit/components/terminator/nsTerminator.cpp index ff9b03132922..e3d958a8807f 100644 --- a/toolkit/components/terminator/nsTerminator.cpp +++ b/toolkit/components/terminator/nsTerminator.cpp @@ -32,7 +32,6 @@ #if defined(MOZ_CRASHREPORTER) #include "nsExceptionHandler.h" #endif -#include "GeckoProfiler.h" #if defined(XP_WIN) #include @@ -125,7 +124,6 @@ struct Options { void RunWatchdog(void* arg) { - AutoProfilerRegister registerThread("Shutdown Hang Terminator"); PR_SetCurrentThreadName("Shutdown Hang Terminator"); // Let's copy and deallocate options, that's one less leak to worry @@ -216,7 +214,6 @@ PRMonitor* gWriteReady = nullptr; void RunWriter(void* arg) { - AutoProfilerRegister registerThread("Shutdown Statistics Writer"); PR_SetCurrentThreadName("Shutdown Statistics Writer"); MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(arg); diff --git a/toolkit/components/url-classifier/tests/gtest/Common.cpp b/toolkit/components/url-classifier/tests/gtest/Common.cpp index b2c9bad8bc41..b5f024b38e41 100644 --- a/toolkit/components/url-classifier/tests/gtest/Common.cpp +++ b/toolkit/components/url-classifier/tests/gtest/Common.cpp @@ -14,8 +14,7 @@ template void RunTestInNewThread(Function&& aFunction) { nsCOMPtr r = NS_NewRunnableFunction(mozilla::Forward(aFunction)); nsCOMPtr testingThread; - nsresult rv = - NS_NewNamedThread("Testing Thread", getter_AddRefs(testingThread), r); + nsresult rv = NS_NewThread(getter_AddRefs(testingThread), r); ASSERT_EQ(rv, NS_OK); testingThread->Shutdown(); } diff --git a/toolkit/crashreporter/nsExceptionHandler.cpp b/toolkit/crashreporter/nsExceptionHandler.cpp index 5922b9b80c2d..9fd69f504830 100644 --- a/toolkit/crashreporter/nsExceptionHandler.cpp +++ b/toolkit/crashreporter/nsExceptionHandler.cpp @@ -3609,7 +3609,7 @@ InjectCrashReporterIntoProcess(DWORD processID, InjectorCrashCallback* cb) OOPInit(); if (!sInjectorThread) { - if (NS_FAILED(NS_NewNamedThread("CrashRep Inject", &sInjectorThread))) + if (NS_FAILED(NS_NewThread(&sInjectorThread))) return; } diff --git a/toolkit/identity/IdentityCryptoService.cpp b/toolkit/identity/IdentityCryptoService.cpp index 5ad3fd19c9d4..0aeaed2f3f94 100644 --- a/toolkit/identity/IdentityCryptoService.cpp +++ b/toolkit/identity/IdentityCryptoService.cpp @@ -205,8 +205,7 @@ IdentityCryptoService::GenerateKeyPair( nsCOMPtr r = new KeyGenRunnable(keyType, callback); nsCOMPtr thread; - nsresult rv = NS_NewNamedThread("GenerateKeyPair", getter_AddRefs(thread), - r); + nsresult rv = NS_NewThread(getter_AddRefs(thread), r); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -310,7 +309,7 @@ KeyPair::Sign(const nsACString & textToSign, callback); nsCOMPtr thread; - nsresult rv = NS_NewNamedThread("KeyPair Sign", getter_AddRefs(thread), r); + nsresult rv = NS_NewThread(getter_AddRefs(thread), r); return rv; } diff --git a/toolkit/xre/EventTracer.cpp b/toolkit/xre/EventTracer.cpp index 622334f43eda..cb0d88524db4 100644 --- a/toolkit/xre/EventTracer.cpp +++ b/toolkit/xre/EventTracer.cpp @@ -122,7 +122,6 @@ class EventLoopLagDispatcher : public Runnable */ void TracerThread(void *arg) { - AutoProfilerRegister registerThread("Event Tracer"); PR_SetCurrentThreadName("Event Tracer"); TracerStartClosure* threadArgs = static_cast(arg); diff --git a/toolkit/xre/nsUpdateDriver.cpp b/toolkit/xre/nsUpdateDriver.cpp index 8c1bb9bca843..ce60c652187a 100644 --- a/toolkit/xre/nsUpdateDriver.cpp +++ b/toolkit/xre/nsUpdateDriver.cpp @@ -1246,8 +1246,7 @@ nsUpdateProcessor::ProcessUpdate(nsIUpdate* aUpdate) MOZ_ASSERT(NS_IsMainThread(), "not main thread"); nsCOMPtr r = NewRunnableMethod(this, &nsUpdateProcessor::StartStagedUpdate); - return NS_NewNamedThread("Update Watcher", getter_AddRefs(mProcessWatcher), - r); + return NS_NewThread(getter_AddRefs(mProcessWatcher), r); } diff --git a/tools/profiler/public/GeckoProfiler.h b/tools/profiler/public/GeckoProfiler.h index 81452dd6563c..bef017d11558 100644 --- a/tools/profiler/public/GeckoProfiler.h +++ b/tools/profiler/public/GeckoProfiler.h @@ -248,14 +248,6 @@ static inline bool profiler_in_privacy_mode() { return false; } static inline void profiler_log(const char *str) {} static inline void profiler_log(const char *fmt, va_list args) {} -class AutoProfilerRegister final MOZ_STACK_CLASS -{ - AutoProfilerRegister(const char* aName) {} -private: - AutoProfilerRegister(const AutoProfilerRegister&) = delete; - AutoProfilerRegister& operator=(const AutoProfilerRegister&) = delete; -}; - #else #include "GeckoProfilerImpl.h" diff --git a/tools/profiler/public/GeckoProfilerImpl.h b/tools/profiler/public/GeckoProfilerImpl.h index 2522400fff62..a32096b94315 100644 --- a/tools/profiler/public/GeckoProfilerImpl.h +++ b/tools/profiler/public/GeckoProfilerImpl.h @@ -461,26 +461,6 @@ private: void* mHandle; }; -/** - * Convenience class to register and unregister a thread with the profiler. - * Needs to be the first object on the stack of the thread. - */ -class MOZ_STACK_CLASS AutoProfilerRegister final -{ -public: - explicit AutoProfilerRegister(const char* aName) - { - profiler_register_thread(aName, this); - } - ~AutoProfilerRegister() - { - profiler_unregister_thread(); - } -private: - AutoProfilerRegister(const AutoProfilerRegister&) = delete; - AutoProfilerRegister& operator=(const AutoProfilerRegister&) = delete; -}; - } // namespace mozilla inline PseudoStack* mozilla_get_pseudo_stack(void) diff --git a/widget/windows/LSPAnnotator.cpp b/widget/windows/LSPAnnotator.cpp index 5e8f465116e1..5b0c1d14b484 100644 --- a/widget/windows/LSPAnnotator.cpp +++ b/widget/windows/LSPAnnotator.cpp @@ -151,7 +151,7 @@ void LSPAnnotate() nsCOMPtr thread; nsCOMPtr runnable = do_QueryObject(new LSPAnnotationGatherer()); - NS_NewNamedThread("LSP Annotate", getter_AddRefs(thread), runnable); + NS_NewThread(getter_AddRefs(thread), runnable); } } // namespace crashreporter diff --git a/widget/windows/nsSound.cpp b/widget/windows/nsSound.cpp index a22e048df3ef..5635f8356b9d 100644 --- a/widget/windows/nsSound.cpp +++ b/widget/windows/nsSound.cpp @@ -241,9 +241,7 @@ NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias) return NS_OK; nsCOMPtr player = new nsSoundPlayer(this, aSoundAlias); NS_ENSURE_TRUE(player, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = - NS_NewNamedThread("PlaySystemSound", getter_AddRefs(mPlayerThread), - player); + nsresult rv = NS_NewThread(getter_AddRefs(mPlayerThread), player); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } @@ -301,8 +299,7 @@ NS_IMETHODIMP nsSound::PlayEventSound(uint32_t aEventId) nsCOMPtr player = new nsSoundPlayer(this, sound); NS_ENSURE_TRUE(player, NS_ERROR_OUT_OF_MEMORY); - nsresult rv = - NS_NewNamedThread("PlayEventSound", getter_AddRefs(mPlayerThread), player); + nsresult rv = NS_NewThread(getter_AddRefs(mPlayerThread), player); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } diff --git a/xpcom/build/MainThreadIOLogger.cpp b/xpcom/build/MainThreadIOLogger.cpp index 95e469899fbd..0ca942cb9f76 100644 --- a/xpcom/build/MainThreadIOLogger.cpp +++ b/xpcom/build/MainThreadIOLogger.cpp @@ -114,7 +114,6 @@ MainThreadIOLoggerImpl::Init() /* static */ void MainThreadIOLoggerImpl::sIOThreadFunc(void* aArg) { - AutoProfilerRegister registerThread("MainThreadIOLogger"); PR_SetCurrentThreadName("MainThreadIOLogger"); MainThreadIOLoggerImpl* obj = static_cast(aArg); obj->IOThreadFunc(); diff --git a/xpcom/glue/nsThreadUtils.cpp b/xpcom/glue/nsThreadUtils.cpp index d2f5c88bcb6f..994f71de7d25 100644 --- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -95,16 +95,13 @@ IncrementalRunnable::SetDeadline(TimeStamp aDeadline) //----------------------------------------------------------------------------- nsresult -NS_NewNamedThread(const nsACString& aName, - nsIThread** aResult, - nsIRunnable* aEvent, - uint32_t aStackSize) +NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) { nsCOMPtr thread; #ifdef MOZILLA_INTERNAL_API nsresult rv = - nsThreadManager::get().nsThreadManager::NewNamedThread(aName, aStackSize, - getter_AddRefs(thread)); + nsThreadManager::get().nsThreadManager::NewThread(0, aStackSize, + getter_AddRefs(thread)); #else nsresult rv; nsCOMPtr mgr = @@ -113,7 +110,7 @@ NS_NewNamedThread(const nsACString& aName, return rv; } - rv = mgr->NewNamedThread(aName, aStackSize, getter_AddRefs(thread)); + rv = mgr->NewThread(0, aStackSize, getter_AddRefs(thread)); #endif if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -131,12 +128,6 @@ NS_NewNamedThread(const nsACString& aName, return NS_OK; } -nsresult -NS_NewThread(nsIThread** aResult, nsIRunnable* aEvent, uint32_t aStackSize) -{ - return NS_NewNamedThread(NS_LITERAL_CSTRING(""), aResult, aEvent, aStackSize); -} - nsresult NS_GetCurrentThread(nsIThread** aResult) { @@ -390,6 +381,56 @@ NS_ProcessNextEvent(nsIThread* aThread, bool aMayWait) return NS_SUCCEEDED(aThread->ProcessNextEvent(aMayWait, &val)) && val; } +#ifndef XPCOM_GLUE_AVOID_NSPR + +namespace { + +class nsNameThreadRunnable final : public nsIRunnable +{ + ~nsNameThreadRunnable() {} + +public: + explicit nsNameThreadRunnable(const nsACString& aName) : mName(aName) {} + + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSIRUNNABLE + +protected: + const nsCString mName; +}; + +NS_IMPL_ISUPPORTS(nsNameThreadRunnable, nsIRunnable) + +NS_IMETHODIMP +nsNameThreadRunnable::Run() +{ + PR_SetCurrentThreadName(mName.BeginReading()); + return NS_OK; +} + +} // namespace + +void +NS_SetThreadName(nsIThread* aThread, const nsACString& aName) +{ + if (!aThread) { + return; + } + + aThread->Dispatch(new nsNameThreadRunnable(aName), + nsIEventTarget::DISPATCH_NORMAL); +} + +#else // !XPCOM_GLUE_AVOID_NSPR + +void +NS_SetThreadName(nsIThread* aThread, const nsACString& aName) +{ + // No NSPR, no love. +} + +#endif + #ifdef MOZILLA_INTERNAL_API nsIThread* NS_GetCurrentThread() @@ -399,13 +440,23 @@ NS_GetCurrentThread() #endif // nsThreadPoolNaming -nsCString -nsThreadPoolNaming::GetNextThreadName(const nsACString& aPoolName) +void +nsThreadPoolNaming::SetThreadPoolName(const nsACString& aPoolName, + nsIThread* aThread) { nsCString name(aPoolName); name.AppendLiteral(" #"); - name.AppendInt(++mCounter, 10); // The counter is declared as atomic - return name; + name.AppendInt(++mCounter, 10); // The counter is declared as volatile + + if (aThread) { + // Set on the target thread + NS_SetThreadName(aThread, name); + } else { + // Set on the current thread +#ifndef XPCOM_GLUE_AVOID_NSPR + PR_SetCurrentThreadName(name.BeginReading()); +#endif + } } // nsAutoLowPriorityIO diff --git a/xpcom/glue/nsThreadUtils.h b/xpcom/glue/nsThreadUtils.h index 82ed1294cdfc..309729a1e99a 100644 --- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -32,6 +32,24 @@ // These methods are alternatives to the methods on nsIThreadManager, provided // for convenience. +/** + * Set name of the target thread. This operation is asynchronous. + */ +extern void NS_SetThreadName(nsIThread* aThread, const nsACString& aName); + +/** + * Static length version of the above function checking length of the + * name at compile time. + */ +template +inline void +NS_SetThreadName(nsIThread* aThread, const char (&aName)[LEN]) +{ + static_assert(LEN <= 16, + "Thread name must be no more than 16 characters"); + NS_SetThreadName(aThread, nsDependentCString(aName)); +} + /** * Create a new thread, and optionally provide an initial event for the thread. * @@ -53,12 +71,6 @@ NS_NewThread(nsIThread** aResult, /** * Creates a named thread, otherwise the same as NS_NewThread */ -extern nsresult -NS_NewNamedThread(const nsACString& aName, - nsIThread** aResult, - nsIRunnable* aInitialEvent = nullptr, - uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE); - template inline nsresult NS_NewNamedThread(const char (&aName)[LEN], @@ -66,10 +78,21 @@ NS_NewNamedThread(const char (&aName)[LEN], nsIRunnable* aInitialEvent = nullptr, uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) { - static_assert(LEN <= 16, - "Thread name must be no more than 16 characters"); - return NS_NewNamedThread(nsDependentCString(aName, LEN - 1), - aResult, aInitialEvent, aStackSize); + // Hold a ref while dispatching the initial event to match NS_NewThread() + nsCOMPtr thread; + nsresult rv = NS_NewThread(getter_AddRefs(thread), nullptr, aStackSize); + if (NS_WARN_IF(NS_FAILED(rv))) { + return rv; + } + NS_SetThreadName(thread, aName); + if (aInitialEvent) { + rv = thread->Dispatch(aInitialEvent, NS_DISPATCH_NORMAL); + NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Initial event dispatch failed"); + } + + *aResult = nullptr; + thread.swap(*aResult); + return rv; } /** @@ -1003,15 +1026,12 @@ public: nsThreadPoolNaming() : mCounter(0) {} /** - * Returns a thread name as " #" and increments the counter. + * Creates and sets next thread name as " #" + * on the specified thread. If no thread is specified (aThread + * is null) then the name is synchronously set on the current thread. */ - nsCString GetNextThreadName(const nsACString& aPoolName); - - template - nsCString GetNextThreadName(const char (&aPoolName)[LEN]) - { - return GetNextThreadName(nsDependentCString(aPoolName, LEN - 1)); - } + void SetThreadPoolName(const nsACString& aPoolName, + nsIThread* aThread = nullptr); private: mozilla::Atomic mCounter; diff --git a/xpcom/tests/gtest/TestPipes.cpp b/xpcom/tests/gtest/TestPipes.cpp index 5bf31c94197e..87b923008258 100644 --- a/xpcom/tests/gtest/TestPipes.cpp +++ b/xpcom/tests/gtest/TestPipes.cpp @@ -107,7 +107,7 @@ TestPipe(nsIInputStream* in, nsIOutputStream* out) nsresult rv; nsCOMPtr thread; - rv = NS_NewNamedThread("TestPipe", getter_AddRefs(thread), receiver); + rv = NS_NewThread(getter_AddRefs(thread), receiver); if (NS_FAILED(rv)) return rv; uint32_t total = 0; @@ -225,8 +225,7 @@ TestShortWrites(nsIInputStream* in, nsIOutputStream* out) nsresult rv; nsCOMPtr thread; - rv = NS_NewNamedThread("TestShortWrites", getter_AddRefs(thread), - receiver); + rv = NS_NewThread(getter_AddRefs(thread), receiver); if (NS_FAILED(rv)) return rv; uint32_t total = 0; @@ -331,15 +330,14 @@ TEST(Pipes, ChainedPipes) if (pump == nullptr) return; nsCOMPtr thread; - rv = NS_NewNamedThread("ChainedPipePump", getter_AddRefs(thread), pump); + rv = NS_NewThread(getter_AddRefs(thread), pump); if (NS_FAILED(rv)) return; RefPtr receiver = new nsReceiver(in2); if (receiver == nullptr) return; nsCOMPtr receiverThread; - rv = NS_NewNamedThread("ChainedPipeRecv", getter_AddRefs(receiverThread), - receiver); + rv = NS_NewThread(getter_AddRefs(receiverThread), receiver); if (NS_FAILED(rv)) return; uint32_t total = 0; diff --git a/xpcom/tests/gtest/TestRacingServiceManager.cpp b/xpcom/tests/gtest/TestRacingServiceManager.cpp index 1309083ed853..b0638db02f48 100644 --- a/xpcom/tests/gtest/TestRacingServiceManager.cpp +++ b/xpcom/tests/gtest/TestRacingServiceManager.cpp @@ -255,7 +255,7 @@ TEST(RacingServiceManager, Test) // Run the classID test nsCOMPtr newThread; - rv = NS_NewNamedThread("RacingServMan", getter_AddRefs(newThread), runnable); + rv = NS_NewThread(getter_AddRefs(newThread), runnable); ASSERT_TRUE(NS_SUCCEEDED(rv)); { diff --git a/xpcom/tests/gtest/TestThreads.cpp b/xpcom/tests/gtest/TestThreads.cpp index 4d47f2649415..4f6055dce9b9 100644 --- a/xpcom/tests/gtest/TestThreads.cpp +++ b/xpcom/tests/gtest/TestThreads.cpp @@ -49,7 +49,7 @@ TEST(Threads, Main) EXPECT_TRUE(event); nsCOMPtr runner; - rv = NS_NewNamedThread("TestThreadsMain", getter_AddRefs(runner), event); + rv = NS_NewThread(getter_AddRefs(runner), event); EXPECT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr thread; @@ -112,8 +112,7 @@ TEST(Threads, Stress) for (k = 0; k < threads; k++) { nsCOMPtr t; - nsresult rv = NS_NewNamedThread("StressRunner", getter_AddRefs(t), - new nsStressRunner(k)); + nsresult rv = NS_NewThread(getter_AddRefs(t), new nsStressRunner(k)); EXPECT_TRUE(NS_SUCCEEDED(rv)); NS_ADDREF(array[k] = t); } @@ -170,8 +169,7 @@ public: { mozilla::MonitorAutoLock lock(*gBeginAsyncShutdownMonitor); - rv = NS_NewNamedThread("AsyncShutdownPr", getter_AddRefs(t), - new AsyncShutdownPreparer()); + rv = NS_NewThread(getter_AddRefs(t), new AsyncShutdownPreparer()); EXPECT_TRUE(NS_SUCCEEDED(rv)); lock.Wait(); @@ -223,8 +221,7 @@ TEST(Threads, AsyncShutdown) { mozilla::MonitorAutoLock lock(*gAsyncShutdownReadyMonitor); - rv = NS_NewNamedThread("AsyncShutdownWt", getter_AddRefs(t), - new AsyncShutdownWaiter()); + rv = NS_NewThread(getter_AddRefs(t), new AsyncShutdownWaiter()); EXPECT_TRUE(NS_SUCCEEDED(rv)); lock.Wait(); diff --git a/xpcom/tests/gtest/TestTimers.cpp b/xpcom/tests/gtest/TestTimers.cpp index 524e1e8b3f7b..fe7520ab1018 100644 --- a/xpcom/tests/gtest/TestTimers.cpp +++ b/xpcom/tests/gtest/TestTimers.cpp @@ -31,7 +31,7 @@ class AutoTestThread public: AutoTestThread() { nsCOMPtr newThread; - nsresult rv = NS_NewNamedThread("AutoTestThread", getter_AddRefs(newThread)); + nsresult rv = NS_NewThread(getter_AddRefs(newThread)); if (NS_FAILED(rv)) return; diff --git a/xpcom/threads/BackgroundHangMonitor.cpp b/xpcom/threads/BackgroundHangMonitor.cpp index cc16973752fa..ac65d9f37162 100644 --- a/xpcom/threads/BackgroundHangMonitor.cpp +++ b/xpcom/threads/BackgroundHangMonitor.cpp @@ -22,7 +22,6 @@ #include "nsIObserver.h" #include "mozilla/Services.h" #include "nsXULAppAPI.h" -#include "GeckoProfiler.h" #include @@ -55,7 +54,6 @@ private: // Background hang monitor thread function static void MonitorThread(void* aData) { - AutoProfilerRegister registerThread("BgHangMonitor"); PR_SetCurrentThreadName("BgHangManager"); /* We do not hold a reference to BackgroundHangManager here diff --git a/xpcom/threads/HangMonitor.cpp b/xpcom/threads/HangMonitor.cpp index ab402eb68f58..cde8052f33c4 100644 --- a/xpcom/threads/HangMonitor.cpp +++ b/xpcom/threads/HangMonitor.cpp @@ -21,7 +21,6 @@ #endif #include "nsThreadUtils.h" #include "nsXULAppAPI.h" -#include "GeckoProfiler.h" #ifdef MOZ_CRASHREPORTER #include "nsExceptionHandler.h" @@ -210,7 +209,6 @@ GetChromeHangReport(Telemetry::ProcessedStack& aStack, void ThreadMain(void*) { - AutoProfilerRegister registerThread("Hang Monitor"); PR_SetCurrentThreadName("Hang Monitor"); MonitorAutoLock lock(*gMonitor); diff --git a/xpcom/threads/LazyIdleThread.cpp b/xpcom/threads/LazyIdleThread.cpp index be3acfa61fc5..527cc681962f 100644 --- a/xpcom/threads/LazyIdleThread.cpp +++ b/xpcom/threads/LazyIdleThread.cpp @@ -169,7 +169,7 @@ LazyIdleThread::EnsureThread() return NS_ERROR_UNEXPECTED; } - rv = NS_NewNamedThread("Lazy Idle", getter_AddRefs(mThread), runnable); + rv = NS_NewThread(getter_AddRefs(mThread), runnable); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -180,6 +180,11 @@ LazyIdleThread::EnsureThread() void LazyIdleThread::InitThread() { + char aLocal; + profiler_register_thread(mName.get(), &aLocal); + + PR_SetCurrentThreadName(mName.get()); + // Happens on mThread but mThread may not be set yet... nsCOMPtr thread(do_QueryInterface(NS_GetCurrentThread())); @@ -206,6 +211,8 @@ LazyIdleThread::CleanupThread() MOZ_ASSERT(!mThreadIsShuttingDown, "Shouldn't be true ever!"); mThreadIsShuttingDown = true; } + + profiler_unregister_thread(); } void diff --git a/xpcom/threads/TimerThread.cpp b/xpcom/threads/TimerThread.cpp index da4bc6edba26..8536f0395ab7 100644 --- a/xpcom/threads/TimerThread.cpp +++ b/xpcom/threads/TimerThread.cpp @@ -323,8 +323,7 @@ TimerThread::Init() if (mInitInProgress.exchange(true) == false) { // We hold on to mThread to keep the thread alive. - nsresult rv = - NS_NewNamedThread("Timer Thread", getter_AddRefs(mThread), this); + nsresult rv = NS_NewThread(getter_AddRefs(mThread), this); if (NS_FAILED(rv)) { mThread = nullptr; } else { diff --git a/xpcom/threads/nsIThreadManager.idl b/xpcom/threads/nsIThreadManager.idl index fa0f037c2712..9b4fc126f9b3 100644 --- a/xpcom/threads/nsIThreadManager.idl +++ b/xpcom/threads/nsIThreadManager.idl @@ -35,20 +35,6 @@ interface nsIThreadManager : nsISupports */ nsIThread newThread(in unsigned long creationFlags, [optional] in unsigned long stackSize); - /** - * Create a new thread (a global, user PRThread) with the specified name. - * - * @param name - * The name of the thread. Passing an empty name is equivalent to - * calling newThread(0, stackSize), i.e. the thread will not be named. - * @param stackSize - * Number of bytes to reserve for the thread's stack. - * - * @returns - * The newly created nsIThread object. - */ - [noscript] nsIThread newNamedThread(in ACString name, [optional] in unsigned long stackSize); - /** * Get the nsIThread object (if any) corresponding to the given PRThread. * This method returns null if there is no corresponding nsIThread. diff --git a/xpcom/threads/nsProcessCommon.cpp b/xpcom/threads/nsProcessCommon.cpp index 37071b58c95f..709865a09d8b 100644 --- a/xpcom/threads/nsProcessCommon.cpp +++ b/xpcom/threads/nsProcessCommon.cpp @@ -25,7 +25,6 @@ #include "nsIObserverService.h" #include "nsXULAppAPI.h" #include "mozilla/Services.h" -#include "GeckoProfiler.h" #include @@ -236,13 +235,10 @@ assembleCmdLine(char* const* aArgv, wchar_t** aWideCmdLine, UINT aCodePage) void nsProcess::Monitor(void* aArg) { - char stackBaseGuess; - RefPtr process = dont_AddRef(static_cast(aArg)); if (!process->mBlocking) { PR_SetCurrentThreadName("RunProcess"); - profiler_register_thread("RunProcess", &stackBaseGuess); } #if defined(PROCESSMODEL_WINAPI) @@ -308,10 +304,6 @@ nsProcess::Monitor(void* aArg) } else { NS_DispatchToMainThread(NewRunnableMethod(process, &nsProcess::ProcessComplete)); } - - if (!process->mBlocking) { - profiler_unregister_thread(); - } } void diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp index 119e0c788471..6c0f898240ae 100644 --- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -38,7 +38,6 @@ #include "nsIIncrementalRunnable.h" #include "nsThreadSyncDispatch.h" #include "LeakRefPtr.h" -#include "GeckoProfiler.h" #ifdef MOZ_CRASHREPORTER #include "nsServiceManagerUtils.h" @@ -433,34 +432,15 @@ SetupCurrentThreadForChaosMode() } } -namespace { - -struct ThreadInitData { - nsThread* thread; - const nsACString& name; -}; - -} - /*static*/ void nsThread::ThreadFunc(void* aArg) { using mozilla::ipc::BackgroundChild; - char stackTop; - - ThreadInitData* initData = static_cast(aArg); - nsThread* self = initData->thread; // strong reference - + nsThread* self = static_cast(aArg); // strong reference self->mThread = PR_GetCurrentThread(); SetupCurrentThreadForChaosMode(); - if (initData->name.Length() > 0) { - PR_SetCurrentThreadName(initData->name.BeginReading()); - - profiler_register_thread(initData->name.BeginReading(), &stackTop); - } - // Inform the ThreadManager nsThreadManager::get().RegisterCurrentThread(*self); @@ -475,9 +455,6 @@ nsThread::ThreadFunc(void* aArg) return; } } - - initData = nullptr; // clear before unblocking nsThread::Init - event->Run(); // unblocks nsThread::Init event = nullptr; @@ -524,8 +501,6 @@ nsThread::ThreadFunc(void* aArg) // Inform the threadmanager that this thread is going away nsThreadManager::get().UnregisterCurrentThread(*self); - profiler_unregister_thread(); - // Dispatch shutdown ACK NotNull context = WrapNotNull(self->mShutdownContext); @@ -653,7 +628,7 @@ nsThread::~nsThread() } nsresult -nsThread::Init(const nsACString& aName) +nsThread::Init() { // spawn thread and wait until it is fully setup RefPtr startup = new nsThreadStartupEvent(); @@ -664,10 +639,8 @@ nsThread::Init(const nsACString& aName) mShutdownRequired = true; - ThreadInitData initData = { this, aName }; - // ThreadFunc is responsible for setting mThread - if (!PR_CreateThread(PR_USER_THREAD, ThreadFunc, &initData, + if (!PR_CreateThread(PR_USER_THREAD, ThreadFunc, this, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, mStackSize)) { NS_RELEASE_THIS(); diff --git a/xpcom/threads/nsThread.h b/xpcom/threads/nsThread.h index fd8209b0b5c4..836123747aad 100644 --- a/xpcom/threads/nsThread.h +++ b/xpcom/threads/nsThread.h @@ -48,8 +48,8 @@ public: nsThread(MainThreadFlag aMainThread, uint32_t aStackSize); - // Initialize this as a wrapper for a new PRThread, and optionally give it a name. - nsresult Init(const nsACString& aName = NS_LITERAL_CSTRING("")); + // Initialize this as a wrapper for a new PRThread. + nsresult Init(); // Initialize this as a wrapper for the current PRThread. nsresult InitCurrentThread(); diff --git a/xpcom/threads/nsThreadManager.cpp b/xpcom/threads/nsThreadManager.cpp index 217e557a8274..d1eb84b8f84c 100644 --- a/xpcom/threads/nsThreadManager.cpp +++ b/xpcom/threads/nsThreadManager.cpp @@ -248,14 +248,6 @@ NS_IMETHODIMP nsThreadManager::NewThread(uint32_t aCreationFlags, uint32_t aStackSize, nsIThread** aResult) -{ - return NewNamedThread(NS_LITERAL_CSTRING(""), aStackSize, aResult); -} - -NS_IMETHODIMP -nsThreadManager::NewNamedThread(const nsACString& aName, - uint32_t aStackSize, - nsIThread** aResult) { // Note: can be called from arbitrary threads @@ -265,7 +257,7 @@ nsThreadManager::NewNamedThread(const nsACString& aName, } RefPtr thr = new nsThread(nsThread::NOT_MAIN_THREAD, aStackSize); - nsresult rv = thr->Init(aName); // Note: blocks until the new thread has been set up + nsresult rv = thr->Init(); // Note: blocks until the new thread has been set up if (NS_FAILED(rv)) { return rv; } diff --git a/xpcom/threads/nsThreadPool.cpp b/xpcom/threads/nsThreadPool.cpp index f1d849ed1a85..241fad39dcc2 100644 --- a/xpcom/threads/nsThreadPool.cpp +++ b/xpcom/threads/nsThreadPool.cpp @@ -104,9 +104,8 @@ nsThreadPool::PutEvent(already_AddRefed aEvent, uint32_t aFlags) } nsCOMPtr thread; - nsresult rv = NS_NewNamedThread(mThreadNaming.GetNextThreadName(mName), - getter_AddRefs(thread), nullptr, stackSize); - if (NS_WARN_IF(NS_FAILED(rv))) { + nsThreadManager::get().NewThread(0, stackSize, getter_AddRefs(thread)); + if (NS_WARN_IF(!thread)) { return NS_ERROR_UNEXPECTED; } @@ -153,6 +152,8 @@ nsThreadPool::ShutdownThread(nsIThread* aThread) NS_IMETHODIMP nsThreadPool::Run() { + mThreadNaming.SetThreadPoolName(mName); + LOG(("THRD-P(%p) enter %s\n", this, mName.BeginReading())); nsCOMPtr current; From 73503504639ab4ec8ae557d4f5b3014c6db5ea9d Mon Sep 17 00:00:00 2001 From: Tim Nguyen Date: Fri, 30 Dec 2016 03:11:52 +0100 Subject: [PATCH 144/229] Bug 1325213 - Fix lots of eslint errors in devtools/shared/. r=jryans MozReview-Commit-ID: 2XxhfV8ih0S --HG-- extra : rebase_source : 1d4c869401ed8b501565d0d8927728771597cc30 --- .eslintignore | 10 - devtools/shared/client/connection-manager.js | 22 +- devtools/shared/client/main.js | 1310 +++++++++-------- devtools/shared/discovery/discovery.js | 22 +- .../shared/discovery/tests/unit/.eslintrc.js | 6 + .../discovery/tests/unit/test_discovery.js | 1 - .../shared/performance/recording-common.js | 86 +- .../shared/performance/recording-utils.js | 7 +- devtools/shared/performance/test/.eslintrc.js | 6 + devtools/shared/performance/test/head.js | 5 +- .../test_perf-utils-allocations-to-samples.js | 14 +- devtools/shared/qrcode/index.js | 1 - .../shared/qrcode/tests/unit/.eslintrc.js | 6 + devtools/shared/security/auth.js | 10 +- devtools/shared/security/cert.js | 1 - devtools/shared/security/socket.js | 10 +- .../shared/security/tests/chrome/.eslintrc.js | 6 + .../chrome/test_websocket-transport.html | 8 +- .../shared/security/tests/unit/head_dbg.js | 56 +- .../security/tests/unit/test_oob_cert_auth.js | 12 +- .../shared/security/tests/unit/testactors.js | 34 +- devtools/shared/shims/event-emitter.js | 9 +- .../tests/browser/browser_async_storage.js | 2 +- devtools/shared/tests/unit/exposeLoader.js | 2 + devtools/shared/tests/unit/head_devtools.js | 36 +- devtools/shared/tests/unit/test_assert.js | 5 +- .../shared/tests/unit/test_async-utils.js | 16 +- .../tests/unit/test_console_filtering.js | 20 +- .../unit/test_defineLazyPrototypeGetter.js | 4 +- .../shared/tests/unit/test_executeSoon.js | 1 - devtools/shared/tests/unit/test_flatten.js | 2 + .../tests/unit/test_independent_loaders.js | 2 + devtools/shared/tests/unit/test_isSet.js | 2 + devtools/shared/tests/unit/test_require.js | 2 + .../shared/tests/unit/test_require_lazy.js | 5 +- .../shared/tests/unit/test_require_raw.js | 2 + .../shared/tests/unit/test_safeErrorString.js | 2 + devtools/shared/tests/unit/test_stack.js | 2 + devtools/shared/touch/simulator-content.js | 2 +- devtools/shared/touch/simulator-core.js | 18 +- 40 files changed, 968 insertions(+), 799 deletions(-) create mode 100644 devtools/shared/discovery/tests/unit/.eslintrc.js create mode 100644 devtools/shared/performance/test/.eslintrc.js create mode 100644 devtools/shared/qrcode/tests/unit/.eslintrc.js create mode 100644 devtools/shared/security/tests/chrome/.eslintrc.js diff --git a/.eslintignore b/.eslintignore index a676a160e1c7..c678180d573a 100644 --- a/.eslintignore +++ b/.eslintignore @@ -117,20 +117,10 @@ devtools/server/tests/browser/** devtools/server/tests/mochitest/** devtools/server/tests/unit/** devtools/shared/apps/** -devtools/shared/client/** -devtools/shared/discovery/** devtools/shared/gcli/** !devtools/shared/gcli/templater.js devtools/shared/heapsnapshot/** devtools/shared/layout/** -devtools/shared/performance/** -!devtools/shared/platform/** -devtools/shared/qrcode/** -devtools/shared/security/** -devtools/shared/shims/** -devtools/shared/tests/** -!devtools/shared/tests/unit/test_csslexer.js -devtools/shared/touch/** devtools/shared/transport/** !devtools/shared/transport/transport.js !devtools/shared/transport/websocket-transport.js diff --git a/devtools/shared/client/connection-manager.js b/devtools/shared/client/connection-manager.js index ef242db85302..6b6a1e5e85c9 100644 --- a/devtools/shared/client/connection-manager.js +++ b/devtools/shared/client/connection-manager.js @@ -6,9 +6,8 @@ "use strict"; -const {Cc, Ci, Cu, Cr} = require("chrome"); +const {Cc, Ci, Cr} = require("chrome"); const EventEmitter = require("devtools/shared/event-emitter"); -const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/main"); const Services = require("Services"); @@ -70,8 +69,10 @@ const REMOTE_TIMEOUT = "devtools.debugger.remote-timeout"; * . Connection.Events.CONNECTING Trying to connect to host:port * . Connection.Events.CONNECTED Connection is successful * . Connection.Events.DISCONNECTING Trying to disconnect from server - * . Connection.Events.DISCONNECTED Disconnected (at client request, or because of a timeout or connection error) - * . Connection.Events.STATUS_CHANGED The connection status (connection.status) has changed + * . Connection.Events.DISCONNECTED Disconnected (at client request, + * or because of a timeout or connection error) + * . Connection.Events.STATUS_CHANGED The connection status (connection.status) + * has changed * . Connection.Events.TIMEOUT Connection timeout * . Connection.Events.HOST_CHANGED Host has changed * . Connection.Events.PORT_CHANGED Port has changed @@ -168,8 +169,9 @@ Connection.prototype = { }, set host(value) { - if (this._host && this._host == value) + if (this._host && this._host == value) { return; + } this._host = value; this.emit(Connection.Events.HOST_CHANGED); }, @@ -179,8 +181,9 @@ Connection.prototype = { }, set port(value) { - if (this._port && this._port == value) + if (this._port && this._port == value) { return; + } this._port = value; this.emit(Connection.Events.PORT_CHANGED); }, @@ -334,8 +337,9 @@ Connection.prototype = { }, _setStatus: function (value) { - if (this._status && this._status == value) + if (this._status && this._status == value) { return; + } this._status = value; this.emit(value); this.emit(Connection.Events.STATUS_CHANGED, value); @@ -357,7 +361,9 @@ Connection.prototype = { this.log("disconnected (unexpected)"); break; case Connection.Status.CONNECTING: - this.log("connection error. Possible causes: USB port not connected, port not forwarded (adb forward), wrong host or port, remote debugging not enabled on the device."); + this.log("connection error. Possible causes: USB port not connected, port not " + + "forwarded (adb forward), wrong host or port, remote debugging not " + + "enabled on the device."); break; default: this.log("disconnected"); diff --git a/devtools/shared/client/main.js b/devtools/shared/client/main.js index 408c0b277edc..b1e3295aff64 100644 --- a/devtools/shared/client/main.js +++ b/devtools/shared/client/main.js @@ -7,7 +7,6 @@ "use strict"; const { Ci, Cu } = require("chrome"); -const Services = require("Services"); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const { getStack, callFunctionWithAsyncStack } = require("devtools/shared/platform/stack"); @@ -28,22 +27,22 @@ const noop = () => {}; * augmented with the necessary facilities by passing its prototype to this * function. * - * @param aProto object + * @param proto object * The prototype object that will be modified. */ -function eventSource(aProto) { +function eventSource(proto) { /** * Add a listener to the event source for a given event. * - * @param aName string + * @param name string * The event to listen for. - * @param aListener function + * @param listener function * Called when the event is fired. If the same listener * is added more than once, it will be called once per * addListener call. */ - aProto.addListener = function (aName, aListener) { - if (typeof aListener != "function") { + proto.addListener = function (name, listener) { + if (typeof listener != "function") { throw TypeError("Listeners must be functions."); } @@ -51,47 +50,46 @@ function eventSource(aProto) { this._listeners = {}; } - this._getListeners(aName).push(aListener); + this._getListeners(name).push(listener); }; /** * Add a listener to the event source for a given event. The * listener will be removed after it is called for the first time. * - * @param aName string + * @param name string * The event to listen for. - * @param aListener function + * @param listener function * Called when the event is fired. */ - aProto.addOneTimeListener = function (aName, aListener) { + proto.addOneTimeListener = function (name, listener) { let l = (...args) => { - this.removeListener(aName, l); - aListener.apply(null, args); + this.removeListener(name, l); + listener.apply(null, args); }; - this.addListener(aName, l); + this.addListener(name, l); }; /** * Remove a listener from the event source previously added with * addListener(). * - * @param aName string + * @param name string * The event name used during addListener to add the listener. - * @param aListener function + * @param listener function * The callback to remove. If addListener was called multiple * times, all instances will be removed. */ - aProto.removeListener = function (aName, aListener) { - if (!this._listeners || (aListener && !this._listeners[aName])) { + proto.removeListener = function (name, listener) { + if (!this._listeners || (listener && !this._listeners[name])) { return; } - if (!aListener) { - this._listeners[aName] = []; - } - else { - this._listeners[aName] = - this._listeners[aName].filter(function (l) { return l != aListener; }); + if (!listener) { + this._listeners[name] = []; + } else { + this._listeners[name] = + this._listeners[name].filter(l => l != listener); } }; @@ -99,27 +97,27 @@ function eventSource(aProto) { * Returns the listeners for the specified event name. If none are defined it * initializes an empty list and returns that. * - * @param aName string + * @param name string * The event name. */ - aProto._getListeners = function (aName) { - if (aName in this._listeners) { - return this._listeners[aName]; + proto._getListeners = function (name) { + if (name in this._listeners) { + return this._listeners[name]; } - this._listeners[aName] = []; - return this._listeners[aName]; + this._listeners[name] = []; + return this._listeners[name]; }; /** * Notify listeners of an event. * - * @param aName string + * @param name string * The event to fire. * @param arguments * All arguments will be passed along to the listeners, * including the name argument. */ - aProto.emit = function () { + proto.emit = function () { if (!this._listeners) { return; } @@ -202,9 +200,8 @@ const UnsolicitedPauses = { * provides the means to communicate with the server and exchange the messages * required by the protocol in a traditional JavaScript API. */ -const DebuggerClient = exports.DebuggerClient = function (aTransport) -{ - this._transport = aTransport; +const DebuggerClient = exports.DebuggerClient = function (transport) { + this._transport = transport; this._transport.hooks = this; // Map actor ID to client instance for each actor type. @@ -224,18 +221,18 @@ const DebuggerClient = exports.DebuggerClient = function (aTransport) * the connection's root actor. */ this.mainRoot = null; - this.expectReply("root", (aPacket) => { - this.mainRoot = new RootClient(this, aPacket); - this.emit("connected", aPacket.applicationType, aPacket.traits); + this.expectReply("root", (packet) => { + this.mainRoot = new RootClient(this, packet); + this.emit("connected", packet.applicationType, packet.traits); }); }; /** * A declarative helper for defining methods that send requests to the server. * - * @param aPacketSkeleton + * @param packetSkeleton * The form of the packet to send. Can specify fields to be filled from - * the parameters by using the |args| function. + * the parameters by using the |arg| function. * @param before * The function to call before sending the packet. Is passed the packet, * and the return value is used as the new packet. The |this| context is @@ -249,21 +246,21 @@ const DebuggerClient = exports.DebuggerClient = function (aTransport) * The `Request` object that is a Promise object and resolves once * we receive the response. (See request method for more details) */ -DebuggerClient.requester = function (aPacketSkeleton, config = {}) { +DebuggerClient.requester = function (packetSkeleton, config = {}) { let { before, after } = config; return DevToolsUtils.makeInfallible(function (...args) { let outgoingPacket = { - to: aPacketSkeleton.to || this.actor + to: packetSkeleton.to || this.actor }; let maxPosition = -1; - for (let k of Object.keys(aPacketSkeleton)) { - if (aPacketSkeleton[k] instanceof DebuggerClient.Argument) { - let { position } = aPacketSkeleton[k]; - outgoingPacket[k] = aPacketSkeleton[k].getArgument(args); + for (let k of Object.keys(packetSkeleton)) { + if (packetSkeleton[k] instanceof DebuggerClient.Argument) { + let { position } = packetSkeleton[k]; + outgoingPacket[k] = packetSkeleton[k].getArgument(args); maxPosition = Math.max(position, maxPosition); } else { - outgoingPacket[k] = aPacketSkeleton[k]; + outgoingPacket[k] = packetSkeleton[k]; } } @@ -271,37 +268,37 @@ DebuggerClient.requester = function (aPacketSkeleton, config = {}) { outgoingPacket = before.call(this, outgoingPacket); } - return this.request(outgoingPacket, DevToolsUtils.makeInfallible((aResponse) => { + return this.request(outgoingPacket, DevToolsUtils.makeInfallible((response) => { if (after) { - let { from } = aResponse; - aResponse = after.call(this, aResponse); - if (!aResponse.from) { - aResponse.from = from; + let { from } = response; + response = after.call(this, response); + if (!response.from) { + response.from = from; } } // The callback is always the last parameter. let thisCallback = args[maxPosition + 1]; if (thisCallback) { - thisCallback(aResponse); + thisCallback(response); } }, "DebuggerClient.requester request callback")); }, "DebuggerClient.requester"); }; -function args(aPos) { - return new DebuggerClient.Argument(aPos); +function arg(pos) { + return new DebuggerClient.Argument(pos); } -DebuggerClient.Argument = function (aPosition) { - this.position = aPosition; +DebuggerClient.Argument = function (position) { + this.position = position; }; -DebuggerClient.Argument.prototype.getArgument = function (aParams) { - if (!(this.position in aParams)) { +DebuggerClient.Argument.prototype.getArgument = function (params) { + if (!(this.position in params)) { throw new Error("Bad index into params: " + this.position); } - return aParams[this.position]; + return params[this.position]; }; // Expose these to save callers the trouble of importing DebuggerSocket @@ -320,7 +317,7 @@ DebuggerClient.prototype = { /** * Connect to the server and start exchanging protocol messages. * - * @param aOnConnected function + * @param onConnected function * If specified, will be called when the greeting packet is * received from the debugging server. * @@ -330,7 +327,7 @@ DebuggerClient.prototype = { * element is the traits object (help figure out the features * and behaviors of the server we connect to. See RootActor). */ - connect: function (aOnConnected) { + connect: function (onConnected) { let deferred = promise.defer(); this.emit("connect"); @@ -338,12 +335,12 @@ DebuggerClient.prototype = { // so it's possible to track all instances. events.emit(DebuggerClient, "connect", this); - this.addOneTimeListener("connected", (aName, aApplicationType, aTraits) => { - this.traits = aTraits; - if (aOnConnected) { - aOnConnected(aApplicationType, aTraits); + this.addOneTimeListener("connected", (name, applicationType, traits) => { + this.traits = traits; + if (onConnected) { + onConnected(applicationType, traits); } - deferred.resolve([aApplicationType, aTraits]); + deferred.resolve([applicationType, traits]); }); this._transport.ready(); @@ -353,17 +350,17 @@ DebuggerClient.prototype = { /** * Shut down communication with the debugging server. * - * @param aOnClosed function + * @param onClosed function * If specified, will be called when the debugging connection * has been closed. This parameter is deprecated - please use * the returned Promise. * @return Promise * Resolves after the underlying transport is closed. */ - close: function (aOnClosed) { + close: function (onClosed) { let deferred = promise.defer(); - if (aOnClosed) { - deferred.promise.then(aOnClosed); + if (onClosed) { + deferred.promise.then(onClosed); } // Disable detach event notifications, because event handlers will be in a @@ -413,198 +410,206 @@ DebuggerClient.prototype = { * This function exists only to preserve DebuggerClient's interface; * new code should say 'client.mainRoot.listTabs()'. */ - listTabs: function (aOnResponse) { return this.mainRoot.listTabs(aOnResponse); }, + listTabs: function (onResponse) { + return this.mainRoot.listTabs(onResponse); + }, /* * This function exists only to preserve DebuggerClient's interface; * new code should say 'client.mainRoot.listAddons()'. */ - listAddons: function (aOnResponse) { return this.mainRoot.listAddons(aOnResponse); }, + listAddons: function (onResponse) { + return this.mainRoot.listAddons(onResponse); + }, - getTab: function (aFilter) { return this.mainRoot.getTab(aFilter); }, + getTab: function (filter) { + return this.mainRoot.getTab(filter); + }, /** * Attach to a tab actor. * - * @param string aTabActor + * @param string tabActor * The actor ID for the tab to attach. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a TabClient * (which will be undefined on error). */ - attachTab: function (aTabActor, aOnResponse = noop) { - if (this._clients.has(aTabActor)) { - let cachedTab = this._clients.get(aTabActor); + attachTab: function (tabActor, onResponse = noop) { + if (this._clients.has(tabActor)) { + let cachedTab = this._clients.get(tabActor); let cachedResponse = { cacheDisabled: cachedTab.cacheDisabled, javascriptEnabled: cachedTab.javascriptEnabled, traits: cachedTab.traits, }; - DevToolsUtils.executeSoon(() => aOnResponse(cachedResponse, cachedTab)); + DevToolsUtils.executeSoon(() => onResponse(cachedResponse, cachedTab)); return promise.resolve([cachedResponse, cachedTab]); } let packet = { - to: aTabActor, + to: tabActor, type: "attach" }; - return this.request(packet).then(aResponse => { + return this.request(packet).then(response => { let tabClient; - if (!aResponse.error) { - tabClient = new TabClient(this, aResponse); + if (!response.error) { + tabClient = new TabClient(this, response); this.registerClient(tabClient); } - aOnResponse(aResponse, tabClient); - return [aResponse, tabClient]; + onResponse(response, tabClient); + return [response, tabClient]; }); }, - attachWorker: function DC_attachWorker(aWorkerActor, aOnResponse = noop) { - let workerClient = this._clients.get(aWorkerActor); + attachWorker: function (workerActor, onResponse = noop) { + let workerClient = this._clients.get(workerActor); if (workerClient !== undefined) { let response = { from: workerClient.actor, type: "attached", url: workerClient.url }; - DevToolsUtils.executeSoon(() => aOnResponse(response, workerClient)); + DevToolsUtils.executeSoon(() => onResponse(response, workerClient)); return promise.resolve([response, workerClient]); } - return this.request({ to: aWorkerActor, type: "attach" }).then(aResponse => { - if (aResponse.error) { - aOnResponse(aResponse, null); - return [aResponse, null]; + return this.request({ to: workerActor, type: "attach" }).then(response => { + if (response.error) { + onResponse(response, null); + return [response, null]; } - let workerClient = new WorkerClient(this, aResponse); + workerClient = new WorkerClient(this, response); this.registerClient(workerClient); - aOnResponse(aResponse, workerClient); - return [aResponse, workerClient]; + onResponse(response, workerClient); + return [response, workerClient]; }); }, /** * Attach to an addon actor. * - * @param string aAddonActor + * @param string addonActor * The actor ID for the addon to attach. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a AddonClient * (which will be undefined on error). */ - attachAddon: function DC_attachAddon(aAddonActor, aOnResponse = noop) { + attachAddon: function (addonActor, onResponse = noop) { let packet = { - to: aAddonActor, + to: addonActor, type: "attach" }; - return this.request(packet).then(aResponse => { + return this.request(packet).then(response => { let addonClient; - if (!aResponse.error) { - addonClient = new AddonClient(this, aAddonActor); + if (!response.error) { + addonClient = new AddonClient(this, addonActor); this.registerClient(addonClient); this.activeAddon = addonClient; } - aOnResponse(aResponse, addonClient); - return [aResponse, addonClient]; + onResponse(response, addonClient); + return [response, addonClient]; }); }, /** * Attach to a Web Console actor. * - * @param string aConsoleActor + * @param string consoleActor * The ID for the console actor to attach to. - * @param array aListeners + * @param array listeners * The console listeners you want to start. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a WebConsoleClient * instance (which will be undefined on error). */ attachConsole: - function (aConsoleActor, aListeners, aOnResponse = noop) { + function (consoleActor, listeners, onResponse = noop) { let packet = { - to: aConsoleActor, + to: consoleActor, type: "startListeners", - listeners: aListeners, + listeners: listeners, }; - return this.request(packet).then(aResponse => { + return this.request(packet).then(response => { let consoleClient; - if (!aResponse.error) { - if (this._clients.has(aConsoleActor)) { - consoleClient = this._clients.get(aConsoleActor); + if (!response.error) { + if (this._clients.has(consoleActor)) { + consoleClient = this._clients.get(consoleActor); } else { - consoleClient = new WebConsoleClient(this, aResponse); + consoleClient = new WebConsoleClient(this, response); this.registerClient(consoleClient); } } - aOnResponse(aResponse, consoleClient); - return [aResponse, consoleClient]; + onResponse(response, consoleClient); + return [response, consoleClient]; }); }, /** * Attach to a global-scoped thread actor for chrome debugging. * - * @param string aThreadActor + * @param string threadActor * The actor ID for the thread to attach. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a ThreadClient * (which will be undefined on error). - * @param object aOptions + * @param object options * Configuration options. * - useSourceMaps: whether to use source maps or not. */ - attachThread: function (aThreadActor, aOnResponse = noop, aOptions = {}) { - if (this._clients.has(aThreadActor)) { - let client = this._clients.get(aThreadActor); - DevToolsUtils.executeSoon(() => aOnResponse({}, client)); + attachThread: function (threadActor, onResponse = noop, options = {}) { + if (this._clients.has(threadActor)) { + let client = this._clients.get(threadActor); + DevToolsUtils.executeSoon(() => onResponse({}, client)); return promise.resolve([{}, client]); } let packet = { - to: aThreadActor, + to: threadActor, type: "attach", - options: aOptions + options, }; - return this.request(packet).then(aResponse => { - if (!aResponse.error) { - var threadClient = new ThreadClient(this, aThreadActor); + return this.request(packet).then(response => { + let threadClient; + if (!response.error) { + threadClient = new ThreadClient(this, threadActor); this.registerClient(threadClient); } - aOnResponse(aResponse, threadClient); - return [aResponse, threadClient]; + onResponse(response, threadClient); + return [response, threadClient]; }); }, /** * Attach to a trace actor. * - * @param string aTraceActor + * @param string traceActor * The actor ID for the tracer to attach. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a TraceClient * (which will be undefined on error). */ - attachTracer: function (aTraceActor, aOnResponse = noop) { - if (this._clients.has(aTraceActor)) { - let client = this._clients.get(aTraceActor); - DevToolsUtils.executeSoon(() => aOnResponse({}, client)); + attachTracer: function (traceActor, onResponse = noop) { + if (this._clients.has(traceActor)) { + let client = this._clients.get(traceActor); + DevToolsUtils.executeSoon(() => onResponse({}, client)); return promise.resolve([{}, client]); } let packet = { - to: aTraceActor, + to: traceActor, type: "attach" }; - return this.request(packet).then(aResponse => { - if (!aResponse.error) { - var traceClient = new TraceClient(this, aTraceActor); + return this.request(packet).then(response => { + let traceClient; + if (!response.error) { + traceClient = new TraceClient(this, traceActor); this.registerClient(traceClient); } - aOnResponse(aResponse, traceClient); - return [aResponse, traceClient]; + onResponse(response, traceClient); + return [response, traceClient]; }); }, @@ -612,17 +617,17 @@ DebuggerClient.prototype = { * Fetch the ChromeActor for the main process or ChildProcessActor for a * a given child process ID. * - * @param number aId + * @param number id * The ID for the process to attach (returned by `listProcesses`). * Connected to the main process if omitted, or is 0. */ - getProcess: function (aId) { + getProcess: function (id) { let packet = { to: "root", type: "getProcess" }; - if (typeof (aId) == "number") { - packet.id = aId; + if (typeof (id) == "number") { + packet.id = id; } return this.request(packet); }, @@ -630,23 +635,23 @@ DebuggerClient.prototype = { /** * Release an object actor. * - * @param string aActor + * @param string actor * The actor ID to send the request to. - * @param aOnResponse function + * @param onResponse function * If specified, will be called with the response packet when * debugging server responds. */ release: DebuggerClient.requester({ - to: args(0), + to: arg(0), type: "release" }), /** * Send a request to the debugging server. * - * @param aRequest object + * @param packet object * A JSON packet to send to the debugging server. - * @param aOnResponse function + * @param onResponse function * If specified, will be called with the JSON response packet when * debugging server responds. * @return Request @@ -656,7 +661,7 @@ DebuggerClient.prototype = { * whenever a JSON or a Bulk response is received; and is rejected * if the response is an error. * Note: This return value can be ignored if you are using JSON alone, - * because the callback provided in |aOnResponse| will be bound to the + * because the callback provided in |onResponse| will be bound to the * "json-reply" event automatically. * * Events emitted: @@ -688,30 +693,30 @@ DebuggerClient.prototype = { * This object also emits "progress" events for each chunk * that is copied. See stream-utils.js. */ - request: function (aRequest, aOnResponse) { + request: function (packet, onResponse) { if (!this.mainRoot) { throw Error("Have not yet received a hello packet from the server."); } - let type = aRequest.type || ""; - if (!aRequest.to) { + let type = packet.type || ""; + if (!packet.to) { throw Error("'" + type + "' request packet has no destination."); } if (this._closed) { let msg = "'" + type + "' request packet to " + - "'" + aRequest.to + "' " + + "'" + packet.to + "' " + "can't be sent as the connection is closed."; let resp = { error: "connectionClosed", message: msg }; - if (aOnResponse) { - aOnResponse(resp); + if (onResponse) { + onResponse(resp); } return promise.reject(resp); } - let request = new Request(aRequest); + let request = new Request(packet); request.format = "json"; request.stack = getStack(); - if (aOnResponse) { - request.on("json-reply", aOnResponse); + if (onResponse) { + request.on("json-reply", onResponse); } this._sendOrQueueRequest(request); @@ -861,7 +866,7 @@ DebuggerClient.prototype = { if (request.format === "json") { this._transport.send(request.request); - return false; + return; } this._transport.startBulkSend(request.request).then((...args) => { @@ -899,28 +904,28 @@ DebuggerClient.prototype = { }, /** - * Arrange to hand the next reply from |aActor| to the handler bound to - * |aRequest|. + * Arrange to hand the next reply from |actor| to the handler bound to + * |request|. * * DebuggerClient.prototype.request / startBulkRequest usually takes care of * establishing the handler for a given request, but in rare cases (well, * greetings from new root actors, is the only case at the moment) we must be * prepared for a "reply" that doesn't correspond to any request we sent. */ - expectReply: function (aActor, aRequest) { - if (this._activeRequests.has(aActor)) { - throw Error("clashing handlers for next reply from " + uneval(aActor)); + expectReply: function (actor, request) { + if (this._activeRequests.has(actor)) { + throw Error("clashing handlers for next reply from " + actor); } // If a handler is passed directly (as it is with the handler for the root // actor greeting), create a dummy request to bind this to. - if (typeof aRequest === "function") { - let handler = aRequest; - aRequest = new Request(); - aRequest.on("json-reply", handler); + if (typeof request === "function") { + let handler = request; + request = new Request(); + request.on("json-reply", handler); } - this._activeRequests.set(aActor, aRequest); + this._activeRequests.set(actor, request); }, // Transport hooks. @@ -928,23 +933,23 @@ DebuggerClient.prototype = { /** * Called by DebuggerTransport to dispatch incoming packets as appropriate. * - * @param aPacket object + * @param packet object * The incoming packet. */ - onPacket: function (aPacket) { - if (!aPacket.from) { + onPacket: function (packet) { + if (!packet.from) { DevToolsUtils.reportException( "onPacket", new Error("Server did not specify an actor, dropping packet: " + - JSON.stringify(aPacket))); + JSON.stringify(packet))); return; } // If we have a registered Front for this actor, let it handle the packet // and skip all the rest of this unpleasantness. - let front = this.getActor(aPacket.from); + let front = this.getActor(packet.from); if (front) { - front.onPacket(aPacket); + front.onPacket(packet); return; } @@ -952,17 +957,17 @@ DebuggerClient.prototype = { // This is necessary because we might receive this event while the client is closing, // and the clients have already been removed by that point. if (this.mainRoot && - aPacket.from == this.mainRoot.actor && - aPacket.type == "forwardingCancelled") { - this.purgeRequests(aPacket.prefix); + packet.from == this.mainRoot.actor && + packet.type == "forwardingCancelled") { + this.purgeRequests(packet.prefix); return; } - if (this._clients.has(aPacket.from) && aPacket.type) { - let client = this._clients.get(aPacket.from); - let type = aPacket.type; + if (this._clients.has(packet.from) && packet.type) { + let client = this._clients.get(packet.from); + let type = packet.type; if (client.events.indexOf(type) != -1) { - client.emit(type, aPacket); + client.emit(type, packet); // we ignore the rest, as the client is expected to handle this packet. return; } @@ -972,24 +977,24 @@ DebuggerClient.prototype = { // See if we have a handler function waiting for a reply from this // actor. (Don't count unsolicited notifications or pauses as // replies.) - if (this._activeRequests.has(aPacket.from) && - !(aPacket.type in UnsolicitedNotifications) && - !(aPacket.type == ThreadStateTypes.paused && - aPacket.why.type in UnsolicitedPauses)) { - activeRequest = this._activeRequests.get(aPacket.from); - this._activeRequests.delete(aPacket.from); + if (this._activeRequests.has(packet.from) && + !(packet.type in UnsolicitedNotifications) && + !(packet.type == ThreadStateTypes.paused && + packet.why.type in UnsolicitedPauses)) { + activeRequest = this._activeRequests.get(packet.from); + this._activeRequests.delete(packet.from); } // If there is a subsequent request for the same actor, hand it off to the // transport. Delivery of packets on the other end is always async, even // in the local transport case. - this._attemptNextRequest(aPacket.from); + this._attemptNextRequest(packet.from); // Packets that indicate thread state changes get special treatment. - if (aPacket.type in ThreadStateTypes && - this._clients.has(aPacket.from) && - typeof this._clients.get(aPacket.from)._onThreadState == "function") { - this._clients.get(aPacket.from)._onThreadState(aPacket); + if (packet.type in ThreadStateTypes && + this._clients.has(packet.from) && + typeof this._clients.get(packet.from)._onThreadState == "function") { + this._clients.get(packet.from)._onThreadState(packet); } // TODO: Bug 1151156 - Remove once Gecko 40 is on b2g-stable. @@ -997,10 +1002,10 @@ DebuggerClient.prototype = { // On navigation the server resumes, so the client must resume as well. // We achieve that by generating a fake resumption packet that triggers // the client's thread state change listeners. - if (aPacket.type == UnsolicitedNotifications.tabNavigated && - this._clients.has(aPacket.from) && - this._clients.get(aPacket.from).thread) { - let thread = this._clients.get(aPacket.from).thread; + if (packet.type == UnsolicitedNotifications.tabNavigated && + this._clients.has(packet.from) && + this._clients.get(packet.from).thread) { + let thread = this._clients.get(packet.from).thread; let resumption = { from: thread._actor, type: "resumed" }; thread._onThreadState(resumption); } @@ -1008,12 +1013,12 @@ DebuggerClient.prototype = { // Only try to notify listeners on events, not responses to requests // that lack a packet type. - if (aPacket.type) { - this.emit(aPacket.type, aPacket); + if (packet.type) { + this.emit(packet.type, packet); } if (activeRequest) { - let emitReply = () => activeRequest.emit("json-reply", aPacket); + let emitReply = () => activeRequest.emit("json-reply", packet); if (activeRequest.stack) { callFunctionWithAsyncStack(emitReply, activeRequest.stack, "DevTools RDP"); @@ -1054,7 +1059,7 @@ DebuggerClient.prototype = { * that is copied. See stream-utils.js. */ onBulkPacket: function (packet) { - let { actor, type, length } = packet; + let { actor } = packet; if (!actor) { DevToolsUtils.reportException( @@ -1084,7 +1089,7 @@ DebuggerClient.prototype = { /** * Called by DebuggerTransport when the underlying stream is closed. * - * @param aStatus nsresult + * @param status nsresult * The status code that corresponds to the reason for closing * the stream. */ @@ -1280,7 +1285,9 @@ DebuggerClient.prototype = { poolFor: function (actorID) { for (let pool of this._pools) { - if (pool.has(actorID)) return pool; + if (pool.has(actorID)) { + return pool; + } } return null; }, @@ -1315,7 +1322,9 @@ Request.prototype = { events.emit(this, type, ...args); }, - get actor() { return this.request.to || this.request.actor; } + get actor() { + return this.request.to || this.request.actor; + } }; @@ -1324,76 +1333,80 @@ Request.prototype = { * is a front to the tab actor created in the server side, hiding the protocol * details in a traditional JavaScript API. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aForm object + * @param form object * The protocol form for this tab. */ -function TabClient(aClient, aForm) { - this.client = aClient; - this._actor = aForm.from; - this._threadActor = aForm.threadActor; - this.javascriptEnabled = aForm.javascriptEnabled; - this.cacheDisabled = aForm.cacheDisabled; +function TabClient(client, form) { + this.client = client; + this._actor = form.from; + this._threadActor = form.threadActor; + this.javascriptEnabled = form.javascriptEnabled; + this.cacheDisabled = form.cacheDisabled; this.thread = null; this.request = this.client.request; - this.traits = aForm.traits || {}; + this.traits = form.traits || {}; this.events = ["workerListChanged"]; } TabClient.prototype = { - get actor() { return this._actor; }, - get _transport() { return this.client._transport; }, + get actor() { + return this._actor; + }, + get _transport() { + return this.client._transport; + }, /** * Attach to a thread actor. * - * @param object aOptions + * @param object options * Configuration options. * - useSourceMaps: whether to use source maps or not. - * @param function aOnResponse + * @param function onResponse * Called with the response packet and a ThreadClient * (which will be undefined on error). */ - attachThread: function (aOptions = {}, aOnResponse = noop) { + attachThread: function (options = {}, onResponse = noop) { if (this.thread) { - DevToolsUtils.executeSoon(() => aOnResponse({}, this.thread)); + DevToolsUtils.executeSoon(() => onResponse({}, this.thread)); return promise.resolve([{}, this.thread]); } let packet = { to: this._threadActor, type: "attach", - options: aOptions + options, }; - return this.request(packet).then(aResponse => { - if (!aResponse.error) { + return this.request(packet).then(response => { + if (!response.error) { this.thread = new ThreadClient(this, this._threadActor); this.client.registerClient(this.thread); } - aOnResponse(aResponse, this.thread); - return [aResponse, this.thread]; + onResponse(response, this.thread); + return [response, this.thread]; }); }, /** * Detach the client from the tab actor. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - before: function (aPacket) { + before: function (packet) { if (this.thread) { this.thread.detach(); } - return aPacket; + return packet; }, - after: function (aResponse) { + after: function (response) { this.client.unregisterClient(this); - return aResponse; + return response; }, }), @@ -1416,7 +1429,7 @@ TabClient.prototype = { }, _reload: DebuggerClient.requester({ type: "reload", - options: args(0) + options: arg(0) }), /** @@ -1427,28 +1440,28 @@ TabClient.prototype = { */ navigateTo: DebuggerClient.requester({ type: "navigateTo", - url: args(0) + url: arg(0) }), /** * Reconfigure the tab actor. * - * @param object aOptions + * @param object options * A dictionary object of the new options to use in the tab actor. - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ reconfigure: DebuggerClient.requester({ type: "reconfigure", - options: args(0) + options: arg(0) }), listWorkers: DebuggerClient.requester({ type: "listWorkers" }), - attachWorker: function (aWorkerActor, aOnResponse) { - this.client.attachWorker(aWorkerActor, aOnResponse); + attachWorker: function (workerActor, onResponse) { + this.client.attachWorker(workerActor, onResponse); }, /** @@ -1461,17 +1474,17 @@ TabClient.prototype = { */ resolveLocation: DebuggerClient.requester({ type: "resolveLocation", - location: args(0) + location: arg(0) }), }; eventSource(TabClient.prototype); -function WorkerClient(aClient, aForm) { - this.client = aClient; - this._actor = aForm.from; +function WorkerClient(client, form) { + this.client = client; + this._actor = form.from; this._isClosed = false; - this._url = aForm.url; + this._url = form.url; this._onClose = this._onClose.bind(this); @@ -1502,23 +1515,23 @@ WorkerClient.prototype = { }, detach: DebuggerClient.requester({ type: "detach" }, { - after: function (aResponse) { + after: function (response) { if (this.thread) { this.client.unregisterClient(this.thread); } this.client.unregisterClient(this); - return aResponse; + return response; }, }), - attachThread: function (aOptions = {}, aOnResponse = noop) { + attachThread: function (options = {}, onResponse = noop) { if (this.thread) { let response = [{ type: "connected", threadActor: this.thread._actor, consoleActor: this.consoleActor, }, this.thread]; - DevToolsUtils.executeSoon(() => aOnResponse(response)); + DevToolsUtils.executeSoon(() => onResponse(response)); return response; } @@ -1526,31 +1539,31 @@ WorkerClient.prototype = { return this.request({ to: this._actor, type: "connect", - options: aOptions, - }).then(connectReponse => { - if (connectReponse.error) { - aOnResponse(connectReponse, null); + options, + }).then(connectResponse => { + if (connectResponse.error) { + onResponse(connectResponse, null); return [connectResponse, null]; } return this.request({ - to: connectReponse.threadActor, + to: connectResponse.threadActor, type: "attach", - options: aOptions + options, }).then(attachResponse => { if (attachResponse.error) { - aOnResponse(attachResponse, null); + onResponse(attachResponse, null); } - this.thread = new ThreadClient(this, connectReponse.threadActor); - this.consoleActor = connectReponse.consoleActor; + this.thread = new ThreadClient(this, connectResponse.threadActor); + this.consoleActor = connectResponse.consoleActor; this.client.registerClient(this.thread); - aOnResponse(connectReponse, this.thread); + onResponse(connectResponse, this.thread); return [connectResponse, this.thread]; }); }, error => { - aOnResponse(error, null); + onResponse(error, null); }); }, @@ -1573,32 +1586,36 @@ WorkerClient.prototype = { eventSource(WorkerClient.prototype); -function AddonClient(aClient, aActor) { - this._client = aClient; - this._actor = aActor; +function AddonClient(client, actor) { + this._client = client; + this._actor = actor; this.request = this._client.request; this.events = []; } AddonClient.prototype = { - get actor() { return this._actor; }, - get _transport() { return this._client._transport; }, + get actor() { + return this._actor; + }, + get _transport() { + return this._client._transport; + }, /** * Detach the client from the addon actor. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - after: function (aResponse) { + after: function (response) { if (this._client.activeAddon === this) { this._client.activeAddon = null; } this._client.unregisterClient(this); - return aResponse; + return response; }, }) }; @@ -1609,9 +1626,9 @@ AddonClient.prototype = { * for the initial connection; DebuggerClient's 'listTabs' and * 'listChildProcesses' methods forward to that root actor. * - * @param aClient object + * @param client object * The client connection to which this actor belongs. - * @param aGreeting string + * @param greeting string * The greeting packet from the root actor we're to represent. * * Properties of a RootClient instance: @@ -1623,11 +1640,11 @@ AddonClient.prototype = { * @property traits object * The traits object, as given in the root actor's greeting packet. */ -function RootClient(aClient, aGreeting) { - this._client = aClient; - this.actor = aGreeting.from; - this.applicationType = aGreeting.applicationType; - this.traits = aGreeting.traits; +function RootClient(client, greeting) { + this._client = client; + this.actor = greeting.from; + this.applicationType = greeting.applicationType; + this.traits = greeting.traits; } exports.RootClient = RootClient; @@ -1637,7 +1654,7 @@ RootClient.prototype = { /** * List the open tabs. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listTabs: DebuggerClient.requester({ type: "listTabs" }), @@ -1645,7 +1662,7 @@ RootClient.prototype = { /** * List the installed addons. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listAddons: DebuggerClient.requester({ type: "listAddons" }), @@ -1653,7 +1670,7 @@ RootClient.prototype = { /** * List the registered workers. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listWorkers: DebuggerClient.requester({ type: "listWorkers" }), @@ -1661,7 +1678,7 @@ RootClient.prototype = { /** * List the registered service workers. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listServiceWorkerRegistrations: DebuggerClient.requester({ @@ -1671,7 +1688,7 @@ RootClient.prototype = { /** * List the running processes. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ listProcesses: DebuggerClient.requester({ type: "listProcesses" }), @@ -1680,7 +1697,7 @@ RootClient.prototype = { * Fetch the TabActor for the currently selected tab, or for a specific * tab given as first parameter. * - * @param [optional] object aFilter + * @param [optional] object filter * A dictionary object with following optional attributes: * - outerWindowID: used to match tabs in parent process * - tabId: used to match tabs in child processes @@ -1688,19 +1705,19 @@ RootClient.prototype = { * If nothing is specified, returns the actor for the currently * selected tab. */ - getTab: function (aFilter) { + getTab: function (filter) { let packet = { to: this.actor, type: "getTab" }; - if (aFilter) { - if (typeof (aFilter.outerWindowID) == "number") { - packet.outerWindowID = aFilter.outerWindowID; - } else if (typeof (aFilter.tabId) == "number") { - packet.tabId = aFilter.tabId; - } else if ("tab" in aFilter) { - let browser = aFilter.tab.linkedBrowser; + if (filter) { + if (typeof (filter.outerWindowID) == "number") { + packet.outerWindowID = filter.outerWindowID; + } else if (typeof (filter.tabId) == "number") { + packet.tabId = filter.tabId; + } else if ("tab" in filter) { + let browser = filter.tab.linkedBrowser; if (browser.frameLoader.tabParent) { // Tabs in child process packet.tabId = browser.frameLoader.tabParent.tabId; @@ -1727,7 +1744,7 @@ RootClient.prototype = { /** * Description of protocol's actors and methods. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ protocolDescription: DebuggerClient.requester({ type: "protocolDescription" }), @@ -1736,8 +1753,12 @@ RootClient.prototype = { * Methods constructed by DebuggerClient.requester require these forwards * on their 'this'. */ - get _transport() { return this._client._transport; }, - get request() { return this._client.request; } + get _transport() { + return this._client._transport; + }, + get request() { + return this._client.request; + } }; /** @@ -1745,16 +1766,16 @@ RootClient.prototype = { * is a front to the thread actor created in the server side, hiding the * protocol details in a traditional JavaScript API. * - * @param aClient DebuggerClient|TabClient + * @param client DebuggerClient|TabClient * The parent of the thread (tab for tab-scoped debuggers, DebuggerClient * for chrome debuggers). - * @param aActor string + * @param actor string * The actor ID for this thread. */ -function ThreadClient(aClient, aActor) { - this._parent = aClient; - this.client = aClient instanceof DebuggerClient ? aClient : aClient.client; - this._actor = aActor; +function ThreadClient(client, actor) { + this._parent = client; + this.client = client instanceof DebuggerClient ? client : client.client; + this._actor = actor; this._frameCache = []; this._scriptCache = {}; this._pauseGrips = {}; @@ -1764,40 +1785,48 @@ function ThreadClient(aClient, aActor) { ThreadClient.prototype = { _state: "paused", - get state() { return this._state; }, - get paused() { return this._state === "paused"; }, + get state() { + return this._state; + }, + get paused() { + return this._state === "paused"; + }, _pauseOnExceptions: false, _ignoreCaughtExceptions: false, _pauseOnDOMEvents: null, _actor: null, - get actor() { return this._actor; }, + get actor() { + return this._actor; + }, - get _transport() { return this.client._transport; }, + get _transport() { + return this.client._transport; + }, - _assertPaused: function (aCommand) { + _assertPaused: function (command) { if (!this.paused) { - throw Error(aCommand + " command sent while not paused. Currently " + this._state); + throw Error(command + " command sent while not paused. Currently " + this._state); } }, /** - * Resume a paused thread. If the optional aLimit parameter is present, then + * Resume a paused thread. If the optional limit parameter is present, then * the thread will also pause when that limit is reached. * - * @param [optional] object aLimit + * @param [optional] object limit * An object with a type property set to the appropriate limit (next, * step, or finish) per the remote debugging protocol specification. * Use null to specify no limit. - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ _doResume: DebuggerClient.requester({ type: "resume", - resumeLimit: args(0) + resumeLimit: arg(0) }, { - before: function (aPacket) { + before: function (packet) { this._assertPaused("resume"); // Put the client in a tentative "resuming" state so we can prevent @@ -1806,150 +1835,152 @@ ThreadClient.prototype = { this._state = "resuming"; if (this._pauseOnExceptions) { - aPacket.pauseOnExceptions = this._pauseOnExceptions; + packet.pauseOnExceptions = this._pauseOnExceptions; } if (this._ignoreCaughtExceptions) { - aPacket.ignoreCaughtExceptions = this._ignoreCaughtExceptions; + packet.ignoreCaughtExceptions = this._ignoreCaughtExceptions; } if (this._pauseOnDOMEvents) { - aPacket.pauseOnDOMEvents = this._pauseOnDOMEvents; + packet.pauseOnDOMEvents = this._pauseOnDOMEvents; } - return aPacket; + return packet; }, - after: function (aResponse) { - if (aResponse.error && this._state == "resuming") { + after: function (response) { + if (response.error && this._state == "resuming") { // There was an error resuming, update the state to the new one // reported by the server, if given (only on wrongState), otherwise // reset back to the previous state. - if (aResponse.state) { - this._state = ThreadStateTypes[aResponse.state]; + if (response.state) { + this._state = ThreadStateTypes[response.state]; } else { this._state = this._previousState; } } delete this._previousState; - return aResponse; + return response; }, }), /** * Reconfigure the thread actor. * - * @param object aOptions + * @param object options * A dictionary object of the new options to use in the thread actor. - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ reconfigure: DebuggerClient.requester({ type: "reconfigure", - options: args(0) + options: arg(0) }), /** * Resume a paused thread. */ - resume: function (aOnResponse) { - return this._doResume(null, aOnResponse); + resume: function (onResponse) { + return this._doResume(null, onResponse); }, /** * Resume then pause without stepping. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - resumeThenPause: function (aOnResponse) { - return this._doResume({ type: "break" }, aOnResponse); + resumeThenPause: function (onResponse) { + return this._doResume({ type: "break" }, onResponse); }, /** * Step over a function call. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - stepOver: function (aOnResponse) { - return this._doResume({ type: "next" }, aOnResponse); + stepOver: function (onResponse) { + return this._doResume({ type: "next" }, onResponse); }, /** * Step into a function call. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - stepIn: function (aOnResponse) { - return this._doResume({ type: "step" }, aOnResponse); + stepIn: function (onResponse) { + return this._doResume({ type: "step" }, onResponse); }, /** * Step out of a function call. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - stepOut: function (aOnResponse) { - return this._doResume({ type: "finish" }, aOnResponse); + stepOut: function (onResponse) { + return this._doResume({ type: "finish" }, onResponse); }, /** * Immediately interrupt a running thread. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - interrupt: function (aOnResponse) { - return this._doInterrupt(null, aOnResponse); + interrupt: function (onResponse) { + return this._doInterrupt(null, onResponse); }, /** * Pause execution right before the next JavaScript bytecode is executed. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ - breakOnNext: function (aOnResponse) { - return this._doInterrupt("onNext", aOnResponse); + breakOnNext: function (onResponse) { + return this._doInterrupt("onNext", onResponse); }, /** * Interrupt a running thread. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ _doInterrupt: DebuggerClient.requester({ type: "interrupt", - when: args(0) + when: arg(0) }), /** * Enable or disable pausing when an exception is thrown. * - * @param boolean aFlag + * @param boolean pauseOnExceptions * Enables pausing if true, disables otherwise. - * @param function aOnResponse + * @param boolean ignoreCaughtExceptions + * Whether to ignore caught exceptions + * @param function onResponse * Called with the response packet. */ - pauseOnExceptions: function (aPauseOnExceptions, - aIgnoreCaughtExceptions, - aOnResponse = noop) { - this._pauseOnExceptions = aPauseOnExceptions; - this._ignoreCaughtExceptions = aIgnoreCaughtExceptions; + pauseOnExceptions: function (pauseOnExceptions, + ignoreCaughtExceptions, + onResponse = noop) { + this._pauseOnExceptions = pauseOnExceptions; + this._ignoreCaughtExceptions = ignoreCaughtExceptions; // Otherwise send the flag using a standard resume request. if (!this.paused) { - return this.interrupt(aResponse => { - if (aResponse.error) { + return this.interrupt(response => { + if (response.error) { // Can't continue if pausing failed. - aOnResponse(aResponse); - return aResponse; + onResponse(response); + return response; } - return this.resume(aOnResponse); + return this.resume(onResponse); }); } - aOnResponse(); + onResponse(); return promise.resolve(); }, @@ -1988,48 +2019,48 @@ ThreadClient.prototype = { * Send a clientEvaluate packet to the debuggee. Response * will be a resume packet. * - * @param string aFrame + * @param string frame * The actor ID of the frame where the evaluation should take place. - * @param string aExpression + * @param string expression * The expression that will be evaluated in the scope of the frame * above. - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ eval: DebuggerClient.requester({ type: "clientEvaluate", - frame: args(0), - expression: args(1) + frame: arg(0), + expression: arg(1) }, { - before: function (aPacket) { + before: function (packet) { this._assertPaused("eval"); // Put the client in a tentative "resuming" state so we can prevent // further requests that should only be sent in the paused state. this._state = "resuming"; - return aPacket; + return packet; }, - after: function (aResponse) { - if (aResponse.error) { + after: function (response) { + if (response.error) { // There was an error resuming, back to paused state. this._state = "paused"; } - return aResponse; + return response; }, }), /** * Detach from the thread actor. * - * @param function aOnResponse + * @param function onResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - after: function (aResponse) { + after: function (response) { this.client.unregisterClient(this); this._parent.thread = null; - return aResponse; + return response; }, }), @@ -2043,7 +2074,7 @@ ThreadClient.prototype = { */ releaseMany: DebuggerClient.requester({ type: "releaseMany", - actors: args(0), + actors: arg(0), }), /** @@ -2054,13 +2085,13 @@ ThreadClient.prototype = { */ threadGrips: DebuggerClient.requester({ type: "threadGrips", - actors: args(0) + actors: arg(0) }), /** * Return the event listeners defined on the page. * - * @param aOnResponse Function + * @param onResponse Function * Called with the thread's response. */ eventListeners: DebuggerClient.requester({ @@ -2070,7 +2101,7 @@ ThreadClient.prototype = { /** * Request the loaded sources for the current thread. * - * @param aOnResponse Function + * @param onResponse Function * Called with the thread's response. */ getSources: DebuggerClient.requester({ @@ -2091,19 +2122,19 @@ ThreadClient.prototype = { /** * Request frames from the callstack for the current thread. * - * @param aStart integer + * @param start integer * The number of the youngest stack frame to return (the youngest * frame is 0). - * @param aCount integer + * @param count integer * The maximum number of frames to return, or null to return all * frames. - * @param aOnResponse function + * @param onResponse function * Called with the thread's response. */ getFrames: DebuggerClient.requester({ type: "frames", - start: args(0), - count: args(1) + start: arg(0), + count: arg(1) }), /** @@ -2111,7 +2142,9 @@ ThreadClient.prototype = { * framescleared event to keep up to date on changes to this cache, * and can fill it using the fillFrames method. */ - get cachedFrames() { return this._frameCache; }, + get cachedFrames() { + return this._frameCache; + }, /** * true if there are more stack frames available on the server. @@ -2122,34 +2155,34 @@ ThreadClient.prototype = { }, /** - * Ensure that at least aTotal stack frames have been loaded in the + * Ensure that at least total stack frames have been loaded in the * ThreadClient's stack frame cache. A framesadded event will be * sent when the stack frame cache is updated. * - * @param aTotal number + * @param total number * The minimum number of stack frames to be included. - * @param aCallback function + * @param callback function * Optional callback function called when frames have been loaded * @returns true if a framesadded notification should be expected. */ - fillFrames: function (aTotal, aCallback = noop) { + fillFrames: function (total, callback = noop) { this._assertPaused("fillFrames"); - if (this._frameCache.length >= aTotal) { + if (this._frameCache.length >= total) { return false; } let numFrames = this._frameCache.length; - this.getFrames(numFrames, aTotal - numFrames, (aResponse) => { - if (aResponse.error) { - aCallback(aResponse); + this.getFrames(numFrames, total - numFrames, (response) => { + if (response.error) { + callback(response); return; } let threadGrips = DevToolsUtils.values(this._threadGrips); - for (let i in aResponse.frames) { - let frame = aResponse.frames[i]; + for (let i in response.frames) { + let frame = response.frames[i]; if (!frame.where.source) { // Older servers use urls instead, so we need to resolve // them to source actors @@ -2167,7 +2200,7 @@ ThreadClient.prototype = { // frames available. this.emit("framesadded"); - aCallback(aResponse); + callback(response); }); return true; @@ -2187,16 +2220,16 @@ ThreadClient.prototype = { /** * Return a ObjectClient object for the given object grip. * - * @param aGrip object + * @param grip object * A pause-lifetime object grip returned by the protocol. */ - pauseGrip: function (aGrip) { - if (aGrip.actor in this._pauseGrips) { - return this._pauseGrips[aGrip.actor]; + pauseGrip: function (grip) { + if (grip.actor in this._pauseGrips) { + return this._pauseGrips[grip.actor]; } - let client = new ObjectClient(this.client, aGrip); - this._pauseGrips[aGrip.actor] = client; + let client = new ObjectClient(this.client, grip); + this._pauseGrips[grip.actor] = client; return client; }, @@ -2204,19 +2237,19 @@ ThreadClient.prototype = { * Get or create a long string client, checking the grip client cache if it * already exists. * - * @param aGrip Object + * @param grip Object * The long string grip returned by the protocol. - * @param aGripCacheName String + * @param gripCacheName String * The property name of the grip client cache to check for existing * clients in. */ - _longString: function (aGrip, aGripCacheName) { - if (aGrip.actor in this[aGripCacheName]) { - return this[aGripCacheName][aGrip.actor]; + _longString: function (grip, gripCacheName) { + if (grip.actor in this[gripCacheName]) { + return this[gripCacheName][grip.actor]; } - let client = new LongStringClient(this.client, aGrip); - this[aGripCacheName][aGrip.actor] = client; + let client = new LongStringClient(this.client, grip); + this[gripCacheName][grip.actor] = client; return client; }, @@ -2224,35 +2257,35 @@ ThreadClient.prototype = { * Return an instance of LongStringClient for the given long string grip that * is scoped to the current pause. * - * @param aGrip Object + * @param grip Object * The long string grip returned by the protocol. */ - pauseLongString: function (aGrip) { - return this._longString(aGrip, "_pauseGrips"); + pauseLongString: function (grip) { + return this._longString(grip, "_pauseGrips"); }, /** * Return an instance of LongStringClient for the given long string grip that * is scoped to the thread lifetime. * - * @param aGrip Object + * @param grip Object * The long string grip returned by the protocol. */ - threadLongString: function (aGrip) { - return this._longString(aGrip, "_threadGrips"); + threadLongString: function (grip) { + return this._longString(grip, "_threadGrips"); }, /** * Clear and invalidate all the grip clients from the given cache. * - * @param aGripCacheName + * @param gripCacheName * The property name of the grip cache we want to clear. */ - _clearObjectClients: function (aGripCacheName) { - for (let id in this[aGripCacheName]) { - this[aGripCacheName][id].valid = false; + _clearObjectClients: function (gripCacheName) { + for (let id in this[gripCacheName]) { + this[gripCacheName][id].valid = false; } - this[aGripCacheName] = {}; + this[gripCacheName] = {}; }, /** @@ -2275,16 +2308,16 @@ ThreadClient.prototype = { * Handle thread state change by doing necessary cleanup and notifying all * registered listeners. */ - _onThreadState: function (aPacket) { - this._state = ThreadStateTypes[aPacket.type]; + _onThreadState: function (packet) { + this._state = ThreadStateTypes[packet.type]; // The debugger UI may not be initialized yet so we want to keep // the packet around so it knows what to pause state to display // when it's initialized - this._lastPausePacket = aPacket.type === "resumed" ? null : aPacket; + this._lastPausePacket = packet.type === "resumed" ? null : packet; this._clearFrames(); this._clearPauseGrips(); - aPacket.type === ThreadStateTypes.detached && this._clearThreadGrips(); - this.client._eventsEnabled && this.emit(aPacket.type, aPacket); + packet.type === ThreadStateTypes.detached && this._clearThreadGrips(); + this.client._eventsEnabled && this.emit(packet.type, packet); }, getLastPausePacket: function () { @@ -2294,32 +2327,33 @@ ThreadClient.prototype = { /** * Return an EnvironmentClient instance for the given environment actor form. */ - environment: function (aForm) { - return new EnvironmentClient(this.client, aForm); + environment: function (form) { + return new EnvironmentClient(this.client, form); }, /** * Return an instance of SourceClient for the given source actor form. */ - source: function (aForm) { - if (aForm.actor in this._threadGrips) { - return this._threadGrips[aForm.actor]; + source: function (form) { + if (form.actor in this._threadGrips) { + return this._threadGrips[form.actor]; } - return this._threadGrips[aForm.actor] = new SourceClient(this, aForm); + this._threadGrips[form.actor] = new SourceClient(this, form); + return this._threadGrips[form.actor]; }, /** * Request the prototype and own properties of mutlipleObjects. * - * @param aOnResponse function + * @param onResponse function * Called with the request's response. * @param actors [string] * List of actor ID of the queried objects. */ getPrototypesAndProperties: DebuggerClient.requester({ type: "prototypesAndProperties", - actors: args(0) + actors: arg(0) }), events: ["newSource"] @@ -2333,14 +2367,14 @@ eventSource(ThreadClient.prototype); * server side, hiding the protocol details in a traditional * JavaScript API. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aActor string + * @param actor string * The actor ID for this thread. */ -function TraceClient(aClient, aActor) { - this._client = aClient; - this._actor = aActor; +function TraceClient(client, actor) { + this._client = client; + this._actor = actor; this._activeTraces = new Set(); this._waitingPackets = new Map(); this._expectedPacket = 0; @@ -2349,10 +2383,16 @@ function TraceClient(aClient, aActor) { } TraceClient.prototype = { - get actor() { return this._actor; }, - get tracing() { return this._activeTraces.size > 0; }, + get actor() { + return this._actor; + }, + get tracing() { + return this._activeTraces.size > 0; + }, - get _transport() { return this._client._transport; }, + get _transport() { + return this._client._transport; + }, /** * Detach from the trace actor. @@ -2360,41 +2400,41 @@ TraceClient.prototype = { detach: DebuggerClient.requester({ type: "detach" }, { - after: function (aResponse) { + after: function (response) { this._client.unregisterClient(this); - return aResponse; + return response; }, }), /** * Start a new trace. * - * @param aTrace [string] + * @param trace [string] * An array of trace types to be recorded by the new trace. * - * @param aName string + * @param name string * The name of the new trace. * - * @param aOnResponse function + * @param onResponse function * Called with the request's response. */ startTrace: DebuggerClient.requester({ type: "startTrace", - name: args(1), - trace: args(0) + name: arg(1), + trace: arg(0) }, { - after: function (aResponse) { - if (aResponse.error) { - return aResponse; + after: function (response) { + if (response.error) { + return response; } if (!this.tracing) { this._waitingPackets.clear(); this._expectedPacket = 0; } - this._activeTraces.add(aResponse.name); + this._activeTraces.add(response.name); - return aResponse; + return response; }, }), @@ -2402,24 +2442,24 @@ TraceClient.prototype = { * End a trace. If a name is provided, stop the named * trace. Otherwise, stop the most recently started trace. * - * @param aName string + * @param name string * The name of the trace to stop. * - * @param aOnResponse function + * @param onResponse function * Called with the request's response. */ stopTrace: DebuggerClient.requester({ type: "stopTrace", - name: args(0) + name: arg(0) }, { - after: function (aResponse) { - if (aResponse.error) { - return aResponse; + after: function (response) { + if (response.error) { + return response; } - this._activeTraces.delete(aResponse.name); + this._activeTraces.delete(response.name); - return aResponse; + return response; }, }) }; @@ -2427,22 +2467,25 @@ TraceClient.prototype = { /** * Grip clients are used to retrieve information about the relevant object. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aGrip object + * @param grip object * A pause-lifetime object grip returned by the protocol. */ -function ObjectClient(aClient, aGrip) -{ - this._grip = aGrip; - this._client = aClient; +function ObjectClient(client, grip) { + this._grip = grip; + this._client = client; this.request = this._client.request; } exports.ObjectClient = ObjectClient; ObjectClient.prototype = { - get actor() { return this._grip.actor; }, - get _transport() { return this._client._transport; }, + get actor() { + return this._grip.actor; + }, + get _transport() { + return this._client._transport; + }, valid: true, @@ -2459,18 +2502,18 @@ ObjectClient.prototype = { getDefinitionSite: DebuggerClient.requester({ type: "definitionSite" }, { - before: function (aPacket) { + before: function (packet) { if (this._grip.class != "Function") { throw new Error("getDefinitionSite is only valid for function grips."); } - return aPacket; + return packet; } }), /** * Request the names of a function's formal parameters. * - * @param aOnResponse function + * @param onResponse function * Called with an object of the form: * { parameterNames:[, ...] } * where each is the name of a parameter. @@ -2478,11 +2521,11 @@ ObjectClient.prototype = { getParameterNames: DebuggerClient.requester({ type: "parameterNames" }, { - before: function (aPacket) { - if (this._grip["class"] !== "Function") { + before: function (packet) { + if (this._grip.class !== "Function") { throw new Error("getParameterNames is only valid for function grips."); } - return aPacket; + return packet; }, }), @@ -2490,7 +2533,7 @@ ObjectClient.prototype = { * Request the names of the properties defined on the object and not its * prototype. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getOwnPropertyNames: DebuggerClient.requester({ type: "ownPropertyNames" @@ -2499,7 +2542,7 @@ ObjectClient.prototype = { /** * Request the prototype and own properties of the object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getPrototypeAndProperties: DebuggerClient.requester({ type: "prototypeAndProperties" @@ -2521,17 +2564,17 @@ ObjectClient.prototype = { * - sort Boolean * If true, the iterator will sort the properties by name * before dispatching them. - * @param aOnResponse function Called with the client instance. + * @param onResponse function Called with the client instance. */ enumProperties: DebuggerClient.requester({ type: "enumProperties", - options: args(0) + options: arg(0) }, { - after: function (aResponse) { - if (aResponse.iterator) { - return { iterator: new PropertyIteratorClient(this._client, aResponse.iterator) }; + after: function (response) { + if (response.iterator) { + return { iterator: new PropertyIteratorClient(this._client, response.iterator) }; } - return aResponse; + return response; }, }), @@ -2539,7 +2582,7 @@ ObjectClient.prototype = { * Request a PropertyIteratorClient instance to enumerate entries in a * Map/Set-like object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ enumEntries: DebuggerClient.requester({ type: "enumEntries" @@ -2563,18 +2606,18 @@ ObjectClient.prototype = { /** * Request the property descriptor of the object's specified property. * - * @param aName string The name of the requested property. - * @param aOnResponse function Called with the request's response. + * @param name string The name of the requested property. + * @param onResponse function Called with the request's response. */ getProperty: DebuggerClient.requester({ type: "property", - name: args(0) + name: arg(0) }), /** * Request the prototype of the object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getPrototype: DebuggerClient.requester({ type: "prototype" @@ -2583,7 +2626,7 @@ ObjectClient.prototype = { /** * Request the display string of the object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getDisplayString: DebuggerClient.requester({ type: "displayString" @@ -2592,16 +2635,16 @@ ObjectClient.prototype = { /** * Request the scope of the object. * - * @param aOnResponse function Called with the request's response. + * @param onResponse function Called with the request's response. */ getScope: DebuggerClient.requester({ type: "scope" }, { - before: function (aPacket) { + before: function (packet) { if (this._grip.class !== "Function") { throw new Error("scope is only valid for function grips."); } - return aPacket; + return packet; }, }), @@ -2611,12 +2654,12 @@ ObjectClient.prototype = { getDependentPromises: DebuggerClient.requester({ type: "dependentPromises" }, { - before: function (aPacket) { + before: function (packet) { if (this._grip.class !== "Promise") { throw new Error("getDependentPromises is only valid for promise " + "grips."); } - return aPacket; + return packet; } }), @@ -2626,11 +2669,11 @@ ObjectClient.prototype = { getPromiseAllocationStack: DebuggerClient.requester({ type: "allocationStack" }, { - before: function (aPacket) { + before: function (packet) { if (this._grip.class !== "Promise") { throw new Error("getAllocationStack is only valid for promise grips."); } - return aPacket; + return packet; } }), @@ -2672,25 +2715,29 @@ ObjectClient.prototype = { * this is controled while creating the PropertyIteratorClient * from ObjectClient.enumProperties. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aGrip Object + * @param grip Object * A PropertyIteratorActor grip returned by the protocol via * TabActor.enumProperties request. */ -function PropertyIteratorClient(aClient, aGrip) { - this._grip = aGrip; - this._client = aClient; +function PropertyIteratorClient(client, grip) { + this._grip = grip; + this._client = client; this.request = this._client.request; } PropertyIteratorClient.prototype = { - get actor() { return this._grip.actor; }, + get actor() { + return this._grip.actor; + }, /** * Get the total number of properties available in the iterator. */ - get count() { return this._grip.count; }, + get count() { + return this._grip.count; + }, /** * Get one or more property names that correspond to the positions in the @@ -2698,12 +2745,12 @@ PropertyIteratorClient.prototype = { * * @param indexes Array * An array of property indexes. - * @param aCallback Function + * @param callback Function * The function called when we receive the property names. */ names: DebuggerClient.requester({ type: "names", - indexes: args(0) + indexes: arg(0) }, {}), /** @@ -2713,19 +2760,19 @@ PropertyIteratorClient.prototype = { * The index of the first property to fetch. * @param count Number * The number of properties to fetch. - * @param aCallback Function + * @param callback Function * The function called when we receive the property values. */ slice: DebuggerClient.requester({ type: "slice", - start: args(0), - count: args(1) + start: arg(0), + count: arg(1) }, {}), /** * Get all the property values. * - * @param aCallback Function + * @param callback Function * The function called when we receive the property values. */ all: DebuggerClient.requester({ @@ -2737,57 +2784,65 @@ PropertyIteratorClient.prototype = { * A LongStringClient provides a way to access "very long" strings from the * debugger server. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aGrip Object + * @param grip Object * A pause-lifetime long string grip returned by the protocol. */ -function LongStringClient(aClient, aGrip) { - this._grip = aGrip; - this._client = aClient; +function LongStringClient(client, grip) { + this._grip = grip; + this._client = client; this.request = this._client.request; } exports.LongStringClient = LongStringClient; LongStringClient.prototype = { - get actor() { return this._grip.actor; }, - get length() { return this._grip.length; }, - get initial() { return this._grip.initial; }, - get _transport() { return this._client._transport; }, + get actor() { + return this._grip.actor; + }, + get length() { + return this._grip.length; + }, + get initial() { + return this._grip.initial; + }, + get _transport() { + return this._client._transport; + }, valid: true, /** - * Get the substring of this LongString from aStart to aEnd. + * Get the substring of this LongString from start to end. * - * @param aStart Number + * @param start Number * The starting index. - * @param aEnd Number + * @param end Number * The ending index. - * @param aCallback Function + * @param callback Function * The function called when we receive the substring. */ substring: DebuggerClient.requester({ type: "substring", - start: args(0), - end: args(1) + start: arg(0), + end: arg(1) }), }; /** * A SourceClient provides a way to access the source text of a script. * - * @param aClient ThreadClient + * @param client ThreadClient * The thread client parent. - * @param aForm Object + * @param form Object * The form sent across the remote debugging protocol. */ -function SourceClient(aClient, aForm) { - this._form = aForm; - this._isBlackBoxed = aForm.isBlackBoxed; - this._isPrettyPrinted = aForm.isPrettyPrinted; - this._activeThread = aClient; - this._client = aClient.client; +function SourceClient(client, form) { + this._form = form; + this._isBlackBoxed = form.isBlackBoxed; + this._isPrettyPrinted = form.isPrettyPrinted; + this._activeThread = client; + this._client = client.client; } SourceClient.prototype = { @@ -2813,47 +2868,47 @@ SourceClient.prototype = { /** * Black box this SourceClient's source. * - * @param aCallback Function + * @param callback Function * The callback function called when we receive the response from the server. */ blackBox: DebuggerClient.requester({ type: "blackbox" }, { - after: function (aResponse) { - if (!aResponse.error) { + after: function (response) { + if (!response.error) { this._isBlackBoxed = true; if (this._activeThread) { this._activeThread.emit("blackboxchange", this); } } - return aResponse; + return response; } }), /** * Un-black box this SourceClient's source. * - * @param aCallback Function + * @param callback Function * The callback function called when we receive the response from the server. */ unblackBox: DebuggerClient.requester({ type: "unblackbox" }, { - after: function (aResponse) { - if (!aResponse.error) { + after: function (response) { + if (!response.error) { this._isBlackBoxed = false; if (this._activeThread) { this._activeThread.emit("blackboxchange", this); } } - return aResponse; + return response; } }), /** * Get Executable Lines from a source * - * @param aCallback Function + * @param callback Function * The callback function called when we receive the response from the server. */ getExecutableLines: function (cb = noop) { @@ -2871,105 +2926,105 @@ SourceClient.prototype = { /** * Get a long string grip for this SourceClient's source. */ - source: function (aCallback = noop) { + source: function (callback = noop) { let packet = { to: this._form.actor, type: "source" }; - return this._client.request(packet).then(aResponse => { - return this._onSourceResponse(aResponse, aCallback); + return this._client.request(packet).then(response => { + return this._onSourceResponse(response, callback); }); }, /** * Pretty print this source's text. */ - prettyPrint: function (aIndent, aCallback = noop) { + prettyPrint: function (indent, callback = noop) { const packet = { to: this._form.actor, type: "prettyPrint", - indent: aIndent + indent }; - return this._client.request(packet).then(aResponse => { - if (!aResponse.error) { + return this._client.request(packet).then(response => { + if (!response.error) { this._isPrettyPrinted = true; this._activeThread._clearFrames(); this._activeThread.emit("prettyprintchange", this); } - return this._onSourceResponse(aResponse, aCallback); + return this._onSourceResponse(response, callback); }); }, /** * Stop pretty printing this source's text. */ - disablePrettyPrint: function (aCallback = noop) { + disablePrettyPrint: function (callback = noop) { const packet = { to: this._form.actor, type: "disablePrettyPrint" }; - return this._client.request(packet).then(aResponse => { - if (!aResponse.error) { + return this._client.request(packet).then(response => { + if (!response.error) { this._isPrettyPrinted = false; this._activeThread._clearFrames(); this._activeThread.emit("prettyprintchange", this); } - return this._onSourceResponse(aResponse, aCallback); + return this._onSourceResponse(response, callback); }); }, - _onSourceResponse: function (aResponse, aCallback) { - if (aResponse.error) { - aCallback(aResponse); - return aResponse; + _onSourceResponse: function (response, callback) { + if (response.error) { + callback(response); + return response; } - if (typeof aResponse.source === "string") { - aCallback(aResponse); - return aResponse; + if (typeof response.source === "string") { + callback(response); + return response; } - let { contentType, source } = aResponse; + let { contentType, source } = response; let longString = this._activeThread.threadLongString(source); - return longString.substring(0, longString.length).then(function (aResponse) { - if (aResponse.error) { - aCallback(aResponse); - return aReponse; + return longString.substring(0, longString.length).then(function (resp) { + if (resp.error) { + callback(resp); + return resp; } - let response = { - source: aResponse.substring, + let newResponse = { + source: resp.substring, contentType: contentType }; - aCallback(response); - return response; + callback(newResponse); + return newResponse; }); }, /** * Request to set a breakpoint in the specified location. * - * @param object aLocation + * @param object location * The location and condition of the breakpoint in * the form of { line[, column, condition] }. - * @param function aOnResponse + * @param function onResponse * Called with the thread's response. */ - setBreakpoint: function ({ line, column, condition, noSliding }, aOnResponse = noop) { + setBreakpoint: function ({ line, column, condition, noSliding }, onResponse = noop) { // A helper function that sets the breakpoint. - let doSetBreakpoint = aCallback => { + let doSetBreakpoint = callback => { let root = this._client.mainRoot; let location = { - line: line, - column: column + line, + column, }; let packet = { to: this.actor, type: "setBreakpoint", - location: location, - condition: condition, - noSliding: noSliding + location, + condition, + noSliding, }; // Backwards compatibility: send the breakpoint request to the @@ -2979,24 +3034,24 @@ SourceClient.prototype = { packet.location.url = this.url; } - return this._client.request(packet).then(aResponse => { + return this._client.request(packet).then(response => { // Ignoring errors, since the user may be setting a breakpoint in a // dead script that will reappear on a page reload. let bpClient; - if (aResponse.actor) { + if (response.actor) { bpClient = new BreakpointClient( this._client, this, - aResponse.actor, + response.actor, location, root.traits.conditionalBreakpoints ? condition : undefined ); } - aOnResponse(aResponse, bpClient); - if (aCallback) { - aCallback(); + onResponse(response, bpClient); + if (callback) { + callback(); } - return [aResponse, bpClient]; + return [response, bpClient]; }); }; @@ -3005,14 +3060,14 @@ SourceClient.prototype = { return doSetBreakpoint(); } // Otherwise, force a pause in order to set the breakpoint. - return this._activeThread.interrupt().then(aResponse => { - if (aResponse.error) { + return this._activeThread.interrupt().then(response => { + if (response.error) { // Can't set the breakpoint if pausing failed. - aOnResponse(aResponse); - return aResponse; + onResponse(response); + return response; } - const { type, why } = aResponse; + const { type, why } = response; const cleanUp = type == "paused" && why.type == "interrupted" ? () => this._activeThread.resume() : noop; @@ -3025,38 +3080,42 @@ SourceClient.prototype = { /** * Breakpoint clients are used to remove breakpoints that are no longer used. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aSourceClient SourceClient + * @param sourceClient SourceClient * The source where this breakpoint exists - * @param aActor string + * @param actor string * The actor ID for this breakpoint. - * @param aLocation object + * @param location object * The location of the breakpoint. This is an object with two properties: * url and line. - * @param aCondition string + * @param condition string * The conditional expression of the breakpoint */ -function BreakpointClient(aClient, aSourceClient, aActor, aLocation, aCondition) { - this._client = aClient; - this._actor = aActor; - this.location = aLocation; - this.location.actor = aSourceClient.actor; - this.location.url = aSourceClient.url; - this.source = aSourceClient; +function BreakpointClient(client, sourceClient, actor, location, condition) { + this._client = client; + this._actor = actor; + this.location = location; + this.location.actor = sourceClient.actor; + this.location.url = sourceClient.url; + this.source = sourceClient; this.request = this._client.request; // The condition property should only exist if it's a truthy value - if (aCondition) { - this.condition = aCondition; + if (condition) { + this.condition = condition; } } BreakpointClient.prototype = { _actor: null, - get actor() { return this._actor; }, - get _transport() { return this._client._transport; }, + get actor() { + return this._actor; + }, + get _transport() { + return this._client._transport; + }, /** * Remove the breakpoint from the server. @@ -3074,9 +3133,8 @@ BreakpointClient.prototype = { // conditional breakpoints if (root.traits.conditionalBreakpoints) { return "condition" in this; - } else { - return "conditionalExpression" in this; } + return "conditionalExpression" in this; }, /** @@ -3090,15 +3148,14 @@ BreakpointClient.prototype = { let root = this._client.mainRoot; if (root.traits.conditionalBreakpoints) { return this.condition; - } else { - return this.conditionalExpression; } + return this.conditionalExpression; }, /** * Set the condition of this breakpoint */ - setCondition: function (gThreadClient, aCondition) { + setCondition: function (gThreadClient, condition) { let root = this._client.mainRoot; let deferred = promise.defer(); @@ -3106,32 +3163,31 @@ BreakpointClient.prototype = { let info = { line: this.location.line, column: this.location.column, - condition: aCondition + condition: condition }; // Remove the current breakpoint and add a new one with the // condition. - this.remove(aResponse => { - if (aResponse && aResponse.error) { - deferred.reject(aResponse); + this.remove(response => { + if (response && response.error) { + deferred.reject(response); return; } - this.source.setBreakpoint(info, (aResponse, aNewBreakpoint) => { - if (aResponse && aResponse.error) { - deferred.reject(aResponse); + this.source.setBreakpoint(info, (resp, newBreakpoint) => { + if (resp && resp.error) { + deferred.reject(resp); } else { - deferred.resolve(aNewBreakpoint); + deferred.resolve(newBreakpoint); } }); }); } else { // The property shouldn't even exist if the condition is blank - if (aCondition === "") { + if (condition === "") { delete this.conditionalExpression; - } - else { - this.conditionalExpression = aCondition; + } else { + this.conditionalExpression = condition; } deferred.resolve(this); } @@ -3145,14 +3201,14 @@ eventSource(BreakpointClient.prototype); /** * Environment clients are used to manipulate the lexical environment actors. * - * @param aClient DebuggerClient + * @param client DebuggerClient * The debugger client parent. - * @param aForm Object + * @param form Object * The form sent across the remote debugging protocol. */ -function EnvironmentClient(aClient, aForm) { - this._client = aClient; - this._form = aForm; +function EnvironmentClient(client, form) { + this._client = client; + this._form = form; this.request = this._client.request; } exports.EnvironmentClient = EnvironmentClient; @@ -3162,7 +3218,9 @@ EnvironmentClient.prototype = { get actor() { return this._form.actor; }, - get _transport() { return this._client._transport; }, + get _transport() { + return this._client._transport; + }, /** * Fetches the bindings introduced by this lexical environment. @@ -3177,8 +3235,8 @@ EnvironmentClient.prototype = { */ assign: DebuggerClient.requester({ type: "assign", - name: args(0), - value: args(1) + name: arg(0), + value: arg(1) }) }; diff --git a/devtools/shared/discovery/discovery.js b/devtools/shared/discovery/discovery.js index d0b49f1290cd..a07f21d445e7 100644 --- a/devtools/shared/discovery/discovery.js +++ b/devtools/shared/discovery/discovery.js @@ -47,8 +47,8 @@ const REPLY_TIMEOUT = 5000; const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {}); XPCOMUtils.defineLazyGetter(this, "converter", () => { - let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]. - createInstance(Ci.nsIScriptableUnicodeConverter); + let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"] + .createInstance(Ci.nsIScriptableUnicodeConverter); conv.charset = "utf8"; return conv; }); @@ -77,7 +77,8 @@ function log(msg) { function Transport(port) { EventEmitter.decorate(this); try { - this.socket = new UDPSocket(port, false, Services.scriptSecurityManager.getSystemPrincipal()); + this.socket = new UDPSocket(port, false, + Services.scriptSecurityManager.getSystemPrincipal()); this.socket.joinMulticast(ADDRESS); this.socket.asyncListen(this); } catch (e) { @@ -146,7 +147,8 @@ function LocalDevice() { Cc["@mozilla.org/settingsService;1"].getService(Ci.nsISettingsService); Services.obs.addObserver(this, "mozsettings-changed", false); } - this._get(); // Trigger |_get| to load name eagerly + // Trigger |_get| to load name eagerly + this._get(); } LocalDevice.SETTING = "devtools.discovery.device"; @@ -344,7 +346,8 @@ Discovery.prototype = { _startListeningForScan: function () { if (this._transports.scan) { - return; // Already listening + // Already listening + return; } log("LISTEN FOR SCAN"); this._transports.scan = new this.Transport(SCAN_PORT); @@ -353,7 +356,8 @@ Discovery.prototype = { _stopListeningForScan: function () { if (!this._transports.scan) { - return; // Not listening + // Not listening + return; } this._transports.scan.off("message", this._onRemoteScan); this._transports.scan.destroy(); @@ -362,7 +366,8 @@ Discovery.prototype = { _startListeningForUpdate: function () { if (this._transports.update) { - return; // Already listening + // Already listening + return; } log("LISTEN FOR UPDATE"); this._transports.update = new this.Transport(UPDATE_PORT); @@ -371,7 +376,8 @@ Discovery.prototype = { _stopListeningForUpdate: function () { if (!this._transports.update) { - return; // Not listening + // Not listening + return; } this._transports.update.off("message", this._onRemoteUpdate); this._transports.update.destroy(); diff --git a/devtools/shared/discovery/tests/unit/.eslintrc.js b/devtools/shared/discovery/tests/unit/.eslintrc.js new file mode 100644 index 000000000000..f21b71f67ad0 --- /dev/null +++ b/devtools/shared/discovery/tests/unit/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../../.eslintrc.xpcshell.js" +}; \ No newline at end of file diff --git a/devtools/shared/discovery/tests/unit/test_discovery.js b/devtools/shared/discovery/tests/unit/test_discovery.js index c31340b08966..56b0bc1e7c94 100644 --- a/devtools/shared/discovery/tests/unit/test_discovery.js +++ b/devtools/shared/discovery/tests/unit/test_discovery.js @@ -8,7 +8,6 @@ var Cu = Components.utils; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); const Services = require("Services"); -const promise = require("promise"); const defer = require("devtools/shared/defer"); const EventEmitter = require("devtools/shared/event-emitter"); const discovery = require("devtools/shared/discovery/discovery"); diff --git a/devtools/shared/performance/recording-common.js b/devtools/shared/performance/recording-common.js index d0826bd1881e..8aa6440e4ee1 100644 --- a/devtools/shared/performance/recording-common.js +++ b/devtools/shared/performance/recording-common.js @@ -9,7 +9,7 @@ * and LegacyPerformanceRecording for helper methods to access data. */ -const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { +exports.PerformanceRecordingCommon = { // Private fields, only needed when a recording is started or stopped. _console: false, _imported: false, @@ -35,18 +35,32 @@ const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { * Helper methods for returning the status of the recording. * These methods should be consistent on both the front and actor. */ - isRecording: function () { return this._recording; }, - isCompleted: function () { return this._completed || this.isImported(); }, - isFinalizing: function () { return !this.isRecording() && !this.isCompleted(); }, - isConsole: function () { return this._console; }, - isImported: function () { return this._imported; }, + isRecording: function () { + return this._recording; + }, + isCompleted: function () { + return this._completed || this.isImported(); + }, + isFinalizing: function () { + return !this.isRecording() && !this.isCompleted(); + }, + isConsole: function () { + return this._console; + }, + isImported: function () { + return this._imported; + }, /** * Helper methods for returning configuration for the recording. * These methods should be consistent on both the front and actor. */ - getConfiguration: function () { return this._configuration; }, - getLabel: function () { return this._label; }, + getConfiguration: function () { + return this._configuration; + }, + getLabel: function () { + return this._label; + }, /** * Gets duration of this recording, in milliseconds. @@ -59,25 +73,43 @@ const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { // the duration from the profiler; if between recording and being finalized, // use the last estimated duration. if (this.isRecording()) { - return this._estimatedDuration = Date.now() - this._localStartTime; - } else { - return this._duration || this._estimatedDuration || 0; + this._estimatedDuration = Date.now() - this._localStartTime; + return this._estimatedDuration; } + return this._duration || this._estimatedDuration || 0; }, /** * Helper methods for returning recording data. * These methods should be consistent on both the front and actor. */ - getMarkers: function () { return this._markers; }, - getFrames: function () { return this._frames; }, - getMemory: function () { return this._memory; }, - getTicks: function () { return this._ticks; }, - getAllocations: function () { return this._allocations; }, - getProfile: function () { return this._profile; }, - getHostSystemInfo: function () { return this._systemHost; }, - getClientSystemInfo: function () { return this._systemClient; }, - getStartingBufferStatus: function () { return this._startingBufferStatus; }, + getMarkers: function () { + return this._markers; + }, + getFrames: function () { + return this._frames; + }, + getMemory: function () { + return this._memory; + }, + getTicks: function () { + return this._ticks; + }, + getAllocations: function () { + return this._allocations; + }, + getProfile: function () { + return this._profile; + }, + getHostSystemInfo: function () { + return this._systemHost; + }, + getClientSystemInfo: function () { + return this._systemClient; + }, + getStartingBufferStatus: function () { + return this._startingBufferStatus; + }, getAllData: function () { let label = this.getLabel(); @@ -92,6 +124,18 @@ const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { let systemHost = this.getHostSystemInfo(); let systemClient = this.getClientSystemInfo(); - return { label, duration, markers, frames, memory, ticks, allocations, profile, configuration, systemHost, systemClient }; + return { + label, + duration, + markers, + frames, + memory, + ticks, + allocations, + profile, + configuration, + systemHost, + systemClient + }; }, }; diff --git a/devtools/shared/performance/recording-utils.js b/devtools/shared/performance/recording-utils.js index 64ed12c71f1c..3b9c4cbca0fd 100644 --- a/devtools/shared/performance/recording-utils.js +++ b/devtools/shared/performance/recording-utils.js @@ -3,7 +3,6 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Cc, Ci, Cu, Cr } = require("chrome"); loader.lazyRequireGetter(this, "extend", "sdk/util/object", true); @@ -16,7 +15,8 @@ function mapRecordingOptions(type, options) { if (type === "profiler") { return { entries: options.bufferSize, - interval: options.sampleFrequency ? (1000 / (options.sampleFrequency * 1000)) : void 0 + interval: options.sampleFrequency ? (1000 / (options.sampleFrequency * 1000)) + : void 0 }; } @@ -568,7 +568,8 @@ UniqueStacks.prototype.getOrAddFrameIndex = function (frame) { let implementationIndex = this.getOrAddStringIndex(frame.implementation); // Super dumb. - let hash = `${locationIndex} ${implementationIndex || ""} ${frame.line || ""} ${frame.category || ""}`; + let hash = `${locationIndex} ${implementationIndex || ""} ` + + `${frame.line || ""} ${frame.category || ""}`; let index = frameHash[hash]; if (index !== undefined) { diff --git a/devtools/shared/performance/test/.eslintrc.js b/devtools/shared/performance/test/.eslintrc.js new file mode 100644 index 000000000000..90ed7706421b --- /dev/null +++ b/devtools/shared/performance/test/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../.eslintrc.xpcshell.js" +}; \ No newline at end of file diff --git a/devtools/shared/performance/test/head.js b/devtools/shared/performance/test/head.js index 9e7748055723..414831c96443 100644 --- a/devtools/shared/performance/test/head.js +++ b/devtools/shared/performance/test/head.js @@ -1,7 +1,10 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ + +/* exported require */ + "use strict"; -var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; +var { utils: Cu } = Components; var { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); diff --git a/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js b/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js index 6429eff2d434..141395652275 100644 --- a/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js +++ b/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + /** * Tests if allocations data received from the performance actor is properly * converted to something that follows the same structure as the samples data @@ -65,9 +67,15 @@ var EXPECTED_OUTPUT = { }, "data": [ null, - [ null, 1 ], // x (A:1:2) - [ 1, 2 ], // x (A:1:2) > y (B:3:4) - [ 2, 3 ] // x (A:1:2) > y (B:3:4) > C:5:6 + + // x (A:1:2) + [ null, 1 ], + + // x (A:1:2) > y (B:3:4) + [ 1, 2 ], + + // x (A:1:2) > y (B:3:4) > C:5:6 + [ 2, 3 ] ] }, frameTable: { diff --git a/devtools/shared/qrcode/index.js b/devtools/shared/qrcode/index.js index ec3442426402..7bf97e1babc0 100644 --- a/devtools/shared/qrcode/index.js +++ b/devtools/shared/qrcode/index.js @@ -4,7 +4,6 @@ "use strict"; -const { Cu } = require("chrome"); const promise = require("promise"); const defer = require("devtools/shared/defer"); diff --git a/devtools/shared/qrcode/tests/unit/.eslintrc.js b/devtools/shared/qrcode/tests/unit/.eslintrc.js new file mode 100644 index 000000000000..f21b71f67ad0 --- /dev/null +++ b/devtools/shared/qrcode/tests/unit/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../../.eslintrc.xpcshell.js" +}; \ No newline at end of file diff --git a/devtools/shared/security/auth.js b/devtools/shared/security/auth.js index 9272f602ebdc..52c9070b77bc 100644 --- a/devtools/shared/security/auth.js +++ b/devtools/shared/security/auth.js @@ -8,7 +8,6 @@ var { Ci, Cc } = require("chrome"); var Services = require("Services"); -var promise = require("promise"); var defer = require("devtools/shared/defer"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); var { dumpn, dumpv } = DevToolsUtils; @@ -408,7 +407,8 @@ OOBCert.Client.prototype = { }), _createRandom() { - const length = 16; // 16 bytes / 128 bits + // 16 bytes / 128 bits + const length = 16; let rng = Cc["@mozilla.org/security/random-generator;1"] .createInstance(Ci.nsIRandomGenerator); let bytes = rng.generateRandomBytes(length); @@ -545,9 +545,11 @@ OOBCert.Server.prototype = { switch (authResult) { case AuthenticationResult.ALLOW_PERSIST: case AuthenticationResult.ALLOW: - break; // Further processing + // Further processing + break; default: - return authResult; // Abort for any negative results + // Abort for any negative results + return authResult; } // Examine additional data for authentication diff --git a/devtools/shared/security/cert.js b/devtools/shared/security/cert.js index 7dbeded63116..7c101f3dbf0e 100644 --- a/devtools/shared/security/cert.js +++ b/devtools/shared/security/cert.js @@ -7,7 +7,6 @@ "use strict"; var { Ci, Cc } = require("chrome"); -var promise = require("promise"); var defer = require("devtools/shared/defer"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); DevToolsUtils.defineLazyGetter(this, "localCertService", () => { diff --git a/devtools/shared/security/socket.js b/devtools/shared/security/socket.js index 068a8ea81f0a..64d882c01b5d 100644 --- a/devtools/shared/security/socket.js +++ b/devtools/shared/security/socket.js @@ -6,7 +6,7 @@ "use strict"; -var { Ci, Cc, CC, Cr, Cu } = require("chrome"); +var { Ci, Cc, CC, Cr } = require("chrome"); // Ensure PSM is initialized to support TLS sockets Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports); @@ -143,7 +143,8 @@ var _getTransport = Task.async(function* (settings) { let attempt = yield _attemptTransport(settings); if (attempt.transport) { - return attempt.transport; // Success + // Success + return attempt.transport; } // If the server cert failed validation, store a temporary override and make @@ -156,7 +157,8 @@ var _getTransport = Task.async(function* (settings) { attempt = yield _attemptTransport(settings); if (attempt.transport) { - return attempt.transport; // Success + // Success + return attempt.transport; } throw new Error("Connection failed even after cert override"); @@ -356,7 +358,7 @@ function _storeCertOverride(s, host, port) { let overrideBits = Ci.nsICertOverrideService.ERROR_UNTRUSTED | Ci.nsICertOverrideService.ERROR_MISMATCH; certOverrideService.rememberValidityOverride(host, port, cert, overrideBits, - true /* temporary */); + true /* temporary */); // eslint-disable-line } /** diff --git a/devtools/shared/security/tests/chrome/.eslintrc.js b/devtools/shared/security/tests/chrome/.eslintrc.js new file mode 100644 index 000000000000..6dc0ab32b6e9 --- /dev/null +++ b/devtools/shared/security/tests/chrome/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../../../testing/mochitest/chrome.eslintrc.js" +}; diff --git a/devtools/shared/security/tests/chrome/test_websocket-transport.html b/devtools/shared/security/tests/chrome/test_websocket-transport.html index 542206ecfbfe..edcb5b2ffad7 100644 --- a/devtools/shared/security/tests/chrome/test_websocket-transport.html +++ b/devtools/shared/security/tests/chrome/test_websocket-transport.html @@ -9,7 +9,9 @@ diff --git a/devtools/shared/security/tests/unit/head_dbg.js b/devtools/shared/security/tests/unit/head_dbg.js index f3b2a9a9744d..790675c56dc7 100644 --- a/devtools/shared/security/tests/unit/head_dbg.js +++ b/devtools/shared/security/tests/unit/head_dbg.js @@ -2,20 +2,14 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; -var Cc = Components.classes; -var Ci = Components.interfaces; -var Cu = Components.utils; -var Cr = Components.results; -var CC = Components.Constructor; +/* exported defer, DebuggerClient, initTestDebuggerServer */ + +const { classes: Cc, interfaces: Ci, utils: Cu } = Components; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); -const promise = require("promise"); const defer = require("devtools/shared/defer"); -const { Task } = require("devtools/shared/task"); - const Services = require("Services"); -const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const xpcInspector = require("xpcInspector"); const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/main"); @@ -31,43 +25,43 @@ Services.prefs.setBoolPref("devtools.debugger.remote-enabled", true); // Fast timeout for TLS tests Services.prefs.setIntPref("devtools.remote.tls-handshake-timeout", 1000); -// Convert an nsIScriptError 'aFlags' value into an appropriate string. -function scriptErrorFlagsToKind(aFlags) { - var kind; - if (aFlags & Ci.nsIScriptError.warningFlag) +// Convert an nsIScriptError 'flags' value into an appropriate string. +function scriptErrorFlagsToKind(flags) { + let kind; + if (flags & Ci.nsIScriptError.warningFlag) { kind = "warning"; - if (aFlags & Ci.nsIScriptError.exceptionFlag) + } + if (flags & Ci.nsIScriptError.exceptionFlag) { kind = "exception"; - else + } else { kind = "error"; + } - if (aFlags & Ci.nsIScriptError.strictFlag) + if (flags & Ci.nsIScriptError.strictFlag) { kind = "strict " + kind; + } return kind; } // Register a console listener, so console messages don't just disappear // into the ether. -var errorCount = 0; var listener = { - observe: function (aMessage) { - errorCount++; + observe: function (message) { + let string; try { - // If we've been given an nsIScriptError, then we can print out - // something nicely formatted, for tools like Emacs to pick up. - var scriptError = aMessage.QueryInterface(Ci.nsIScriptError); - dump(aMessage.sourceName + ":" + aMessage.lineNumber + ": " + - scriptErrorFlagsToKind(aMessage.flags) + ": " + - aMessage.errorMessage + "\n"); - var string = aMessage.errorMessage; - } catch (x) { + message.QueryInterface(Ci.nsIScriptError); + dump(message.sourceName + ":" + message.lineNumber + ": " + + scriptErrorFlagsToKind(message.flags) + ": " + + message.errorMessage + "\n"); + string = message.errorMessage; + } catch (ex) { // Be a little paranoid with message, as the whole goal here is to lose // no information. try { - var string = "" + aMessage.message; - } catch (x) { - var string = ""; + string = "" + message.message; + } catch (e) { + string = ""; } } @@ -77,7 +71,7 @@ var listener = { } // Print in most cases, but ignore the "strict" messages - if (!(aMessage.flags & Ci.nsIScriptError.strictFlag)) { + if (!(message.flags & Ci.nsIScriptError.strictFlag)) { do_print("head_dbg.js got console message: " + string + "\n"); } } diff --git a/devtools/shared/security/tests/unit/test_oob_cert_auth.js b/devtools/shared/security/tests/unit/test_oob_cert_auth.js index 1e820af52b2e..e37a0f589d80 100644 --- a/devtools/shared/security/tests/unit/test_oob_cert_auth.js +++ b/devtools/shared/security/tests/unit/test_oob_cert_auth.js @@ -38,7 +38,8 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests + // Skip prompt for tests + serverAuth.receiveOOB = () => oobData.promise; let listener = DebuggerServer.createListener(); ok(listener, "Socket listener created"); @@ -98,7 +99,8 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests + // Skip prompt for tests + serverAuth.receiveOOB = () => oobData.promise; let listener = DebuggerServer.createListener(); ok(listener, "Socket listener created"); @@ -161,7 +163,8 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests + // Skip prompt for tests + serverAuth.receiveOOB = () => oobData.promise; let clientAuth = new AuthenticatorType.Client(); clientAuth.sendOOB = ({ oob }) => { @@ -215,7 +218,8 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests + // Skip prompt for tests + serverAuth.receiveOOB = () => oobData.promise; let clientAuth = new AuthenticatorType.Client(); clientAuth.sendOOB = ({ oob }) => { diff --git a/devtools/shared/security/tests/unit/testactors.js b/devtools/shared/security/tests/unit/testactors.js index 80d5d4e18abe..1a170cba78e9 100644 --- a/devtools/shared/security/tests/unit/testactors.js +++ b/devtools/shared/security/tests/unit/testactors.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + const { ActorPool, appendExtraActors, createExtraActors } = require("devtools/server/actors/common"); const { RootActor } = require("devtools/server/actors/root"); @@ -9,8 +11,8 @@ const { DebuggerServer } = require("devtools/server/main"); const promise = require("promise"); var gTestGlobals = []; -DebuggerServer.addTestGlobal = function (aGlobal) { - gTestGlobals.push(aGlobal); +DebuggerServer.addTestGlobal = function (global) { + gTestGlobals.push(global); }; // A mock tab list, for use by tests. This simply presents each global in @@ -20,18 +22,18 @@ DebuggerServer.addTestGlobal = function (aGlobal) { // As implemented now, we consult gTestGlobals when we're constructed, not // when we're iterated over, so tests have to add their globals before the // root actor is created. -function TestTabList(aConnection) { - this.conn = aConnection; +function TestTabList(connection) { + this.conn = connection; // An array of actors for each global added with // DebuggerServer.addTestGlobal. this._tabActors = []; // A pool mapping those actors' names to the actors. - this._tabActorPool = new ActorPool(aConnection); + this._tabActorPool = new ActorPool(connection); for (let global of gTestGlobals) { - let actor = new TestTabActor(aConnection, global); + let actor = new TestTabActor(connection, global); actor.selected = false; this._tabActors.push(actor); this._tabActorPool.addActor(actor); @@ -40,7 +42,7 @@ function TestTabList(aConnection) { this._tabActors[0].selected = true; } - aConnection.addActorPool(this._tabActorPool); + connection.addActorPool(this._tabActorPool); } TestTabList.prototype = { @@ -50,18 +52,18 @@ TestTabList.prototype = { } }; -function createRootActor(aConnection) { - let root = new RootActor(aConnection, { - tabList: new TestTabList(aConnection), +function createRootActor(connection) { + let root = new RootActor(connection, { + tabList: new TestTabList(connection), globalActorFactories: DebuggerServer.globalActorFactories }); root.applicationType = "xpcshell-tests"; return root; } -function TestTabActor(aConnection, aGlobal) { - this.conn = aConnection; - this._global = aGlobal; +function TestTabActor(connection, global) { + this.conn = connection; + this._global = global; this._threadActor = new ThreadActor(this, this._global); this.conn.addActor(this._threadActor); this._attached = false; @@ -96,7 +98,7 @@ TestTabActor.prototype = { return response; }, - onAttach: function (aRequest) { + onAttach: function (request) { this._attached = true; let response = { type: "tabAttached", threadActor: this._threadActor.actorID }; @@ -105,9 +107,9 @@ TestTabActor.prototype = { return response; }, - onDetach: function (aRequest) { + onDetach: function (request) { if (!this._attached) { - return { "error":"wrongState" }; + return { "error": "wrongState" }; } return { type: "detached" }; }, diff --git a/devtools/shared/shims/event-emitter.js b/devtools/shared/shims/event-emitter.js index 6b3672162917..bf648e373ad4 100644 --- a/devtools/shared/shims/event-emitter.js +++ b/devtools/shared/shims/event-emitter.js @@ -9,10 +9,13 @@ * specific path. */ -(function (factory) { // Module boilerplate - if (this.module && module.id.indexOf("event-emitter") >= 0) { // require +(function (factory) { + // Module boilerplate + if (this.module && module.id.indexOf("event-emitter") >= 0) { + // require factory.call(this, require, exports, module); - } else { // Cu.import + } else { + // Cu.import const Cu = Components.utils; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); diff --git a/devtools/shared/tests/browser/browser_async_storage.js b/devtools/shared/tests/browser/browser_async_storage.js index 4329d639aee2..141965cf00b4 100644 --- a/devtools/shared/tests/browser/browser_async_storage.js +++ b/devtools/shared/tests/browser/browser_async_storage.js @@ -30,7 +30,7 @@ add_task(function* () { }); add_task(function* () { - var object = { + let object = { x: 1, y: "foo", z: true diff --git a/devtools/shared/tests/unit/exposeLoader.js b/devtools/shared/tests/unit/exposeLoader.js index 949640a03e4e..7c8acdd75945 100644 --- a/devtools/shared/tests/unit/exposeLoader.js +++ b/devtools/shared/tests/unit/exposeLoader.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + exports.exerciseLazyRequire = (name, path) => { const o = {}; loader.lazyRequireGetter(o, name, path); diff --git a/devtools/shared/tests/unit/head_devtools.js b/devtools/shared/tests/unit/head_devtools.js index f0f47c93ac15..2854d9389758 100644 --- a/devtools/shared/tests/unit/head_devtools.js +++ b/devtools/shared/tests/unit/head_devtools.js @@ -1,13 +1,12 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; -var Cc = Components.classes; -var Ci = Components.interfaces; -var Cu = Components.utils; -var Cr = Components.results; +/* exported DevToolsUtils, DevToolsLoader */ -const {require, DevToolsLoader, devtools} = Cu.import("resource://devtools/shared/Loader.jsm", {}); +"use strict"; + +const { classes: Cc, interfaces: Ci, utils: Cu } = Components; +const { require, DevToolsLoader } = Cu.import("resource://devtools/shared/Loader.jsm", {}); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const flags = require("devtools/shared/flags"); @@ -23,25 +22,22 @@ do_register_cleanup(() => { // failures, set this to true. var ALLOW_CONSOLE_ERRORS = false; -var errorCount = 0; var listener = { - observe: function (aMessage) { - errorCount++; + observe: function (message) { + let string; try { - // If we've been given an nsIScriptError, then we can print out - // something nicely formatted, for tools like Emacs to pick up. - var scriptError = aMessage.QueryInterface(Ci.nsIScriptError); - dump(aMessage.sourceName + ":" + aMessage.lineNumber + ": " + - scriptErrorFlagsToKind(aMessage.flags) + ": " + - aMessage.errorMessage + "\n"); - var string = aMessage.errorMessage; - } catch (x) { + message.QueryInterface(Ci.nsIScriptError); + dump(message.sourceName + ":" + message.lineNumber + ": " + + scriptErrorFlagsToKind(message.flags) + ": " + + message.errorMessage + "\n"); + string = message.errorMessage; + } catch (ex) { // Be a little paranoid with message, as the whole goal here is to lose // no information. try { - var string = "" + aMessage.message; - } catch (x) { - var string = ""; + string = "" + message.message; + } catch (e) { + string = ""; } } diff --git a/devtools/shared/tests/unit/test_assert.js b/devtools/shared/tests/unit/test_assert.js index b871717511a4..e5fe01974139 100644 --- a/devtools/shared/tests/unit/test_assert.js +++ b/devtools/shared/tests/unit/test_assert.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test DevToolsUtils.assert ALLOW_CONSOLE_ERRORS = true; @@ -32,5 +34,6 @@ function run_test() { } ok(assertionFailed, - "The assertion should have failed, which should throw an error when assertions are enabled."); + "The assertion should have failed, which should throw an error when assertions " + + "are enabled."); } diff --git a/devtools/shared/tests/unit/test_async-utils.js b/devtools/shared/tests/unit/test_async-utils.js index 2b09b82608ca..8c640c473bca 100644 --- a/devtools/shared/tests/unit/test_async-utils.js +++ b/devtools/shared/tests/unit/test_async-utils.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test async-utils.js const {Task} = require("devtools/shared/task"); @@ -60,12 +62,13 @@ function test_async_return(async) { function test_async_throw(async) { let obj = { method: async(function* () { - throw "boom"; + throw new Error("boom"); }) }; return obj.method().then(null, error => { - do_check_eq(error, "boom"); + do_check_true(error instanceof Error); + do_check_eq(error.message, "boom"); }); } @@ -116,7 +119,6 @@ function test_async_once() { function test_async_invoke() { return Task.spawn(function* () { function func(a, b, expectedThis, callback) { - "use strict"; do_check_eq(a, "foo"); do_check_eq(b, "bar"); do_check_eq(this, expectedThis); @@ -127,13 +129,11 @@ function test_async_invoke() { let callResult = yield promiseCall(func, "foo", "bar", undefined); do_check_eq(callResult, "foobar"); - // Test invoke. let obj = { method: func }; let invokeResult = yield promiseInvoke(obj, obj.method, "foo", "bar", obj); do_check_eq(invokeResult, "foobar"); - // Test passing multiple values to the callback. function multipleResults(callback) { callback("foo", "bar"); @@ -144,14 +144,14 @@ function test_async_invoke() { do_check_eq(results[0], "foo"); do_check_eq(results[1], "bar"); - // Test throwing from the function. function thrower() { - throw "boom"; + throw new Error("boom"); } yield promiseCall(thrower).then(null, error => { - do_check_eq(error, "boom"); + do_check_true(error instanceof Error); + do_check_eq(error.message, "boom"); }); }); } diff --git a/devtools/shared/tests/unit/test_console_filtering.js b/devtools/shared/tests/unit/test_console_filtering.js index 6ee620ebbe6f..e126981d0cfa 100644 --- a/devtools/shared/tests/unit/test_console_filtering.js +++ b/devtools/shared/tests/unit/test_console_filtering.js @@ -11,19 +11,19 @@ var seenMessages = 0; var seenTypes = 0; var callback = { - onConsoleAPICall: function (aMessage) { - if (aMessage.consoleID && aMessage.consoleID == "addon/foo") { - do_check_eq(aMessage.level, "warn"); - do_check_eq(aMessage.arguments[0], "Warning from foo"); + onConsoleAPICall: function (message) { + if (message.consoleID && message.consoleID == "addon/foo") { + do_check_eq(message.level, "warn"); + do_check_eq(message.arguments[0], "Warning from foo"); seenTypes |= 1; - } else if (aMessage.originAttributes && - aMessage.originAttributes.addonId == "bar") { - do_check_eq(aMessage.level, "error"); - do_check_eq(aMessage.arguments[0], "Error from bar"); + } else if (message.originAttributes && + message.originAttributes.addonId == "bar") { + do_check_eq(message.level, "error"); + do_check_eq(message.arguments[0], "Error from bar"); seenTypes |= 2; } else { - do_check_eq(aMessage.level, "log"); - do_check_eq(aMessage.arguments[0], "Hello from default console"); + do_check_eq(message.level, "log"); + do_check_eq(message.arguments[0], "Hello from default console"); seenTypes |= 4; } seenMessages++; diff --git a/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js b/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js index d729e747398d..452d01847306 100644 --- a/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js +++ b/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js @@ -1,13 +1,13 @@ -/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test DevToolsUtils.defineLazyPrototypeGetter function Class() {} DevToolsUtils.defineLazyPrototypeGetter(Class.prototype, "foo", () => []); - function run_test() { test_prototype_attributes(); test_instance_attributes(); diff --git a/devtools/shared/tests/unit/test_executeSoon.js b/devtools/shared/tests/unit/test_executeSoon.js index 6154a3e67e35..78bdcd6a4ea3 100644 --- a/devtools/shared/tests/unit/test_executeSoon.js +++ b/devtools/shared/tests/unit/test_executeSoon.js @@ -11,7 +11,6 @@ */ var { executeSoon } = require("devtools/shared/DevToolsUtils"); -var promise = require("promise"); var defer = require("devtools/shared/defer"); var Services = require("Services"); diff --git a/devtools/shared/tests/unit/test_flatten.js b/devtools/shared/tests/unit/test_flatten.js index f5a186770cc0..11c2ac047479 100644 --- a/devtools/shared/tests/unit/test_flatten.js +++ b/devtools/shared/tests/unit/test_flatten.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test ThreadSafeDevToolsUtils.flatten function run_test() { diff --git a/devtools/shared/tests/unit/test_independent_loaders.js b/devtools/shared/tests/unit/test_independent_loaders.js index 20abed27d208..6d3aaead6935 100644 --- a/devtools/shared/tests/unit/test_independent_loaders.js +++ b/devtools/shared/tests/unit/test_independent_loaders.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + /** * Ensure that each instance of the Dev Tools loader contains its own loader * instance, and also returns unique objects. This ensures there is no sharing diff --git a/devtools/shared/tests/unit/test_isSet.js b/devtools/shared/tests/unit/test_isSet.js index f85d6ae3c3f1..a9e1fcafa9ab 100644 --- a/devtools/shared/tests/unit/test_isSet.js +++ b/devtools/shared/tests/unit/test_isSet.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test ThreadSafeDevToolsUtils.isSet function run_test() { diff --git a/devtools/shared/tests/unit/test_require.js b/devtools/shared/tests/unit/test_require.js index 005e5665633e..2d10d1e0f8c0 100644 --- a/devtools/shared/tests/unit/test_require.js +++ b/devtools/shared/tests/unit/test_require.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test require // Ensure that DevtoolsLoader.require doesn't spawn multiple diff --git a/devtools/shared/tests/unit/test_require_lazy.js b/devtools/shared/tests/unit/test_require_lazy.js index 8ef5a7d23e7b..d545653d6244 100644 --- a/devtools/shared/tests/unit/test_require_lazy.js +++ b/devtools/shared/tests/unit/test_require_lazy.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test devtools.lazyRequireGetter function run_test() { @@ -18,7 +20,8 @@ function run_test() { const o2 = {}; let loader = new DevToolsLoader(); - // We have to init the loader by loading any module before lazyRequireGetter is available + // We have to init the loader by loading any module before + // lazyRequireGetter is available loader.require("devtools/shared/DevToolsUtils"); loader.lazyRequireGetter(o2, name, path); diff --git a/devtools/shared/tests/unit/test_require_raw.js b/devtools/shared/tests/unit/test_require_raw.js index 5bec82b55bb0..1cfd0d3f3d22 100644 --- a/devtools/shared/tests/unit/test_require_raw.js +++ b/devtools/shared/tests/unit/test_require_raw.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test require using "raw!". function run_test() { diff --git a/devtools/shared/tests/unit/test_safeErrorString.js b/devtools/shared/tests/unit/test_safeErrorString.js index 9892f34d1e63..afde7d7c97c5 100644 --- a/devtools/shared/tests/unit/test_safeErrorString.js +++ b/devtools/shared/tests/unit/test_safeErrorString.js @@ -2,6 +2,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test DevToolsUtils.safeErrorString function run_test() { diff --git a/devtools/shared/tests/unit/test_stack.js b/devtools/shared/tests/unit/test_stack.js index ef747c83f6de..7342526e45eb 100644 --- a/devtools/shared/tests/unit/test_stack.js +++ b/devtools/shared/tests/unit/test_stack.js @@ -1,6 +1,8 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + // Test stack.js. function run_test() { diff --git a/devtools/shared/touch/simulator-content.js b/devtools/shared/touch/simulator-content.js index 0b10579ca586..6c9f3f2bfdec 100644 --- a/devtools/shared/touch/simulator-content.js +++ b/devtools/shared/touch/simulator-content.js @@ -1,7 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - /* globals addMessageListener, sendAsyncMessage */ + /* globals addMessageListener, sendAsyncMessage, docShell */ "use strict"; const { utils: Cu } = Components; diff --git a/devtools/shared/touch/simulator-core.js b/devtools/shared/touch/simulator-core.js index 6933f9207cbd..52ff5c124df2 100644 --- a/devtools/shared/touch/simulator-core.js +++ b/devtools/shared/touch/simulator-core.js @@ -1,6 +1,9 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* global XPCNativeWrapper */ + "use strict"; const { Ci, Cu } = require("chrome"); @@ -272,12 +275,14 @@ SimulatorCore.prototype = { } } let unwrapped = XPCNativeWrapper.unwrap(target); + /* eslint-disable no-inline-comments */ unwrapped.sendTouchEvent(name, clone([0]), // event type, id clone([evt.clientX]), // x clone([evt.clientY]), // y clone([1]), clone([1]), // rx, ry clone([0]), clone([0]), // rotation, force 1); // count + /* eslint-enable no-inline-comments */ return; } let document = target.ownerDocument; @@ -339,10 +344,10 @@ SimulatorCore.prototype = { let utils = content.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); - let allowZoom = {}, - minZoom = {}, - maxZoom = {}, - autoSize = {}; + let allowZoom = {}; + let minZoom = {}; + let maxZoom = {}; + let autoSize = {}; utils.getViewportInfo(content.innerWidth, content.innerHeight, {}, allowZoom, minZoom, maxZoom, {}, {}, autoSize); @@ -352,14 +357,15 @@ SimulatorCore.prototype = { // delay. But Firefox didn't support this property now, we can't get // this value from utils.getVisitedDependentComputedStyle() to check // if we should suppress 300ms delay. + /* eslint-disable no-inline-comments */ if (!allowZoom.value || // user-scalable = no minZoom.value === maxZoom.value || // minimum-scale = maximum-scale autoSize.value // width = device-width ) { + /* eslint-enable no-inline-comments */ return 0; - } else { - return 300; } + return 300; } }; From 7be77921c00ca47bae030b98556b691452d2aad2 Mon Sep 17 00:00:00 2001 From: JW Wang Date: Thu, 22 Dec 2016 17:28:14 +0800 Subject: [PATCH 145/229] Bug 1325321 - let DecodingState handle audio/video pop events. r=kaku MozReview-Commit-ID: 9EjeOfn1vBU --HG-- extra : rebase_source : 52efab5c60df935de35fb049926c639aa053e389 extra : intermediate-source : d760746364b9585128a74bf284246418eb024280 extra : source : 0537651366abb8524a3436f0208d28b3248a1c52 --- dom/media/MediaDecoderStateMachine.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/dom/media/MediaDecoderStateMachine.cpp b/dom/media/MediaDecoderStateMachine.cpp index 51779615c9b1..356ac26e7eb9 100644 --- a/dom/media/MediaDecoderStateMachine.cpp +++ b/dom/media/MediaDecoderStateMachine.cpp @@ -556,6 +556,8 @@ public: SLOG("Exiting DECODING, decoded for %.3lfs", decodeDuration.ToSeconds()); } mDormantTimer.Reset(); + mOnAudioPopped.DisconnectIfExists(); + mOnVideoPopped.DisconnectIfExists(); } void Step() override @@ -751,6 +753,9 @@ private: // Fired when playback is paused for a while to enter dormant. DelayedScheduler mDormantTimer; + + MediaEventListener mOnAudioPopped; + MediaEventListener mOnVideoPopped; }; /** @@ -1989,6 +1994,15 @@ DecodingState::Enter() return; } + mOnAudioPopped = AudioQueue().PopEvent().Connect( + OwnerThread(), [this] () { + mMaster->DispatchAudioDecodeTaskIfNeeded(); + }); + mOnVideoPopped = VideoQueue().PopEvent().Connect( + OwnerThread(), [this] () { + mMaster->DispatchVideoDecodeTaskIfNeeded(); + }); + mMaster->UpdateNextFrameStatus(MediaDecoderOwner::NEXT_FRAME_AVAILABLE); mDecodeStartTime = TimeStamp::Now(); @@ -2615,9 +2629,7 @@ void MediaDecoderStateMachine::OnAudioPopped(const RefPtr& aSample) { MOZ_ASSERT(OnTaskQueue()); - mPlaybackOffset = std::max(mPlaybackOffset.Ref(), aSample->mOffset); - DispatchAudioDecodeTaskIfNeeded(); } void @@ -2625,7 +2637,6 @@ MediaDecoderStateMachine::OnVideoPopped(const RefPtr& aSample) { MOZ_ASSERT(OnTaskQueue()); mPlaybackOffset = std::max(mPlaybackOffset.Ref(), aSample->mOffset); - DispatchVideoDecodeTaskIfNeeded(); } bool From 3985fd720866507db2beb5455467d27b0d362357 Mon Sep 17 00:00:00 2001 From: JW Wang Date: Fri, 23 Dec 2016 19:17:11 +0800 Subject: [PATCH 146/229] Bug 1326330. Part 1 - remove unused functions. r=JamesCheng MozReview-Commit-ID: 66XDaghbKUy --HG-- extra : rebase_source : a25d3413d6f076366373b92fd51ff850bb1dd79e extra : intermediate-source : a9f7a68b4bff23ec0a059f5cc2a7fca92c1501bd extra : source : d2dbc97390bc85fba1bd0a53d780f6122cc96ac7 --- dom/media/MediaQueue.h | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/dom/media/MediaQueue.h b/dom/media/MediaQueue.h index ecbf1c7f52f3..245139eb94ce 100644 --- a/dom/media/MediaQueue.h +++ b/dom/media/MediaQueue.h @@ -50,13 +50,6 @@ public: mPushEvent.Notify(RefPtr(aItem)); } - inline void PushFront(T* aItem) { - ReentrantMonitorAutoEnter mon(mReentrantMonitor); - MOZ_ASSERT(aItem); - NS_ADDREF(aItem); - nsDeque::PushFront(aItem); - } - inline already_AddRefed PopFront() { ReentrantMonitorAutoEnter mon(mReentrantMonitor); RefPtr rv = dont_AddRef(static_cast(nsDeque::PopFront())); @@ -66,11 +59,6 @@ public: return rv.forget(); } - inline RefPtr Peek() const { - ReentrantMonitorAutoEnter mon(mReentrantMonitor); - return static_cast(nsDeque::Peek()); - } - inline RefPtr PeekFront() const { ReentrantMonitorAutoEnter mon(mReentrantMonitor); return static_cast(nsDeque::PeekFront()); From 4eb1252534ad422736a2af98496aee3bb72fbdae Mon Sep 17 00:00:00 2001 From: JW Wang Date: Fri, 23 Dec 2016 19:19:04 +0800 Subject: [PATCH 147/229] Bug 1326330. Part 2 - add assertions and checks. r=JamesCheng 1. ensure the 'finish' event is notified only once. 2. assert pushing items to a finished queue. MozReview-Commit-ID: 9lYWPANVz0m --HG-- extra : rebase_source : c05b0c77fdee324798579e0e2ebec6ce6303cbf6 extra : intermediate-source : 80be35003c76fc9cc74f206576394b46317b7880 extra : source : 14f5d5c064fddbbcf5728fb4d19e9c0a4e45fac7 --- dom/media/MediaQueue.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/dom/media/MediaQueue.h b/dom/media/MediaQueue.h index 245139eb94ce..b98b887ec55e 100644 --- a/dom/media/MediaQueue.h +++ b/dom/media/MediaQueue.h @@ -43,6 +43,7 @@ public: inline void Push(T* aItem) { ReentrantMonitorAutoEnter mon(mReentrantMonitor); + MOZ_ASSERT(!mEndOfStream); MOZ_ASSERT(aItem); NS_ADDREF(aItem); MOZ_ASSERT(aItem->GetEndTime() >= aItem->mTime); @@ -88,8 +89,10 @@ public: // Informs the media queue that it won't be receiving any more items. void Finish() { ReentrantMonitorAutoEnter mon(mReentrantMonitor); - mEndOfStream = true; - mFinishEvent.Notify(); + if (!mEndOfStream) { + mEndOfStream = true; + mFinishEvent.Notify(); + } } // Returns the approximate number of microseconds of items in the queue. From 767b9e9306d2ca91fad1e7ba8bd4aa750183cd5e Mon Sep 17 00:00:00 2001 From: Joel Maher Date: Fri, 30 Dec 2016 12:30:17 -0500 Subject: [PATCH 148/229] Bug 1253155 - remove test_saved_stacks.js as it isn't useful. r=fitzgen MozReview-Commit-ID: FLBM9k6jpn6 --- tools/profiler/moz.build | 3 + tools/profiler/tests/test_saved_stacks.js | 69 ----------------------- tools/profiler/tests/xpcshell.ini | 3 +- 3 files changed, 4 insertions(+), 71 deletions(-) delete mode 100644 tools/profiler/tests/test_saved_stacks.js diff --git a/tools/profiler/moz.build b/tools/profiler/moz.build index 3c446b0d46d5..b12eacbc6cc5 100644 --- a/tools/profiler/moz.build +++ b/tools/profiler/moz.build @@ -150,3 +150,6 @@ if CONFIG['GNU_CXX']: '-Wno-error=shadow', '-Wno-ignored-qualifiers', # due to use of breakpad headers ] + +with Files('**'): + BUG_COMPONENT = ('Core', 'Gecko Profiler') diff --git a/tools/profiler/tests/test_saved_stacks.js b/tools/profiler/tests/test_saved_stacks.js deleted file mode 100644 index c8852768cfd8..000000000000 --- a/tools/profiler/tests/test_saved_stacks.js +++ /dev/null @@ -1,69 +0,0 @@ -// Test that we get `js::SavedStacks::saveCurrentStack` frames. - -function run_test() { - let p = Cc["@mozilla.org/tools/profiler;1"]; - // Just skip the test if the profiler component isn't present. - if (!p) - return; - p = p.getService(Ci.nsIProfiler); - if (!p) - return; - - const { saveStack } = Cu.getJSTestingFunctions(); - - const ms = 5; - p.StartProfiler(100, ms, ["js"], 1); - - let then = Date.now(); - while (Date.now() - then < 30000) { - function a() { - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - saveStack(); - } - - a(); - a(); - a(); - a(); - a(); - - function b() { - a(); - } - - b(); - b(); - b(); - b(); - b(); - } - - var profile = p.getProfileData().threads[0]; - - do_check_neq(profile.samples.data.length, 0); - - let found = false; - for (let sample of profile.samples.data) { - const stack = getInflatedStackLocations(profile, sample); - for (let frame of stack) { - if (frame.indexOf("js::SavedStacks::saveCurrentStack") >= 0) { - found = true; - break; - } - } - } - do_check_true(found); - - p.StopProfiler(); -} diff --git a/tools/profiler/tests/xpcshell.ini b/tools/profiler/tests/xpcshell.ini index 2726ae3d354f..997a7c142ad0 100644 --- a/tools/profiler/tests/xpcshell.ini +++ b/tools/profiler/tests/xpcshell.ini @@ -15,5 +15,4 @@ skip-if = true skip-if = !debug [test_enterjit_osr_enabling.js] skip-if = !debug -[test_asm.js] -[test_saved_stacks.js] +[test_asm.js] \ No newline at end of file From 706f1d717e4c8e07bff5b5dda01542bbe205e24a Mon Sep 17 00:00:00 2001 From: cku Date: Fri, 30 Dec 2016 03:35:36 +0800 Subject: [PATCH 149/229] Bug 1314001 - (followup) give different color to different kind of mask. r=me MozReview-Commit-ID: 5NtefGdSrUT --HG-- extra : rebase_source : 2f1cbf149e6baa42829c6f50cb81c682865e2e81 --- layout/svg/nsSVGIntegrationUtils.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/layout/svg/nsSVGIntegrationUtils.cpp b/layout/svg/nsSVGIntegrationUtils.cpp index 07d37e3cdcf8..514c45d37a4e 100644 --- a/layout/svg/nsSVGIntegrationUtils.cpp +++ b/layout/svg/nsSVGIntegrationUtils.cpp @@ -1027,7 +1027,20 @@ nsSVGIntegrationUtils::PaintMaskAndClipPath(const PaintFramesParams& aParams) nsLayoutUtils::RectToGfxRect(aParams.borderArea, frame->PresContext()->AppUnitsPerDevPixel()); context.Rectangle(drawingRect, true); - context.SetColor(Color(0.0, 1.0, 0.0, 1.0)); + Color overlayColor(0.0f, 0.0f, 0.0f, 0.8f); + if (maskUsage.shouldGenerateMaskLayer) { + overlayColor.r = 1.0f; // red represents css positioned mask. + } + if (maskUsage.shouldApplyClipPath || + maskUsage.shouldGenerateClipMaskLayer) { + overlayColor.g = 1.0f; // green represents clip-path:. + } + if (maskUsage.shouldApplyBasicShape) { + overlayColor.b = 1.0f; // blue represents + // clip-path:||. + } + + context.SetColor(overlayColor); context.Fill(); } From 1a2e2404c4a2f3190a0f5b9ff9e26de14dd1adb4 Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Fri, 30 Dec 2016 10:56:57 -0800 Subject: [PATCH 150/229] Backed out changeset 263b1b07c2ac (bug 1325651) for being a possible cause of valgrind leaks a=backout --- dom/ipc/ContentParent.cpp | 1 - dom/ipc/URLClassifierParent.cpp | 2 -- 2 files changed, 3 deletions(-) diff --git a/dom/ipc/ContentParent.cpp b/dom/ipc/ContentParent.cpp index a43571de96d3..86d09cfd8bef 100644 --- a/dom/ipc/ContentParent.cpp +++ b/dom/ipc/ContentParent.cpp @@ -4793,7 +4793,6 @@ ContentParent::RecvPURLClassifierConstructor(PURLClassifierParent* aActor, { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(aActor); - *aSuccess = false; auto* actor = static_cast(aActor); nsCOMPtr principal(aPrincipal); diff --git a/dom/ipc/URLClassifierParent.cpp b/dom/ipc/URLClassifierParent.cpp index 987ee59395f5..816802e9b962 100644 --- a/dom/ipc/URLClassifierParent.cpp +++ b/dom/ipc/URLClassifierParent.cpp @@ -18,7 +18,6 @@ URLClassifierParent::StartClassify(nsIPrincipal* aPrincipal, bool aUseTrackingProtection, bool* aSuccess) { - *aSuccess = false; nsresult rv = NS_OK; // Note that in safe mode, the URL classifier service isn't available, so we // should handle the service not being present gracefully. @@ -35,7 +34,6 @@ URLClassifierParent::StartClassify(nsIPrincipal* aPrincipal, // without ever calling out callback in both cases. // This means that code using this in the child process will only get a hit // on its callback if some classification actually happens. - *aSuccess = false; ClassificationFailed(); } return IPC_OK(); From d857328fb127db47dc561df4e7c82c0e3011828b Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Fri, 30 Dec 2016 10:57:11 -0800 Subject: [PATCH 151/229] Backed out changeset fd09b9651dc6 (bug 1324492) for being a possible cause of valgrind leaks a=backout --- taskcluster/docker/centos6-build-upd/Dockerfile | 2 +- taskcluster/docker/centos6-build-upd/VERSION | 2 +- taskcluster/docker/centos6-build/VERSION | 2 +- .../docker/centos6-build/system-setup.sh | 17 +---------------- taskcluster/docker/desktop-build/Dockerfile | 2 +- 5 files changed, 5 insertions(+), 20 deletions(-) diff --git a/taskcluster/docker/centos6-build-upd/Dockerfile b/taskcluster/docker/centos6-build-upd/Dockerfile index 0b8800bb64c8..a245bcbe54b5 100644 --- a/taskcluster/docker/centos6-build-upd/Dockerfile +++ b/taskcluster/docker/centos6-build-upd/Dockerfile @@ -1,4 +1,4 @@ -FROM taskcluster/centos6-build:0.1.7 +FROM taskcluster/centos6-build:0.1.6 MAINTAINER Dustin J. Mitchell ### update to latest from upstream repositories diff --git a/taskcluster/docker/centos6-build-upd/VERSION b/taskcluster/docker/centos6-build-upd/VERSION index eb4d30ac6b70..01ae56f9e52a 100644 --- a/taskcluster/docker/centos6-build-upd/VERSION +++ b/taskcluster/docker/centos6-build-upd/VERSION @@ -1 +1 @@ -0.1.7.20161229150900 +0.1.6.20160329195300 diff --git a/taskcluster/docker/centos6-build/VERSION b/taskcluster/docker/centos6-build/VERSION index 11808190d4b9..c946ee6160c2 100644 --- a/taskcluster/docker/centos6-build/VERSION +++ b/taskcluster/docker/centos6-build/VERSION @@ -1 +1 @@ -0.1.7 +0.1.6 diff --git a/taskcluster/docker/centos6-build/system-setup.sh b/taskcluster/docker/centos6-build/system-setup.sh index 0353768056aa..ddb529eed735 100644 --- a/taskcluster/docker/centos6-build/system-setup.sh +++ b/taskcluster/docker/centos6-build/system-setup.sh @@ -268,6 +268,7 @@ install xvinfo install patch install libuuid-devel install openssl-static +install cmake install subversion run EOF @@ -428,22 +429,6 @@ peep install -r requirements.txt # TC-VCS npm install -g taskcluster-vcs@2.3.18 -# CMake 3.7.1 -cd $BUILD -tooltool_fetch <<'EOF' -[ -{ - "size": 7361172, - "digest": "0539d70ce3ac77042a45d638443b09fbf368e253622db980bc6fb15988743eacd031ab850a45c821ec3e9f0f5f886b9c9cb0668aeda184cd457b78abbfe7b629", - "algorithm": "sha512", - "filename": "cmake-3.7.1.tar.gz", - "unpack": true -} -] -EOF -cd cmake-3.7.1 -./bootstrap && make install - # Ninja cd $BUILD tooltool_fetch <<'EOF' diff --git a/taskcluster/docker/desktop-build/Dockerfile b/taskcluster/docker/desktop-build/Dockerfile index 037495be5795..66fe30ff0c3e 100644 --- a/taskcluster/docker/desktop-build/Dockerfile +++ b/taskcluster/docker/desktop-build/Dockerfile @@ -1,5 +1,5 @@ # TODO remove VOLUME below when the base image is updated next. -FROM taskcluster/centos6-build-upd:0.1.7.20161229150900 +FROM taskcluster/centos6-build-upd:0.1.6.20160329195300 MAINTAINER Dustin J. Mitchell # TODO remove when base image is updated From d823573e34aa25e2bc691945e54598ae34c254af Mon Sep 17 00:00:00 2001 From: Kris Maglione Date: Sat, 24 Dec 2016 18:24:41 -0800 Subject: [PATCH 152/229] Bug 1325158: Part 1 - Don't return error result from OnRedirectVerifyCallback. r=ehsan MozReview-Commit-ID: Hb3I0U8kxdz --HG-- extra : rebase_source : 447f2e11e9e3f59f984de56689681780d85b7bd3 --- dom/xhr/XMLHttpRequestMainThread.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dom/xhr/XMLHttpRequestMainThread.cpp b/dom/xhr/XMLHttpRequestMainThread.cpp index 7bd4a247294b..9a5f417209f2 100644 --- a/dom/xhr/XMLHttpRequestMainThread.cpp +++ b/dom/xhr/XMLHttpRequestMainThread.cpp @@ -3381,7 +3381,10 @@ XMLHttpRequestMainThread::OnRedirectVerifyCallback(nsresult result) mRedirectCallback->OnRedirectVerifyCallback(result); mRedirectCallback = nullptr; - return result; + // It's important that we return success here. If we return the result code + // that we were passed, JavaScript callers who cancel the redirect will wind + // up throwing an exception in the process. + return NS_OK; } ///////////////////////////////////////////////////// From 9822075cb512f469cd524276ba1cf4c51b65c7a1 Mon Sep 17 00:00:00 2001 From: Kris Maglione Date: Sat, 24 Dec 2016 18:26:03 -0800 Subject: [PATCH 153/229] Bug 1325158: Part 3 - Don't create a reference cycle via HTTP channel property bag. r=mixedpuppy MozReview-Commit-ID: 40Ox7BDlgwy --HG-- extra : rebase_source : 1ad1f43b7da1bb0be3b04814347396fc29fbb4f6 --- toolkit/modules/addons/WebRequest.jsm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/toolkit/modules/addons/WebRequest.jsm b/toolkit/modules/addons/WebRequest.jsm index a84a990461bf..c720dae5da73 100644 --- a/toolkit/modules/addons/WebRequest.jsm +++ b/toolkit/modules/addons/WebRequest.jsm @@ -813,14 +813,14 @@ HttpObserverManager = { // Check whether we've already added a listener to this channel, // so we don't wind up chaining multiple listeners. let channelData = getData(channel); - if (!channelData.listener && channel instanceof Ci.nsITraceableChannel) { + if (!channelData.hasListener && channel instanceof Ci.nsITraceableChannel) { let responseStatus = channel.responseStatus; // skip redirections, https://bugzilla.mozilla.org/show_bug.cgi?id=728901#c8 if (responseStatus < 300 || responseStatus >= 400) { let listener = new StartStopListener(this, loadContext); let orig = channel.setNewListener(listener); listener.orig = orig; - channelData.listener = listener; + channelData.hasListener = true; } } } From b4d3f79ec3dcbd1c8d487103413383bed3f3f345 Mon Sep 17 00:00:00 2001 From: Kris Maglione Date: Sat, 24 Dec 2016 18:48:56 -0800 Subject: [PATCH 154/229] Bug 1325158: Part 4 - Fix cases where extension startup listener is not removed. r=aswan MozReview-Commit-ID: FIhGYSDoOhW --HG-- extra : rebase_source : baa8c9f409da54c06cea5fac4dfa6462e2a06697 --- .../content/SpecialPowersObserverAPI.js | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/testing/specialpowers/content/SpecialPowersObserverAPI.js b/testing/specialpowers/content/SpecialPowersObserverAPI.js index d3137a42d45c..9d2f194a19f7 100644 --- a/testing/specialpowers/content/SpecialPowersObserverAPI.js +++ b/testing/specialpowers/content/SpecialPowersObserverAPI.js @@ -544,17 +544,13 @@ SpecialPowersObserverAPI.prototype = { } case "SPStartupExtension": { - let {ExtensionData, Management} = Components.utils.import("resource://gre/modules/Extension.jsm", {}); + let {ExtensionData} = Components.utils.import("resource://gre/modules/Extension.jsm", {}); let id = aMessage.data.id; let extension = this._extensions.get(id); - let startupListener = (msg, ext) => { - if (ext == extension) { - this._sendReply(aMessage, "SPExtensionMessage", {id, type: "extensionSetId", args: [extension.id]}); - Management.off("startup", startupListener); - } - }; - Management.on("startup", startupListener); + extension.on("startup", () => { + this._sendReply(aMessage, "SPExtensionMessage", {id, type: "extensionSetId", args: [extension.id]}); + }); // Make sure the extension passes the packaging checks when // they're run on a bare archive rather than a running instance, @@ -579,7 +575,6 @@ SpecialPowersObserverAPI.prototype = { this._sendReply(aMessage, "SPExtensionMessage", {id, type: "extensionStarted", args: []}); }).catch(e => { dump(`Extension startup failed: ${e}\n${e.stack}`); - Management.off("startup", startupListener); this._sendReply(aMessage, "SPExtensionMessage", {id, type: "extensionFailed", args: []}); }); return undefined; From 6ac54a1574fc7039803e6de5c44ccc20a534ecae Mon Sep 17 00:00:00 2001 From: Phil Ringnalda Date: Thu, 29 Dec 2016 19:01:37 -0800 Subject: [PATCH 155/229] Backed out changeset 67611ffb1fef (bug 1325213) for failures in test_require_lazy.js --- .eslintignore | 10 + devtools/shared/client/connection-manager.js | 22 +- devtools/shared/client/main.js | 1310 ++++++++--------- devtools/shared/discovery/discovery.js | 22 +- .../shared/discovery/tests/unit/.eslintrc.js | 6 - .../discovery/tests/unit/test_discovery.js | 1 + .../shared/performance/recording-common.js | 86 +- .../shared/performance/recording-utils.js | 7 +- devtools/shared/performance/test/.eslintrc.js | 6 - devtools/shared/performance/test/head.js | 5 +- .../test_perf-utils-allocations-to-samples.js | 14 +- devtools/shared/qrcode/index.js | 1 + .../shared/qrcode/tests/unit/.eslintrc.js | 6 - devtools/shared/security/auth.js | 10 +- devtools/shared/security/cert.js | 1 + devtools/shared/security/socket.js | 10 +- .../shared/security/tests/chrome/.eslintrc.js | 6 - .../chrome/test_websocket-transport.html | 8 +- .../shared/security/tests/unit/head_dbg.js | 56 +- .../security/tests/unit/test_oob_cert_auth.js | 12 +- .../shared/security/tests/unit/testactors.js | 34 +- devtools/shared/shims/event-emitter.js | 9 +- .../tests/browser/browser_async_storage.js | 2 +- devtools/shared/tests/unit/exposeLoader.js | 2 - devtools/shared/tests/unit/head_devtools.js | 34 +- devtools/shared/tests/unit/test_assert.js | 5 +- .../shared/tests/unit/test_async-utils.js | 16 +- .../tests/unit/test_console_filtering.js | 20 +- .../unit/test_defineLazyPrototypeGetter.js | 4 +- .../shared/tests/unit/test_executeSoon.js | 1 + devtools/shared/tests/unit/test_flatten.js | 2 - .../tests/unit/test_independent_loaders.js | 2 - devtools/shared/tests/unit/test_isSet.js | 2 - devtools/shared/tests/unit/test_require.js | 2 - .../shared/tests/unit/test_require_lazy.js | 5 +- .../shared/tests/unit/test_require_raw.js | 2 - .../shared/tests/unit/test_safeErrorString.js | 2 - devtools/shared/tests/unit/test_stack.js | 2 - devtools/shared/touch/simulator-content.js | 2 +- devtools/shared/touch/simulator-core.js | 18 +- 40 files changed, 798 insertions(+), 967 deletions(-) delete mode 100644 devtools/shared/discovery/tests/unit/.eslintrc.js delete mode 100644 devtools/shared/performance/test/.eslintrc.js delete mode 100644 devtools/shared/qrcode/tests/unit/.eslintrc.js delete mode 100644 devtools/shared/security/tests/chrome/.eslintrc.js diff --git a/.eslintignore b/.eslintignore index c678180d573a..a676a160e1c7 100644 --- a/.eslintignore +++ b/.eslintignore @@ -117,10 +117,20 @@ devtools/server/tests/browser/** devtools/server/tests/mochitest/** devtools/server/tests/unit/** devtools/shared/apps/** +devtools/shared/client/** +devtools/shared/discovery/** devtools/shared/gcli/** !devtools/shared/gcli/templater.js devtools/shared/heapsnapshot/** devtools/shared/layout/** +devtools/shared/performance/** +!devtools/shared/platform/** +devtools/shared/qrcode/** +devtools/shared/security/** +devtools/shared/shims/** +devtools/shared/tests/** +!devtools/shared/tests/unit/test_csslexer.js +devtools/shared/touch/** devtools/shared/transport/** !devtools/shared/transport/transport.js !devtools/shared/transport/websocket-transport.js diff --git a/devtools/shared/client/connection-manager.js b/devtools/shared/client/connection-manager.js index 6b6a1e5e85c9..ef242db85302 100644 --- a/devtools/shared/client/connection-manager.js +++ b/devtools/shared/client/connection-manager.js @@ -6,8 +6,9 @@ "use strict"; -const {Cc, Ci, Cr} = require("chrome"); +const {Cc, Ci, Cu, Cr} = require("chrome"); const EventEmitter = require("devtools/shared/event-emitter"); +const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/main"); const Services = require("Services"); @@ -69,10 +70,8 @@ const REMOTE_TIMEOUT = "devtools.debugger.remote-timeout"; * . Connection.Events.CONNECTING Trying to connect to host:port * . Connection.Events.CONNECTED Connection is successful * . Connection.Events.DISCONNECTING Trying to disconnect from server - * . Connection.Events.DISCONNECTED Disconnected (at client request, - * or because of a timeout or connection error) - * . Connection.Events.STATUS_CHANGED The connection status (connection.status) - * has changed + * . Connection.Events.DISCONNECTED Disconnected (at client request, or because of a timeout or connection error) + * . Connection.Events.STATUS_CHANGED The connection status (connection.status) has changed * . Connection.Events.TIMEOUT Connection timeout * . Connection.Events.HOST_CHANGED Host has changed * . Connection.Events.PORT_CHANGED Port has changed @@ -169,9 +168,8 @@ Connection.prototype = { }, set host(value) { - if (this._host && this._host == value) { + if (this._host && this._host == value) return; - } this._host = value; this.emit(Connection.Events.HOST_CHANGED); }, @@ -181,9 +179,8 @@ Connection.prototype = { }, set port(value) { - if (this._port && this._port == value) { + if (this._port && this._port == value) return; - } this._port = value; this.emit(Connection.Events.PORT_CHANGED); }, @@ -337,9 +334,8 @@ Connection.prototype = { }, _setStatus: function (value) { - if (this._status && this._status == value) { + if (this._status && this._status == value) return; - } this._status = value; this.emit(value); this.emit(Connection.Events.STATUS_CHANGED, value); @@ -361,9 +357,7 @@ Connection.prototype = { this.log("disconnected (unexpected)"); break; case Connection.Status.CONNECTING: - this.log("connection error. Possible causes: USB port not connected, port not " + - "forwarded (adb forward), wrong host or port, remote debugging not " + - "enabled on the device."); + this.log("connection error. Possible causes: USB port not connected, port not forwarded (adb forward), wrong host or port, remote debugging not enabled on the device."); break; default: this.log("disconnected"); diff --git a/devtools/shared/client/main.js b/devtools/shared/client/main.js index b1e3295aff64..408c0b277edc 100644 --- a/devtools/shared/client/main.js +++ b/devtools/shared/client/main.js @@ -7,6 +7,7 @@ "use strict"; const { Ci, Cu } = require("chrome"); +const Services = require("Services"); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const { getStack, callFunctionWithAsyncStack } = require("devtools/shared/platform/stack"); @@ -27,22 +28,22 @@ const noop = () => {}; * augmented with the necessary facilities by passing its prototype to this * function. * - * @param proto object + * @param aProto object * The prototype object that will be modified. */ -function eventSource(proto) { +function eventSource(aProto) { /** * Add a listener to the event source for a given event. * - * @param name string + * @param aName string * The event to listen for. - * @param listener function + * @param aListener function * Called when the event is fired. If the same listener * is added more than once, it will be called once per * addListener call. */ - proto.addListener = function (name, listener) { - if (typeof listener != "function") { + aProto.addListener = function (aName, aListener) { + if (typeof aListener != "function") { throw TypeError("Listeners must be functions."); } @@ -50,46 +51,47 @@ function eventSource(proto) { this._listeners = {}; } - this._getListeners(name).push(listener); + this._getListeners(aName).push(aListener); }; /** * Add a listener to the event source for a given event. The * listener will be removed after it is called for the first time. * - * @param name string + * @param aName string * The event to listen for. - * @param listener function + * @param aListener function * Called when the event is fired. */ - proto.addOneTimeListener = function (name, listener) { + aProto.addOneTimeListener = function (aName, aListener) { let l = (...args) => { - this.removeListener(name, l); - listener.apply(null, args); + this.removeListener(aName, l); + aListener.apply(null, args); }; - this.addListener(name, l); + this.addListener(aName, l); }; /** * Remove a listener from the event source previously added with * addListener(). * - * @param name string + * @param aName string * The event name used during addListener to add the listener. - * @param listener function + * @param aListener function * The callback to remove. If addListener was called multiple * times, all instances will be removed. */ - proto.removeListener = function (name, listener) { - if (!this._listeners || (listener && !this._listeners[name])) { + aProto.removeListener = function (aName, aListener) { + if (!this._listeners || (aListener && !this._listeners[aName])) { return; } - if (!listener) { - this._listeners[name] = []; - } else { - this._listeners[name] = - this._listeners[name].filter(l => l != listener); + if (!aListener) { + this._listeners[aName] = []; + } + else { + this._listeners[aName] = + this._listeners[aName].filter(function (l) { return l != aListener; }); } }; @@ -97,27 +99,27 @@ function eventSource(proto) { * Returns the listeners for the specified event name. If none are defined it * initializes an empty list and returns that. * - * @param name string + * @param aName string * The event name. */ - proto._getListeners = function (name) { - if (name in this._listeners) { - return this._listeners[name]; + aProto._getListeners = function (aName) { + if (aName in this._listeners) { + return this._listeners[aName]; } - this._listeners[name] = []; - return this._listeners[name]; + this._listeners[aName] = []; + return this._listeners[aName]; }; /** * Notify listeners of an event. * - * @param name string + * @param aName string * The event to fire. * @param arguments * All arguments will be passed along to the listeners, * including the name argument. */ - proto.emit = function () { + aProto.emit = function () { if (!this._listeners) { return; } @@ -200,8 +202,9 @@ const UnsolicitedPauses = { * provides the means to communicate with the server and exchange the messages * required by the protocol in a traditional JavaScript API. */ -const DebuggerClient = exports.DebuggerClient = function (transport) { - this._transport = transport; +const DebuggerClient = exports.DebuggerClient = function (aTransport) +{ + this._transport = aTransport; this._transport.hooks = this; // Map actor ID to client instance for each actor type. @@ -221,18 +224,18 @@ const DebuggerClient = exports.DebuggerClient = function (transport) { * the connection's root actor. */ this.mainRoot = null; - this.expectReply("root", (packet) => { - this.mainRoot = new RootClient(this, packet); - this.emit("connected", packet.applicationType, packet.traits); + this.expectReply("root", (aPacket) => { + this.mainRoot = new RootClient(this, aPacket); + this.emit("connected", aPacket.applicationType, aPacket.traits); }); }; /** * A declarative helper for defining methods that send requests to the server. * - * @param packetSkeleton + * @param aPacketSkeleton * The form of the packet to send. Can specify fields to be filled from - * the parameters by using the |arg| function. + * the parameters by using the |args| function. * @param before * The function to call before sending the packet. Is passed the packet, * and the return value is used as the new packet. The |this| context is @@ -246,21 +249,21 @@ const DebuggerClient = exports.DebuggerClient = function (transport) { * The `Request` object that is a Promise object and resolves once * we receive the response. (See request method for more details) */ -DebuggerClient.requester = function (packetSkeleton, config = {}) { +DebuggerClient.requester = function (aPacketSkeleton, config = {}) { let { before, after } = config; return DevToolsUtils.makeInfallible(function (...args) { let outgoingPacket = { - to: packetSkeleton.to || this.actor + to: aPacketSkeleton.to || this.actor }; let maxPosition = -1; - for (let k of Object.keys(packetSkeleton)) { - if (packetSkeleton[k] instanceof DebuggerClient.Argument) { - let { position } = packetSkeleton[k]; - outgoingPacket[k] = packetSkeleton[k].getArgument(args); + for (let k of Object.keys(aPacketSkeleton)) { + if (aPacketSkeleton[k] instanceof DebuggerClient.Argument) { + let { position } = aPacketSkeleton[k]; + outgoingPacket[k] = aPacketSkeleton[k].getArgument(args); maxPosition = Math.max(position, maxPosition); } else { - outgoingPacket[k] = packetSkeleton[k]; + outgoingPacket[k] = aPacketSkeleton[k]; } } @@ -268,37 +271,37 @@ DebuggerClient.requester = function (packetSkeleton, config = {}) { outgoingPacket = before.call(this, outgoingPacket); } - return this.request(outgoingPacket, DevToolsUtils.makeInfallible((response) => { + return this.request(outgoingPacket, DevToolsUtils.makeInfallible((aResponse) => { if (after) { - let { from } = response; - response = after.call(this, response); - if (!response.from) { - response.from = from; + let { from } = aResponse; + aResponse = after.call(this, aResponse); + if (!aResponse.from) { + aResponse.from = from; } } // The callback is always the last parameter. let thisCallback = args[maxPosition + 1]; if (thisCallback) { - thisCallback(response); + thisCallback(aResponse); } }, "DebuggerClient.requester request callback")); }, "DebuggerClient.requester"); }; -function arg(pos) { - return new DebuggerClient.Argument(pos); +function args(aPos) { + return new DebuggerClient.Argument(aPos); } -DebuggerClient.Argument = function (position) { - this.position = position; +DebuggerClient.Argument = function (aPosition) { + this.position = aPosition; }; -DebuggerClient.Argument.prototype.getArgument = function (params) { - if (!(this.position in params)) { +DebuggerClient.Argument.prototype.getArgument = function (aParams) { + if (!(this.position in aParams)) { throw new Error("Bad index into params: " + this.position); } - return params[this.position]; + return aParams[this.position]; }; // Expose these to save callers the trouble of importing DebuggerSocket @@ -317,7 +320,7 @@ DebuggerClient.prototype = { /** * Connect to the server and start exchanging protocol messages. * - * @param onConnected function + * @param aOnConnected function * If specified, will be called when the greeting packet is * received from the debugging server. * @@ -327,7 +330,7 @@ DebuggerClient.prototype = { * element is the traits object (help figure out the features * and behaviors of the server we connect to. See RootActor). */ - connect: function (onConnected) { + connect: function (aOnConnected) { let deferred = promise.defer(); this.emit("connect"); @@ -335,12 +338,12 @@ DebuggerClient.prototype = { // so it's possible to track all instances. events.emit(DebuggerClient, "connect", this); - this.addOneTimeListener("connected", (name, applicationType, traits) => { - this.traits = traits; - if (onConnected) { - onConnected(applicationType, traits); + this.addOneTimeListener("connected", (aName, aApplicationType, aTraits) => { + this.traits = aTraits; + if (aOnConnected) { + aOnConnected(aApplicationType, aTraits); } - deferred.resolve([applicationType, traits]); + deferred.resolve([aApplicationType, aTraits]); }); this._transport.ready(); @@ -350,17 +353,17 @@ DebuggerClient.prototype = { /** * Shut down communication with the debugging server. * - * @param onClosed function + * @param aOnClosed function * If specified, will be called when the debugging connection * has been closed. This parameter is deprecated - please use * the returned Promise. * @return Promise * Resolves after the underlying transport is closed. */ - close: function (onClosed) { + close: function (aOnClosed) { let deferred = promise.defer(); - if (onClosed) { - deferred.promise.then(onClosed); + if (aOnClosed) { + deferred.promise.then(aOnClosed); } // Disable detach event notifications, because event handlers will be in a @@ -410,206 +413,198 @@ DebuggerClient.prototype = { * This function exists only to preserve DebuggerClient's interface; * new code should say 'client.mainRoot.listTabs()'. */ - listTabs: function (onResponse) { - return this.mainRoot.listTabs(onResponse); - }, + listTabs: function (aOnResponse) { return this.mainRoot.listTabs(aOnResponse); }, /* * This function exists only to preserve DebuggerClient's interface; * new code should say 'client.mainRoot.listAddons()'. */ - listAddons: function (onResponse) { - return this.mainRoot.listAddons(onResponse); - }, + listAddons: function (aOnResponse) { return this.mainRoot.listAddons(aOnResponse); }, - getTab: function (filter) { - return this.mainRoot.getTab(filter); - }, + getTab: function (aFilter) { return this.mainRoot.getTab(aFilter); }, /** * Attach to a tab actor. * - * @param string tabActor + * @param string aTabActor * The actor ID for the tab to attach. - * @param function onResponse + * @param function aOnResponse * Called with the response packet and a TabClient * (which will be undefined on error). */ - attachTab: function (tabActor, onResponse = noop) { - if (this._clients.has(tabActor)) { - let cachedTab = this._clients.get(tabActor); + attachTab: function (aTabActor, aOnResponse = noop) { + if (this._clients.has(aTabActor)) { + let cachedTab = this._clients.get(aTabActor); let cachedResponse = { cacheDisabled: cachedTab.cacheDisabled, javascriptEnabled: cachedTab.javascriptEnabled, traits: cachedTab.traits, }; - DevToolsUtils.executeSoon(() => onResponse(cachedResponse, cachedTab)); + DevToolsUtils.executeSoon(() => aOnResponse(cachedResponse, cachedTab)); return promise.resolve([cachedResponse, cachedTab]); } let packet = { - to: tabActor, + to: aTabActor, type: "attach" }; - return this.request(packet).then(response => { + return this.request(packet).then(aResponse => { let tabClient; - if (!response.error) { - tabClient = new TabClient(this, response); + if (!aResponse.error) { + tabClient = new TabClient(this, aResponse); this.registerClient(tabClient); } - onResponse(response, tabClient); - return [response, tabClient]; + aOnResponse(aResponse, tabClient); + return [aResponse, tabClient]; }); }, - attachWorker: function (workerActor, onResponse = noop) { - let workerClient = this._clients.get(workerActor); + attachWorker: function DC_attachWorker(aWorkerActor, aOnResponse = noop) { + let workerClient = this._clients.get(aWorkerActor); if (workerClient !== undefined) { let response = { from: workerClient.actor, type: "attached", url: workerClient.url }; - DevToolsUtils.executeSoon(() => onResponse(response, workerClient)); + DevToolsUtils.executeSoon(() => aOnResponse(response, workerClient)); return promise.resolve([response, workerClient]); } - return this.request({ to: workerActor, type: "attach" }).then(response => { - if (response.error) { - onResponse(response, null); - return [response, null]; + return this.request({ to: aWorkerActor, type: "attach" }).then(aResponse => { + if (aResponse.error) { + aOnResponse(aResponse, null); + return [aResponse, null]; } - workerClient = new WorkerClient(this, response); + let workerClient = new WorkerClient(this, aResponse); this.registerClient(workerClient); - onResponse(response, workerClient); - return [response, workerClient]; + aOnResponse(aResponse, workerClient); + return [aResponse, workerClient]; }); }, /** * Attach to an addon actor. * - * @param string addonActor + * @param string aAddonActor * The actor ID for the addon to attach. - * @param function onResponse + * @param function aOnResponse * Called with the response packet and a AddonClient * (which will be undefined on error). */ - attachAddon: function (addonActor, onResponse = noop) { + attachAddon: function DC_attachAddon(aAddonActor, aOnResponse = noop) { let packet = { - to: addonActor, + to: aAddonActor, type: "attach" }; - return this.request(packet).then(response => { + return this.request(packet).then(aResponse => { let addonClient; - if (!response.error) { - addonClient = new AddonClient(this, addonActor); + if (!aResponse.error) { + addonClient = new AddonClient(this, aAddonActor); this.registerClient(addonClient); this.activeAddon = addonClient; } - onResponse(response, addonClient); - return [response, addonClient]; + aOnResponse(aResponse, addonClient); + return [aResponse, addonClient]; }); }, /** * Attach to a Web Console actor. * - * @param string consoleActor + * @param string aConsoleActor * The ID for the console actor to attach to. - * @param array listeners + * @param array aListeners * The console listeners you want to start. - * @param function onResponse + * @param function aOnResponse * Called with the response packet and a WebConsoleClient * instance (which will be undefined on error). */ attachConsole: - function (consoleActor, listeners, onResponse = noop) { + function (aConsoleActor, aListeners, aOnResponse = noop) { let packet = { - to: consoleActor, + to: aConsoleActor, type: "startListeners", - listeners: listeners, + listeners: aListeners, }; - return this.request(packet).then(response => { + return this.request(packet).then(aResponse => { let consoleClient; - if (!response.error) { - if (this._clients.has(consoleActor)) { - consoleClient = this._clients.get(consoleActor); + if (!aResponse.error) { + if (this._clients.has(aConsoleActor)) { + consoleClient = this._clients.get(aConsoleActor); } else { - consoleClient = new WebConsoleClient(this, response); + consoleClient = new WebConsoleClient(this, aResponse); this.registerClient(consoleClient); } } - onResponse(response, consoleClient); - return [response, consoleClient]; + aOnResponse(aResponse, consoleClient); + return [aResponse, consoleClient]; }); }, /** * Attach to a global-scoped thread actor for chrome debugging. * - * @param string threadActor + * @param string aThreadActor * The actor ID for the thread to attach. - * @param function onResponse + * @param function aOnResponse * Called with the response packet and a ThreadClient * (which will be undefined on error). - * @param object options + * @param object aOptions * Configuration options. * - useSourceMaps: whether to use source maps or not. */ - attachThread: function (threadActor, onResponse = noop, options = {}) { - if (this._clients.has(threadActor)) { - let client = this._clients.get(threadActor); - DevToolsUtils.executeSoon(() => onResponse({}, client)); + attachThread: function (aThreadActor, aOnResponse = noop, aOptions = {}) { + if (this._clients.has(aThreadActor)) { + let client = this._clients.get(aThreadActor); + DevToolsUtils.executeSoon(() => aOnResponse({}, client)); return promise.resolve([{}, client]); } let packet = { - to: threadActor, + to: aThreadActor, type: "attach", - options, + options: aOptions }; - return this.request(packet).then(response => { - let threadClient; - if (!response.error) { - threadClient = new ThreadClient(this, threadActor); + return this.request(packet).then(aResponse => { + if (!aResponse.error) { + var threadClient = new ThreadClient(this, aThreadActor); this.registerClient(threadClient); } - onResponse(response, threadClient); - return [response, threadClient]; + aOnResponse(aResponse, threadClient); + return [aResponse, threadClient]; }); }, /** * Attach to a trace actor. * - * @param string traceActor + * @param string aTraceActor * The actor ID for the tracer to attach. - * @param function onResponse + * @param function aOnResponse * Called with the response packet and a TraceClient * (which will be undefined on error). */ - attachTracer: function (traceActor, onResponse = noop) { - if (this._clients.has(traceActor)) { - let client = this._clients.get(traceActor); - DevToolsUtils.executeSoon(() => onResponse({}, client)); + attachTracer: function (aTraceActor, aOnResponse = noop) { + if (this._clients.has(aTraceActor)) { + let client = this._clients.get(aTraceActor); + DevToolsUtils.executeSoon(() => aOnResponse({}, client)); return promise.resolve([{}, client]); } let packet = { - to: traceActor, + to: aTraceActor, type: "attach" }; - return this.request(packet).then(response => { - let traceClient; - if (!response.error) { - traceClient = new TraceClient(this, traceActor); + return this.request(packet).then(aResponse => { + if (!aResponse.error) { + var traceClient = new TraceClient(this, aTraceActor); this.registerClient(traceClient); } - onResponse(response, traceClient); - return [response, traceClient]; + aOnResponse(aResponse, traceClient); + return [aResponse, traceClient]; }); }, @@ -617,17 +612,17 @@ DebuggerClient.prototype = { * Fetch the ChromeActor for the main process or ChildProcessActor for a * a given child process ID. * - * @param number id + * @param number aId * The ID for the process to attach (returned by `listProcesses`). * Connected to the main process if omitted, or is 0. */ - getProcess: function (id) { + getProcess: function (aId) { let packet = { to: "root", type: "getProcess" }; - if (typeof (id) == "number") { - packet.id = id; + if (typeof (aId) == "number") { + packet.id = aId; } return this.request(packet); }, @@ -635,23 +630,23 @@ DebuggerClient.prototype = { /** * Release an object actor. * - * @param string actor + * @param string aActor * The actor ID to send the request to. - * @param onResponse function + * @param aOnResponse function * If specified, will be called with the response packet when * debugging server responds. */ release: DebuggerClient.requester({ - to: arg(0), + to: args(0), type: "release" }), /** * Send a request to the debugging server. * - * @param packet object + * @param aRequest object * A JSON packet to send to the debugging server. - * @param onResponse function + * @param aOnResponse function * If specified, will be called with the JSON response packet when * debugging server responds. * @return Request @@ -661,7 +656,7 @@ DebuggerClient.prototype = { * whenever a JSON or a Bulk response is received; and is rejected * if the response is an error. * Note: This return value can be ignored if you are using JSON alone, - * because the callback provided in |onResponse| will be bound to the + * because the callback provided in |aOnResponse| will be bound to the * "json-reply" event automatically. * * Events emitted: @@ -693,30 +688,30 @@ DebuggerClient.prototype = { * This object also emits "progress" events for each chunk * that is copied. See stream-utils.js. */ - request: function (packet, onResponse) { + request: function (aRequest, aOnResponse) { if (!this.mainRoot) { throw Error("Have not yet received a hello packet from the server."); } - let type = packet.type || ""; - if (!packet.to) { + let type = aRequest.type || ""; + if (!aRequest.to) { throw Error("'" + type + "' request packet has no destination."); } if (this._closed) { let msg = "'" + type + "' request packet to " + - "'" + packet.to + "' " + + "'" + aRequest.to + "' " + "can't be sent as the connection is closed."; let resp = { error: "connectionClosed", message: msg }; - if (onResponse) { - onResponse(resp); + if (aOnResponse) { + aOnResponse(resp); } return promise.reject(resp); } - let request = new Request(packet); + let request = new Request(aRequest); request.format = "json"; request.stack = getStack(); - if (onResponse) { - request.on("json-reply", onResponse); + if (aOnResponse) { + request.on("json-reply", aOnResponse); } this._sendOrQueueRequest(request); @@ -866,7 +861,7 @@ DebuggerClient.prototype = { if (request.format === "json") { this._transport.send(request.request); - return; + return false; } this._transport.startBulkSend(request.request).then((...args) => { @@ -904,28 +899,28 @@ DebuggerClient.prototype = { }, /** - * Arrange to hand the next reply from |actor| to the handler bound to - * |request|. + * Arrange to hand the next reply from |aActor| to the handler bound to + * |aRequest|. * * DebuggerClient.prototype.request / startBulkRequest usually takes care of * establishing the handler for a given request, but in rare cases (well, * greetings from new root actors, is the only case at the moment) we must be * prepared for a "reply" that doesn't correspond to any request we sent. */ - expectReply: function (actor, request) { - if (this._activeRequests.has(actor)) { - throw Error("clashing handlers for next reply from " + actor); + expectReply: function (aActor, aRequest) { + if (this._activeRequests.has(aActor)) { + throw Error("clashing handlers for next reply from " + uneval(aActor)); } // If a handler is passed directly (as it is with the handler for the root // actor greeting), create a dummy request to bind this to. - if (typeof request === "function") { - let handler = request; - request = new Request(); - request.on("json-reply", handler); + if (typeof aRequest === "function") { + let handler = aRequest; + aRequest = new Request(); + aRequest.on("json-reply", handler); } - this._activeRequests.set(actor, request); + this._activeRequests.set(aActor, aRequest); }, // Transport hooks. @@ -933,23 +928,23 @@ DebuggerClient.prototype = { /** * Called by DebuggerTransport to dispatch incoming packets as appropriate. * - * @param packet object + * @param aPacket object * The incoming packet. */ - onPacket: function (packet) { - if (!packet.from) { + onPacket: function (aPacket) { + if (!aPacket.from) { DevToolsUtils.reportException( "onPacket", new Error("Server did not specify an actor, dropping packet: " + - JSON.stringify(packet))); + JSON.stringify(aPacket))); return; } // If we have a registered Front for this actor, let it handle the packet // and skip all the rest of this unpleasantness. - let front = this.getActor(packet.from); + let front = this.getActor(aPacket.from); if (front) { - front.onPacket(packet); + front.onPacket(aPacket); return; } @@ -957,17 +952,17 @@ DebuggerClient.prototype = { // This is necessary because we might receive this event while the client is closing, // and the clients have already been removed by that point. if (this.mainRoot && - packet.from == this.mainRoot.actor && - packet.type == "forwardingCancelled") { - this.purgeRequests(packet.prefix); + aPacket.from == this.mainRoot.actor && + aPacket.type == "forwardingCancelled") { + this.purgeRequests(aPacket.prefix); return; } - if (this._clients.has(packet.from) && packet.type) { - let client = this._clients.get(packet.from); - let type = packet.type; + if (this._clients.has(aPacket.from) && aPacket.type) { + let client = this._clients.get(aPacket.from); + let type = aPacket.type; if (client.events.indexOf(type) != -1) { - client.emit(type, packet); + client.emit(type, aPacket); // we ignore the rest, as the client is expected to handle this packet. return; } @@ -977,24 +972,24 @@ DebuggerClient.prototype = { // See if we have a handler function waiting for a reply from this // actor. (Don't count unsolicited notifications or pauses as // replies.) - if (this._activeRequests.has(packet.from) && - !(packet.type in UnsolicitedNotifications) && - !(packet.type == ThreadStateTypes.paused && - packet.why.type in UnsolicitedPauses)) { - activeRequest = this._activeRequests.get(packet.from); - this._activeRequests.delete(packet.from); + if (this._activeRequests.has(aPacket.from) && + !(aPacket.type in UnsolicitedNotifications) && + !(aPacket.type == ThreadStateTypes.paused && + aPacket.why.type in UnsolicitedPauses)) { + activeRequest = this._activeRequests.get(aPacket.from); + this._activeRequests.delete(aPacket.from); } // If there is a subsequent request for the same actor, hand it off to the // transport. Delivery of packets on the other end is always async, even // in the local transport case. - this._attemptNextRequest(packet.from); + this._attemptNextRequest(aPacket.from); // Packets that indicate thread state changes get special treatment. - if (packet.type in ThreadStateTypes && - this._clients.has(packet.from) && - typeof this._clients.get(packet.from)._onThreadState == "function") { - this._clients.get(packet.from)._onThreadState(packet); + if (aPacket.type in ThreadStateTypes && + this._clients.has(aPacket.from) && + typeof this._clients.get(aPacket.from)._onThreadState == "function") { + this._clients.get(aPacket.from)._onThreadState(aPacket); } // TODO: Bug 1151156 - Remove once Gecko 40 is on b2g-stable. @@ -1002,10 +997,10 @@ DebuggerClient.prototype = { // On navigation the server resumes, so the client must resume as well. // We achieve that by generating a fake resumption packet that triggers // the client's thread state change listeners. - if (packet.type == UnsolicitedNotifications.tabNavigated && - this._clients.has(packet.from) && - this._clients.get(packet.from).thread) { - let thread = this._clients.get(packet.from).thread; + if (aPacket.type == UnsolicitedNotifications.tabNavigated && + this._clients.has(aPacket.from) && + this._clients.get(aPacket.from).thread) { + let thread = this._clients.get(aPacket.from).thread; let resumption = { from: thread._actor, type: "resumed" }; thread._onThreadState(resumption); } @@ -1013,12 +1008,12 @@ DebuggerClient.prototype = { // Only try to notify listeners on events, not responses to requests // that lack a packet type. - if (packet.type) { - this.emit(packet.type, packet); + if (aPacket.type) { + this.emit(aPacket.type, aPacket); } if (activeRequest) { - let emitReply = () => activeRequest.emit("json-reply", packet); + let emitReply = () => activeRequest.emit("json-reply", aPacket); if (activeRequest.stack) { callFunctionWithAsyncStack(emitReply, activeRequest.stack, "DevTools RDP"); @@ -1059,7 +1054,7 @@ DebuggerClient.prototype = { * that is copied. See stream-utils.js. */ onBulkPacket: function (packet) { - let { actor } = packet; + let { actor, type, length } = packet; if (!actor) { DevToolsUtils.reportException( @@ -1089,7 +1084,7 @@ DebuggerClient.prototype = { /** * Called by DebuggerTransport when the underlying stream is closed. * - * @param status nsresult + * @param aStatus nsresult * The status code that corresponds to the reason for closing * the stream. */ @@ -1285,9 +1280,7 @@ DebuggerClient.prototype = { poolFor: function (actorID) { for (let pool of this._pools) { - if (pool.has(actorID)) { - return pool; - } + if (pool.has(actorID)) return pool; } return null; }, @@ -1322,9 +1315,7 @@ Request.prototype = { events.emit(this, type, ...args); }, - get actor() { - return this.request.to || this.request.actor; - } + get actor() { return this.request.to || this.request.actor; } }; @@ -1333,80 +1324,76 @@ Request.prototype = { * is a front to the tab actor created in the server side, hiding the protocol * details in a traditional JavaScript API. * - * @param client DebuggerClient + * @param aClient DebuggerClient * The debugger client parent. - * @param form object + * @param aForm object * The protocol form for this tab. */ -function TabClient(client, form) { - this.client = client; - this._actor = form.from; - this._threadActor = form.threadActor; - this.javascriptEnabled = form.javascriptEnabled; - this.cacheDisabled = form.cacheDisabled; +function TabClient(aClient, aForm) { + this.client = aClient; + this._actor = aForm.from; + this._threadActor = aForm.threadActor; + this.javascriptEnabled = aForm.javascriptEnabled; + this.cacheDisabled = aForm.cacheDisabled; this.thread = null; this.request = this.client.request; - this.traits = form.traits || {}; + this.traits = aForm.traits || {}; this.events = ["workerListChanged"]; } TabClient.prototype = { - get actor() { - return this._actor; - }, - get _transport() { - return this.client._transport; - }, + get actor() { return this._actor; }, + get _transport() { return this.client._transport; }, /** * Attach to a thread actor. * - * @param object options + * @param object aOptions * Configuration options. * - useSourceMaps: whether to use source maps or not. - * @param function onResponse + * @param function aOnResponse * Called with the response packet and a ThreadClient * (which will be undefined on error). */ - attachThread: function (options = {}, onResponse = noop) { + attachThread: function (aOptions = {}, aOnResponse = noop) { if (this.thread) { - DevToolsUtils.executeSoon(() => onResponse({}, this.thread)); + DevToolsUtils.executeSoon(() => aOnResponse({}, this.thread)); return promise.resolve([{}, this.thread]); } let packet = { to: this._threadActor, type: "attach", - options, + options: aOptions }; - return this.request(packet).then(response => { - if (!response.error) { + return this.request(packet).then(aResponse => { + if (!aResponse.error) { this.thread = new ThreadClient(this, this._threadActor); this.client.registerClient(this.thread); } - onResponse(response, this.thread); - return [response, this.thread]; + aOnResponse(aResponse, this.thread); + return [aResponse, this.thread]; }); }, /** * Detach the client from the tab actor. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - before: function (packet) { + before: function (aPacket) { if (this.thread) { this.thread.detach(); } - return packet; + return aPacket; }, - after: function (response) { + after: function (aResponse) { this.client.unregisterClient(this); - return response; + return aResponse; }, }), @@ -1429,7 +1416,7 @@ TabClient.prototype = { }, _reload: DebuggerClient.requester({ type: "reload", - options: arg(0) + options: args(0) }), /** @@ -1440,28 +1427,28 @@ TabClient.prototype = { */ navigateTo: DebuggerClient.requester({ type: "navigateTo", - url: arg(0) + url: args(0) }), /** * Reconfigure the tab actor. * - * @param object options + * @param object aOptions * A dictionary object of the new options to use in the tab actor. - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ reconfigure: DebuggerClient.requester({ type: "reconfigure", - options: arg(0) + options: args(0) }), listWorkers: DebuggerClient.requester({ type: "listWorkers" }), - attachWorker: function (workerActor, onResponse) { - this.client.attachWorker(workerActor, onResponse); + attachWorker: function (aWorkerActor, aOnResponse) { + this.client.attachWorker(aWorkerActor, aOnResponse); }, /** @@ -1474,17 +1461,17 @@ TabClient.prototype = { */ resolveLocation: DebuggerClient.requester({ type: "resolveLocation", - location: arg(0) + location: args(0) }), }; eventSource(TabClient.prototype); -function WorkerClient(client, form) { - this.client = client; - this._actor = form.from; +function WorkerClient(aClient, aForm) { + this.client = aClient; + this._actor = aForm.from; this._isClosed = false; - this._url = form.url; + this._url = aForm.url; this._onClose = this._onClose.bind(this); @@ -1515,23 +1502,23 @@ WorkerClient.prototype = { }, detach: DebuggerClient.requester({ type: "detach" }, { - after: function (response) { + after: function (aResponse) { if (this.thread) { this.client.unregisterClient(this.thread); } this.client.unregisterClient(this); - return response; + return aResponse; }, }), - attachThread: function (options = {}, onResponse = noop) { + attachThread: function (aOptions = {}, aOnResponse = noop) { if (this.thread) { let response = [{ type: "connected", threadActor: this.thread._actor, consoleActor: this.consoleActor, }, this.thread]; - DevToolsUtils.executeSoon(() => onResponse(response)); + DevToolsUtils.executeSoon(() => aOnResponse(response)); return response; } @@ -1539,31 +1526,31 @@ WorkerClient.prototype = { return this.request({ to: this._actor, type: "connect", - options, - }).then(connectResponse => { - if (connectResponse.error) { - onResponse(connectResponse, null); + options: aOptions, + }).then(connectReponse => { + if (connectReponse.error) { + aOnResponse(connectReponse, null); return [connectResponse, null]; } return this.request({ - to: connectResponse.threadActor, + to: connectReponse.threadActor, type: "attach", - options, + options: aOptions }).then(attachResponse => { if (attachResponse.error) { - onResponse(attachResponse, null); + aOnResponse(attachResponse, null); } - this.thread = new ThreadClient(this, connectResponse.threadActor); - this.consoleActor = connectResponse.consoleActor; + this.thread = new ThreadClient(this, connectReponse.threadActor); + this.consoleActor = connectReponse.consoleActor; this.client.registerClient(this.thread); - onResponse(connectResponse, this.thread); + aOnResponse(connectReponse, this.thread); return [connectResponse, this.thread]; }); }, error => { - onResponse(error, null); + aOnResponse(error, null); }); }, @@ -1586,36 +1573,32 @@ WorkerClient.prototype = { eventSource(WorkerClient.prototype); -function AddonClient(client, actor) { - this._client = client; - this._actor = actor; +function AddonClient(aClient, aActor) { + this._client = aClient; + this._actor = aActor; this.request = this._client.request; this.events = []; } AddonClient.prototype = { - get actor() { - return this._actor; - }, - get _transport() { - return this._client._transport; - }, + get actor() { return this._actor; }, + get _transport() { return this._client._transport; }, /** * Detach the client from the addon actor. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - after: function (response) { + after: function (aResponse) { if (this._client.activeAddon === this) { this._client.activeAddon = null; } this._client.unregisterClient(this); - return response; + return aResponse; }, }) }; @@ -1626,9 +1609,9 @@ AddonClient.prototype = { * for the initial connection; DebuggerClient's 'listTabs' and * 'listChildProcesses' methods forward to that root actor. * - * @param client object + * @param aClient object * The client connection to which this actor belongs. - * @param greeting string + * @param aGreeting string * The greeting packet from the root actor we're to represent. * * Properties of a RootClient instance: @@ -1640,11 +1623,11 @@ AddonClient.prototype = { * @property traits object * The traits object, as given in the root actor's greeting packet. */ -function RootClient(client, greeting) { - this._client = client; - this.actor = greeting.from; - this.applicationType = greeting.applicationType; - this.traits = greeting.traits; +function RootClient(aClient, aGreeting) { + this._client = aClient; + this.actor = aGreeting.from; + this.applicationType = aGreeting.applicationType; + this.traits = aGreeting.traits; } exports.RootClient = RootClient; @@ -1654,7 +1637,7 @@ RootClient.prototype = { /** * List the open tabs. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ listTabs: DebuggerClient.requester({ type: "listTabs" }), @@ -1662,7 +1645,7 @@ RootClient.prototype = { /** * List the installed addons. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ listAddons: DebuggerClient.requester({ type: "listAddons" }), @@ -1670,7 +1653,7 @@ RootClient.prototype = { /** * List the registered workers. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ listWorkers: DebuggerClient.requester({ type: "listWorkers" }), @@ -1678,7 +1661,7 @@ RootClient.prototype = { /** * List the registered service workers. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ listServiceWorkerRegistrations: DebuggerClient.requester({ @@ -1688,7 +1671,7 @@ RootClient.prototype = { /** * List the running processes. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ listProcesses: DebuggerClient.requester({ type: "listProcesses" }), @@ -1697,7 +1680,7 @@ RootClient.prototype = { * Fetch the TabActor for the currently selected tab, or for a specific * tab given as first parameter. * - * @param [optional] object filter + * @param [optional] object aFilter * A dictionary object with following optional attributes: * - outerWindowID: used to match tabs in parent process * - tabId: used to match tabs in child processes @@ -1705,19 +1688,19 @@ RootClient.prototype = { * If nothing is specified, returns the actor for the currently * selected tab. */ - getTab: function (filter) { + getTab: function (aFilter) { let packet = { to: this.actor, type: "getTab" }; - if (filter) { - if (typeof (filter.outerWindowID) == "number") { - packet.outerWindowID = filter.outerWindowID; - } else if (typeof (filter.tabId) == "number") { - packet.tabId = filter.tabId; - } else if ("tab" in filter) { - let browser = filter.tab.linkedBrowser; + if (aFilter) { + if (typeof (aFilter.outerWindowID) == "number") { + packet.outerWindowID = aFilter.outerWindowID; + } else if (typeof (aFilter.tabId) == "number") { + packet.tabId = aFilter.tabId; + } else if ("tab" in aFilter) { + let browser = aFilter.tab.linkedBrowser; if (browser.frameLoader.tabParent) { // Tabs in child process packet.tabId = browser.frameLoader.tabParent.tabId; @@ -1744,7 +1727,7 @@ RootClient.prototype = { /** * Description of protocol's actors and methods. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ protocolDescription: DebuggerClient.requester({ type: "protocolDescription" }), @@ -1753,12 +1736,8 @@ RootClient.prototype = { * Methods constructed by DebuggerClient.requester require these forwards * on their 'this'. */ - get _transport() { - return this._client._transport; - }, - get request() { - return this._client.request; - } + get _transport() { return this._client._transport; }, + get request() { return this._client.request; } }; /** @@ -1766,16 +1745,16 @@ RootClient.prototype = { * is a front to the thread actor created in the server side, hiding the * protocol details in a traditional JavaScript API. * - * @param client DebuggerClient|TabClient + * @param aClient DebuggerClient|TabClient * The parent of the thread (tab for tab-scoped debuggers, DebuggerClient * for chrome debuggers). - * @param actor string + * @param aActor string * The actor ID for this thread. */ -function ThreadClient(client, actor) { - this._parent = client; - this.client = client instanceof DebuggerClient ? client : client.client; - this._actor = actor; +function ThreadClient(aClient, aActor) { + this._parent = aClient; + this.client = aClient instanceof DebuggerClient ? aClient : aClient.client; + this._actor = aActor; this._frameCache = []; this._scriptCache = {}; this._pauseGrips = {}; @@ -1785,48 +1764,40 @@ function ThreadClient(client, actor) { ThreadClient.prototype = { _state: "paused", - get state() { - return this._state; - }, - get paused() { - return this._state === "paused"; - }, + get state() { return this._state; }, + get paused() { return this._state === "paused"; }, _pauseOnExceptions: false, _ignoreCaughtExceptions: false, _pauseOnDOMEvents: null, _actor: null, - get actor() { - return this._actor; - }, + get actor() { return this._actor; }, - get _transport() { - return this.client._transport; - }, + get _transport() { return this.client._transport; }, - _assertPaused: function (command) { + _assertPaused: function (aCommand) { if (!this.paused) { - throw Error(command + " command sent while not paused. Currently " + this._state); + throw Error(aCommand + " command sent while not paused. Currently " + this._state); } }, /** - * Resume a paused thread. If the optional limit parameter is present, then + * Resume a paused thread. If the optional aLimit parameter is present, then * the thread will also pause when that limit is reached. * - * @param [optional] object limit + * @param [optional] object aLimit * An object with a type property set to the appropriate limit (next, * step, or finish) per the remote debugging protocol specification. * Use null to specify no limit. - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ _doResume: DebuggerClient.requester({ type: "resume", - resumeLimit: arg(0) + resumeLimit: args(0) }, { - before: function (packet) { + before: function (aPacket) { this._assertPaused("resume"); // Put the client in a tentative "resuming" state so we can prevent @@ -1835,152 +1806,150 @@ ThreadClient.prototype = { this._state = "resuming"; if (this._pauseOnExceptions) { - packet.pauseOnExceptions = this._pauseOnExceptions; + aPacket.pauseOnExceptions = this._pauseOnExceptions; } if (this._ignoreCaughtExceptions) { - packet.ignoreCaughtExceptions = this._ignoreCaughtExceptions; + aPacket.ignoreCaughtExceptions = this._ignoreCaughtExceptions; } if (this._pauseOnDOMEvents) { - packet.pauseOnDOMEvents = this._pauseOnDOMEvents; + aPacket.pauseOnDOMEvents = this._pauseOnDOMEvents; } - return packet; + return aPacket; }, - after: function (response) { - if (response.error && this._state == "resuming") { + after: function (aResponse) { + if (aResponse.error && this._state == "resuming") { // There was an error resuming, update the state to the new one // reported by the server, if given (only on wrongState), otherwise // reset back to the previous state. - if (response.state) { - this._state = ThreadStateTypes[response.state]; + if (aResponse.state) { + this._state = ThreadStateTypes[aResponse.state]; } else { this._state = this._previousState; } } delete this._previousState; - return response; + return aResponse; }, }), /** * Reconfigure the thread actor. * - * @param object options + * @param object aOptions * A dictionary object of the new options to use in the thread actor. - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ reconfigure: DebuggerClient.requester({ type: "reconfigure", - options: arg(0) + options: args(0) }), /** * Resume a paused thread. */ - resume: function (onResponse) { - return this._doResume(null, onResponse); + resume: function (aOnResponse) { + return this._doResume(null, aOnResponse); }, /** * Resume then pause without stepping. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ - resumeThenPause: function (onResponse) { - return this._doResume({ type: "break" }, onResponse); + resumeThenPause: function (aOnResponse) { + return this._doResume({ type: "break" }, aOnResponse); }, /** * Step over a function call. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ - stepOver: function (onResponse) { - return this._doResume({ type: "next" }, onResponse); + stepOver: function (aOnResponse) { + return this._doResume({ type: "next" }, aOnResponse); }, /** * Step into a function call. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ - stepIn: function (onResponse) { - return this._doResume({ type: "step" }, onResponse); + stepIn: function (aOnResponse) { + return this._doResume({ type: "step" }, aOnResponse); }, /** * Step out of a function call. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ - stepOut: function (onResponse) { - return this._doResume({ type: "finish" }, onResponse); + stepOut: function (aOnResponse) { + return this._doResume({ type: "finish" }, aOnResponse); }, /** * Immediately interrupt a running thread. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ - interrupt: function (onResponse) { - return this._doInterrupt(null, onResponse); + interrupt: function (aOnResponse) { + return this._doInterrupt(null, aOnResponse); }, /** * Pause execution right before the next JavaScript bytecode is executed. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ - breakOnNext: function (onResponse) { - return this._doInterrupt("onNext", onResponse); + breakOnNext: function (aOnResponse) { + return this._doInterrupt("onNext", aOnResponse); }, /** * Interrupt a running thread. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ _doInterrupt: DebuggerClient.requester({ type: "interrupt", - when: arg(0) + when: args(0) }), /** * Enable or disable pausing when an exception is thrown. * - * @param boolean pauseOnExceptions + * @param boolean aFlag * Enables pausing if true, disables otherwise. - * @param boolean ignoreCaughtExceptions - * Whether to ignore caught exceptions - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ - pauseOnExceptions: function (pauseOnExceptions, - ignoreCaughtExceptions, - onResponse = noop) { - this._pauseOnExceptions = pauseOnExceptions; - this._ignoreCaughtExceptions = ignoreCaughtExceptions; + pauseOnExceptions: function (aPauseOnExceptions, + aIgnoreCaughtExceptions, + aOnResponse = noop) { + this._pauseOnExceptions = aPauseOnExceptions; + this._ignoreCaughtExceptions = aIgnoreCaughtExceptions; // Otherwise send the flag using a standard resume request. if (!this.paused) { - return this.interrupt(response => { - if (response.error) { + return this.interrupt(aResponse => { + if (aResponse.error) { // Can't continue if pausing failed. - onResponse(response); - return response; + aOnResponse(aResponse); + return aResponse; } - return this.resume(onResponse); + return this.resume(aOnResponse); }); } - onResponse(); + aOnResponse(); return promise.resolve(); }, @@ -2019,48 +1988,48 @@ ThreadClient.prototype = { * Send a clientEvaluate packet to the debuggee. Response * will be a resume packet. * - * @param string frame + * @param string aFrame * The actor ID of the frame where the evaluation should take place. - * @param string expression + * @param string aExpression * The expression that will be evaluated in the scope of the frame * above. - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ eval: DebuggerClient.requester({ type: "clientEvaluate", - frame: arg(0), - expression: arg(1) + frame: args(0), + expression: args(1) }, { - before: function (packet) { + before: function (aPacket) { this._assertPaused("eval"); // Put the client in a tentative "resuming" state so we can prevent // further requests that should only be sent in the paused state. this._state = "resuming"; - return packet; + return aPacket; }, - after: function (response) { - if (response.error) { + after: function (aResponse) { + if (aResponse.error) { // There was an error resuming, back to paused state. this._state = "paused"; } - return response; + return aResponse; }, }), /** * Detach from the thread actor. * - * @param function onResponse + * @param function aOnResponse * Called with the response packet. */ detach: DebuggerClient.requester({ type: "detach" }, { - after: function (response) { + after: function (aResponse) { this.client.unregisterClient(this); this._parent.thread = null; - return response; + return aResponse; }, }), @@ -2074,7 +2043,7 @@ ThreadClient.prototype = { */ releaseMany: DebuggerClient.requester({ type: "releaseMany", - actors: arg(0), + actors: args(0), }), /** @@ -2085,13 +2054,13 @@ ThreadClient.prototype = { */ threadGrips: DebuggerClient.requester({ type: "threadGrips", - actors: arg(0) + actors: args(0) }), /** * Return the event listeners defined on the page. * - * @param onResponse Function + * @param aOnResponse Function * Called with the thread's response. */ eventListeners: DebuggerClient.requester({ @@ -2101,7 +2070,7 @@ ThreadClient.prototype = { /** * Request the loaded sources for the current thread. * - * @param onResponse Function + * @param aOnResponse Function * Called with the thread's response. */ getSources: DebuggerClient.requester({ @@ -2122,19 +2091,19 @@ ThreadClient.prototype = { /** * Request frames from the callstack for the current thread. * - * @param start integer + * @param aStart integer * The number of the youngest stack frame to return (the youngest * frame is 0). - * @param count integer + * @param aCount integer * The maximum number of frames to return, or null to return all * frames. - * @param onResponse function + * @param aOnResponse function * Called with the thread's response. */ getFrames: DebuggerClient.requester({ type: "frames", - start: arg(0), - count: arg(1) + start: args(0), + count: args(1) }), /** @@ -2142,9 +2111,7 @@ ThreadClient.prototype = { * framescleared event to keep up to date on changes to this cache, * and can fill it using the fillFrames method. */ - get cachedFrames() { - return this._frameCache; - }, + get cachedFrames() { return this._frameCache; }, /** * true if there are more stack frames available on the server. @@ -2155,34 +2122,34 @@ ThreadClient.prototype = { }, /** - * Ensure that at least total stack frames have been loaded in the + * Ensure that at least aTotal stack frames have been loaded in the * ThreadClient's stack frame cache. A framesadded event will be * sent when the stack frame cache is updated. * - * @param total number + * @param aTotal number * The minimum number of stack frames to be included. - * @param callback function + * @param aCallback function * Optional callback function called when frames have been loaded * @returns true if a framesadded notification should be expected. */ - fillFrames: function (total, callback = noop) { + fillFrames: function (aTotal, aCallback = noop) { this._assertPaused("fillFrames"); - if (this._frameCache.length >= total) { + if (this._frameCache.length >= aTotal) { return false; } let numFrames = this._frameCache.length; - this.getFrames(numFrames, total - numFrames, (response) => { - if (response.error) { - callback(response); + this.getFrames(numFrames, aTotal - numFrames, (aResponse) => { + if (aResponse.error) { + aCallback(aResponse); return; } let threadGrips = DevToolsUtils.values(this._threadGrips); - for (let i in response.frames) { - let frame = response.frames[i]; + for (let i in aResponse.frames) { + let frame = aResponse.frames[i]; if (!frame.where.source) { // Older servers use urls instead, so we need to resolve // them to source actors @@ -2200,7 +2167,7 @@ ThreadClient.prototype = { // frames available. this.emit("framesadded"); - callback(response); + aCallback(aResponse); }); return true; @@ -2220,16 +2187,16 @@ ThreadClient.prototype = { /** * Return a ObjectClient object for the given object grip. * - * @param grip object + * @param aGrip object * A pause-lifetime object grip returned by the protocol. */ - pauseGrip: function (grip) { - if (grip.actor in this._pauseGrips) { - return this._pauseGrips[grip.actor]; + pauseGrip: function (aGrip) { + if (aGrip.actor in this._pauseGrips) { + return this._pauseGrips[aGrip.actor]; } - let client = new ObjectClient(this.client, grip); - this._pauseGrips[grip.actor] = client; + let client = new ObjectClient(this.client, aGrip); + this._pauseGrips[aGrip.actor] = client; return client; }, @@ -2237,19 +2204,19 @@ ThreadClient.prototype = { * Get or create a long string client, checking the grip client cache if it * already exists. * - * @param grip Object + * @param aGrip Object * The long string grip returned by the protocol. - * @param gripCacheName String + * @param aGripCacheName String * The property name of the grip client cache to check for existing * clients in. */ - _longString: function (grip, gripCacheName) { - if (grip.actor in this[gripCacheName]) { - return this[gripCacheName][grip.actor]; + _longString: function (aGrip, aGripCacheName) { + if (aGrip.actor in this[aGripCacheName]) { + return this[aGripCacheName][aGrip.actor]; } - let client = new LongStringClient(this.client, grip); - this[gripCacheName][grip.actor] = client; + let client = new LongStringClient(this.client, aGrip); + this[aGripCacheName][aGrip.actor] = client; return client; }, @@ -2257,35 +2224,35 @@ ThreadClient.prototype = { * Return an instance of LongStringClient for the given long string grip that * is scoped to the current pause. * - * @param grip Object + * @param aGrip Object * The long string grip returned by the protocol. */ - pauseLongString: function (grip) { - return this._longString(grip, "_pauseGrips"); + pauseLongString: function (aGrip) { + return this._longString(aGrip, "_pauseGrips"); }, /** * Return an instance of LongStringClient for the given long string grip that * is scoped to the thread lifetime. * - * @param grip Object + * @param aGrip Object * The long string grip returned by the protocol. */ - threadLongString: function (grip) { - return this._longString(grip, "_threadGrips"); + threadLongString: function (aGrip) { + return this._longString(aGrip, "_threadGrips"); }, /** * Clear and invalidate all the grip clients from the given cache. * - * @param gripCacheName + * @param aGripCacheName * The property name of the grip cache we want to clear. */ - _clearObjectClients: function (gripCacheName) { - for (let id in this[gripCacheName]) { - this[gripCacheName][id].valid = false; + _clearObjectClients: function (aGripCacheName) { + for (let id in this[aGripCacheName]) { + this[aGripCacheName][id].valid = false; } - this[gripCacheName] = {}; + this[aGripCacheName] = {}; }, /** @@ -2308,16 +2275,16 @@ ThreadClient.prototype = { * Handle thread state change by doing necessary cleanup and notifying all * registered listeners. */ - _onThreadState: function (packet) { - this._state = ThreadStateTypes[packet.type]; + _onThreadState: function (aPacket) { + this._state = ThreadStateTypes[aPacket.type]; // The debugger UI may not be initialized yet so we want to keep // the packet around so it knows what to pause state to display // when it's initialized - this._lastPausePacket = packet.type === "resumed" ? null : packet; + this._lastPausePacket = aPacket.type === "resumed" ? null : aPacket; this._clearFrames(); this._clearPauseGrips(); - packet.type === ThreadStateTypes.detached && this._clearThreadGrips(); - this.client._eventsEnabled && this.emit(packet.type, packet); + aPacket.type === ThreadStateTypes.detached && this._clearThreadGrips(); + this.client._eventsEnabled && this.emit(aPacket.type, aPacket); }, getLastPausePacket: function () { @@ -2327,33 +2294,32 @@ ThreadClient.prototype = { /** * Return an EnvironmentClient instance for the given environment actor form. */ - environment: function (form) { - return new EnvironmentClient(this.client, form); + environment: function (aForm) { + return new EnvironmentClient(this.client, aForm); }, /** * Return an instance of SourceClient for the given source actor form. */ - source: function (form) { - if (form.actor in this._threadGrips) { - return this._threadGrips[form.actor]; + source: function (aForm) { + if (aForm.actor in this._threadGrips) { + return this._threadGrips[aForm.actor]; } - this._threadGrips[form.actor] = new SourceClient(this, form); - return this._threadGrips[form.actor]; + return this._threadGrips[aForm.actor] = new SourceClient(this, aForm); }, /** * Request the prototype and own properties of mutlipleObjects. * - * @param onResponse function + * @param aOnResponse function * Called with the request's response. * @param actors [string] * List of actor ID of the queried objects. */ getPrototypesAndProperties: DebuggerClient.requester({ type: "prototypesAndProperties", - actors: arg(0) + actors: args(0) }), events: ["newSource"] @@ -2367,14 +2333,14 @@ eventSource(ThreadClient.prototype); * server side, hiding the protocol details in a traditional * JavaScript API. * - * @param client DebuggerClient + * @param aClient DebuggerClient * The debugger client parent. - * @param actor string + * @param aActor string * The actor ID for this thread. */ -function TraceClient(client, actor) { - this._client = client; - this._actor = actor; +function TraceClient(aClient, aActor) { + this._client = aClient; + this._actor = aActor; this._activeTraces = new Set(); this._waitingPackets = new Map(); this._expectedPacket = 0; @@ -2383,16 +2349,10 @@ function TraceClient(client, actor) { } TraceClient.prototype = { - get actor() { - return this._actor; - }, - get tracing() { - return this._activeTraces.size > 0; - }, + get actor() { return this._actor; }, + get tracing() { return this._activeTraces.size > 0; }, - get _transport() { - return this._client._transport; - }, + get _transport() { return this._client._transport; }, /** * Detach from the trace actor. @@ -2400,41 +2360,41 @@ TraceClient.prototype = { detach: DebuggerClient.requester({ type: "detach" }, { - after: function (response) { + after: function (aResponse) { this._client.unregisterClient(this); - return response; + return aResponse; }, }), /** * Start a new trace. * - * @param trace [string] + * @param aTrace [string] * An array of trace types to be recorded by the new trace. * - * @param name string + * @param aName string * The name of the new trace. * - * @param onResponse function + * @param aOnResponse function * Called with the request's response. */ startTrace: DebuggerClient.requester({ type: "startTrace", - name: arg(1), - trace: arg(0) + name: args(1), + trace: args(0) }, { - after: function (response) { - if (response.error) { - return response; + after: function (aResponse) { + if (aResponse.error) { + return aResponse; } if (!this.tracing) { this._waitingPackets.clear(); this._expectedPacket = 0; } - this._activeTraces.add(response.name); + this._activeTraces.add(aResponse.name); - return response; + return aResponse; }, }), @@ -2442,24 +2402,24 @@ TraceClient.prototype = { * End a trace. If a name is provided, stop the named * trace. Otherwise, stop the most recently started trace. * - * @param name string + * @param aName string * The name of the trace to stop. * - * @param onResponse function + * @param aOnResponse function * Called with the request's response. */ stopTrace: DebuggerClient.requester({ type: "stopTrace", - name: arg(0) + name: args(0) }, { - after: function (response) { - if (response.error) { - return response; + after: function (aResponse) { + if (aResponse.error) { + return aResponse; } - this._activeTraces.delete(response.name); + this._activeTraces.delete(aResponse.name); - return response; + return aResponse; }, }) }; @@ -2467,25 +2427,22 @@ TraceClient.prototype = { /** * Grip clients are used to retrieve information about the relevant object. * - * @param client DebuggerClient + * @param aClient DebuggerClient * The debugger client parent. - * @param grip object + * @param aGrip object * A pause-lifetime object grip returned by the protocol. */ -function ObjectClient(client, grip) { - this._grip = grip; - this._client = client; +function ObjectClient(aClient, aGrip) +{ + this._grip = aGrip; + this._client = aClient; this.request = this._client.request; } exports.ObjectClient = ObjectClient; ObjectClient.prototype = { - get actor() { - return this._grip.actor; - }, - get _transport() { - return this._client._transport; - }, + get actor() { return this._grip.actor; }, + get _transport() { return this._client._transport; }, valid: true, @@ -2502,18 +2459,18 @@ ObjectClient.prototype = { getDefinitionSite: DebuggerClient.requester({ type: "definitionSite" }, { - before: function (packet) { + before: function (aPacket) { if (this._grip.class != "Function") { throw new Error("getDefinitionSite is only valid for function grips."); } - return packet; + return aPacket; } }), /** * Request the names of a function's formal parameters. * - * @param onResponse function + * @param aOnResponse function * Called with an object of the form: * { parameterNames:[, ...] } * where each is the name of a parameter. @@ -2521,11 +2478,11 @@ ObjectClient.prototype = { getParameterNames: DebuggerClient.requester({ type: "parameterNames" }, { - before: function (packet) { - if (this._grip.class !== "Function") { + before: function (aPacket) { + if (this._grip["class"] !== "Function") { throw new Error("getParameterNames is only valid for function grips."); } - return packet; + return aPacket; }, }), @@ -2533,7 +2490,7 @@ ObjectClient.prototype = { * Request the names of the properties defined on the object and not its * prototype. * - * @param onResponse function Called with the request's response. + * @param aOnResponse function Called with the request's response. */ getOwnPropertyNames: DebuggerClient.requester({ type: "ownPropertyNames" @@ -2542,7 +2499,7 @@ ObjectClient.prototype = { /** * Request the prototype and own properties of the object. * - * @param onResponse function Called with the request's response. + * @param aOnResponse function Called with the request's response. */ getPrototypeAndProperties: DebuggerClient.requester({ type: "prototypeAndProperties" @@ -2564,17 +2521,17 @@ ObjectClient.prototype = { * - sort Boolean * If true, the iterator will sort the properties by name * before dispatching them. - * @param onResponse function Called with the client instance. + * @param aOnResponse function Called with the client instance. */ enumProperties: DebuggerClient.requester({ type: "enumProperties", - options: arg(0) + options: args(0) }, { - after: function (response) { - if (response.iterator) { - return { iterator: new PropertyIteratorClient(this._client, response.iterator) }; + after: function (aResponse) { + if (aResponse.iterator) { + return { iterator: new PropertyIteratorClient(this._client, aResponse.iterator) }; } - return response; + return aResponse; }, }), @@ -2582,7 +2539,7 @@ ObjectClient.prototype = { * Request a PropertyIteratorClient instance to enumerate entries in a * Map/Set-like object. * - * @param onResponse function Called with the request's response. + * @param aOnResponse function Called with the request's response. */ enumEntries: DebuggerClient.requester({ type: "enumEntries" @@ -2606,18 +2563,18 @@ ObjectClient.prototype = { /** * Request the property descriptor of the object's specified property. * - * @param name string The name of the requested property. - * @param onResponse function Called with the request's response. + * @param aName string The name of the requested property. + * @param aOnResponse function Called with the request's response. */ getProperty: DebuggerClient.requester({ type: "property", - name: arg(0) + name: args(0) }), /** * Request the prototype of the object. * - * @param onResponse function Called with the request's response. + * @param aOnResponse function Called with the request's response. */ getPrototype: DebuggerClient.requester({ type: "prototype" @@ -2626,7 +2583,7 @@ ObjectClient.prototype = { /** * Request the display string of the object. * - * @param onResponse function Called with the request's response. + * @param aOnResponse function Called with the request's response. */ getDisplayString: DebuggerClient.requester({ type: "displayString" @@ -2635,16 +2592,16 @@ ObjectClient.prototype = { /** * Request the scope of the object. * - * @param onResponse function Called with the request's response. + * @param aOnResponse function Called with the request's response. */ getScope: DebuggerClient.requester({ type: "scope" }, { - before: function (packet) { + before: function (aPacket) { if (this._grip.class !== "Function") { throw new Error("scope is only valid for function grips."); } - return packet; + return aPacket; }, }), @@ -2654,12 +2611,12 @@ ObjectClient.prototype = { getDependentPromises: DebuggerClient.requester({ type: "dependentPromises" }, { - before: function (packet) { + before: function (aPacket) { if (this._grip.class !== "Promise") { throw new Error("getDependentPromises is only valid for promise " + "grips."); } - return packet; + return aPacket; } }), @@ -2669,11 +2626,11 @@ ObjectClient.prototype = { getPromiseAllocationStack: DebuggerClient.requester({ type: "allocationStack" }, { - before: function (packet) { + before: function (aPacket) { if (this._grip.class !== "Promise") { throw new Error("getAllocationStack is only valid for promise grips."); } - return packet; + return aPacket; } }), @@ -2715,29 +2672,25 @@ ObjectClient.prototype = { * this is controled while creating the PropertyIteratorClient * from ObjectClient.enumProperties. * - * @param client DebuggerClient + * @param aClient DebuggerClient * The debugger client parent. - * @param grip Object + * @param aGrip Object * A PropertyIteratorActor grip returned by the protocol via * TabActor.enumProperties request. */ -function PropertyIteratorClient(client, grip) { - this._grip = grip; - this._client = client; +function PropertyIteratorClient(aClient, aGrip) { + this._grip = aGrip; + this._client = aClient; this.request = this._client.request; } PropertyIteratorClient.prototype = { - get actor() { - return this._grip.actor; - }, + get actor() { return this._grip.actor; }, /** * Get the total number of properties available in the iterator. */ - get count() { - return this._grip.count; - }, + get count() { return this._grip.count; }, /** * Get one or more property names that correspond to the positions in the @@ -2745,12 +2698,12 @@ PropertyIteratorClient.prototype = { * * @param indexes Array * An array of property indexes. - * @param callback Function + * @param aCallback Function * The function called when we receive the property names. */ names: DebuggerClient.requester({ type: "names", - indexes: arg(0) + indexes: args(0) }, {}), /** @@ -2760,19 +2713,19 @@ PropertyIteratorClient.prototype = { * The index of the first property to fetch. * @param count Number * The number of properties to fetch. - * @param callback Function + * @param aCallback Function * The function called when we receive the property values. */ slice: DebuggerClient.requester({ type: "slice", - start: arg(0), - count: arg(1) + start: args(0), + count: args(1) }, {}), /** * Get all the property values. * - * @param callback Function + * @param aCallback Function * The function called when we receive the property values. */ all: DebuggerClient.requester({ @@ -2784,65 +2737,57 @@ PropertyIteratorClient.prototype = { * A LongStringClient provides a way to access "very long" strings from the * debugger server. * - * @param client DebuggerClient + * @param aClient DebuggerClient * The debugger client parent. - * @param grip Object + * @param aGrip Object * A pause-lifetime long string grip returned by the protocol. */ -function LongStringClient(client, grip) { - this._grip = grip; - this._client = client; +function LongStringClient(aClient, aGrip) { + this._grip = aGrip; + this._client = aClient; this.request = this._client.request; } exports.LongStringClient = LongStringClient; LongStringClient.prototype = { - get actor() { - return this._grip.actor; - }, - get length() { - return this._grip.length; - }, - get initial() { - return this._grip.initial; - }, - get _transport() { - return this._client._transport; - }, + get actor() { return this._grip.actor; }, + get length() { return this._grip.length; }, + get initial() { return this._grip.initial; }, + get _transport() { return this._client._transport; }, valid: true, /** - * Get the substring of this LongString from start to end. + * Get the substring of this LongString from aStart to aEnd. * - * @param start Number + * @param aStart Number * The starting index. - * @param end Number + * @param aEnd Number * The ending index. - * @param callback Function + * @param aCallback Function * The function called when we receive the substring. */ substring: DebuggerClient.requester({ type: "substring", - start: arg(0), - end: arg(1) + start: args(0), + end: args(1) }), }; /** * A SourceClient provides a way to access the source text of a script. * - * @param client ThreadClient + * @param aClient ThreadClient * The thread client parent. - * @param form Object + * @param aForm Object * The form sent across the remote debugging protocol. */ -function SourceClient(client, form) { - this._form = form; - this._isBlackBoxed = form.isBlackBoxed; - this._isPrettyPrinted = form.isPrettyPrinted; - this._activeThread = client; - this._client = client.client; +function SourceClient(aClient, aForm) { + this._form = aForm; + this._isBlackBoxed = aForm.isBlackBoxed; + this._isPrettyPrinted = aForm.isPrettyPrinted; + this._activeThread = aClient; + this._client = aClient.client; } SourceClient.prototype = { @@ -2868,47 +2813,47 @@ SourceClient.prototype = { /** * Black box this SourceClient's source. * - * @param callback Function + * @param aCallback Function * The callback function called when we receive the response from the server. */ blackBox: DebuggerClient.requester({ type: "blackbox" }, { - after: function (response) { - if (!response.error) { + after: function (aResponse) { + if (!aResponse.error) { this._isBlackBoxed = true; if (this._activeThread) { this._activeThread.emit("blackboxchange", this); } } - return response; + return aResponse; } }), /** * Un-black box this SourceClient's source. * - * @param callback Function + * @param aCallback Function * The callback function called when we receive the response from the server. */ unblackBox: DebuggerClient.requester({ type: "unblackbox" }, { - after: function (response) { - if (!response.error) { + after: function (aResponse) { + if (!aResponse.error) { this._isBlackBoxed = false; if (this._activeThread) { this._activeThread.emit("blackboxchange", this); } } - return response; + return aResponse; } }), /** * Get Executable Lines from a source * - * @param callback Function + * @param aCallback Function * The callback function called when we receive the response from the server. */ getExecutableLines: function (cb = noop) { @@ -2926,105 +2871,105 @@ SourceClient.prototype = { /** * Get a long string grip for this SourceClient's source. */ - source: function (callback = noop) { + source: function (aCallback = noop) { let packet = { to: this._form.actor, type: "source" }; - return this._client.request(packet).then(response => { - return this._onSourceResponse(response, callback); + return this._client.request(packet).then(aResponse => { + return this._onSourceResponse(aResponse, aCallback); }); }, /** * Pretty print this source's text. */ - prettyPrint: function (indent, callback = noop) { + prettyPrint: function (aIndent, aCallback = noop) { const packet = { to: this._form.actor, type: "prettyPrint", - indent + indent: aIndent }; - return this._client.request(packet).then(response => { - if (!response.error) { + return this._client.request(packet).then(aResponse => { + if (!aResponse.error) { this._isPrettyPrinted = true; this._activeThread._clearFrames(); this._activeThread.emit("prettyprintchange", this); } - return this._onSourceResponse(response, callback); + return this._onSourceResponse(aResponse, aCallback); }); }, /** * Stop pretty printing this source's text. */ - disablePrettyPrint: function (callback = noop) { + disablePrettyPrint: function (aCallback = noop) { const packet = { to: this._form.actor, type: "disablePrettyPrint" }; - return this._client.request(packet).then(response => { - if (!response.error) { + return this._client.request(packet).then(aResponse => { + if (!aResponse.error) { this._isPrettyPrinted = false; this._activeThread._clearFrames(); this._activeThread.emit("prettyprintchange", this); } - return this._onSourceResponse(response, callback); + return this._onSourceResponse(aResponse, aCallback); }); }, - _onSourceResponse: function (response, callback) { - if (response.error) { - callback(response); - return response; + _onSourceResponse: function (aResponse, aCallback) { + if (aResponse.error) { + aCallback(aResponse); + return aResponse; } - if (typeof response.source === "string") { - callback(response); - return response; + if (typeof aResponse.source === "string") { + aCallback(aResponse); + return aResponse; } - let { contentType, source } = response; + let { contentType, source } = aResponse; let longString = this._activeThread.threadLongString(source); - return longString.substring(0, longString.length).then(function (resp) { - if (resp.error) { - callback(resp); - return resp; + return longString.substring(0, longString.length).then(function (aResponse) { + if (aResponse.error) { + aCallback(aResponse); + return aReponse; } - let newResponse = { - source: resp.substring, + let response = { + source: aResponse.substring, contentType: contentType }; - callback(newResponse); - return newResponse; + aCallback(response); + return response; }); }, /** * Request to set a breakpoint in the specified location. * - * @param object location + * @param object aLocation * The location and condition of the breakpoint in * the form of { line[, column, condition] }. - * @param function onResponse + * @param function aOnResponse * Called with the thread's response. */ - setBreakpoint: function ({ line, column, condition, noSliding }, onResponse = noop) { + setBreakpoint: function ({ line, column, condition, noSliding }, aOnResponse = noop) { // A helper function that sets the breakpoint. - let doSetBreakpoint = callback => { + let doSetBreakpoint = aCallback => { let root = this._client.mainRoot; let location = { - line, - column, + line: line, + column: column }; let packet = { to: this.actor, type: "setBreakpoint", - location, - condition, - noSliding, + location: location, + condition: condition, + noSliding: noSliding }; // Backwards compatibility: send the breakpoint request to the @@ -3034,24 +2979,24 @@ SourceClient.prototype = { packet.location.url = this.url; } - return this._client.request(packet).then(response => { + return this._client.request(packet).then(aResponse => { // Ignoring errors, since the user may be setting a breakpoint in a // dead script that will reappear on a page reload. let bpClient; - if (response.actor) { + if (aResponse.actor) { bpClient = new BreakpointClient( this._client, this, - response.actor, + aResponse.actor, location, root.traits.conditionalBreakpoints ? condition : undefined ); } - onResponse(response, bpClient); - if (callback) { - callback(); + aOnResponse(aResponse, bpClient); + if (aCallback) { + aCallback(); } - return [response, bpClient]; + return [aResponse, bpClient]; }); }; @@ -3060,14 +3005,14 @@ SourceClient.prototype = { return doSetBreakpoint(); } // Otherwise, force a pause in order to set the breakpoint. - return this._activeThread.interrupt().then(response => { - if (response.error) { + return this._activeThread.interrupt().then(aResponse => { + if (aResponse.error) { // Can't set the breakpoint if pausing failed. - onResponse(response); - return response; + aOnResponse(aResponse); + return aResponse; } - const { type, why } = response; + const { type, why } = aResponse; const cleanUp = type == "paused" && why.type == "interrupted" ? () => this._activeThread.resume() : noop; @@ -3080,42 +3025,38 @@ SourceClient.prototype = { /** * Breakpoint clients are used to remove breakpoints that are no longer used. * - * @param client DebuggerClient + * @param aClient DebuggerClient * The debugger client parent. - * @param sourceClient SourceClient + * @param aSourceClient SourceClient * The source where this breakpoint exists - * @param actor string + * @param aActor string * The actor ID for this breakpoint. - * @param location object + * @param aLocation object * The location of the breakpoint. This is an object with two properties: * url and line. - * @param condition string + * @param aCondition string * The conditional expression of the breakpoint */ -function BreakpointClient(client, sourceClient, actor, location, condition) { - this._client = client; - this._actor = actor; - this.location = location; - this.location.actor = sourceClient.actor; - this.location.url = sourceClient.url; - this.source = sourceClient; +function BreakpointClient(aClient, aSourceClient, aActor, aLocation, aCondition) { + this._client = aClient; + this._actor = aActor; + this.location = aLocation; + this.location.actor = aSourceClient.actor; + this.location.url = aSourceClient.url; + this.source = aSourceClient; this.request = this._client.request; // The condition property should only exist if it's a truthy value - if (condition) { - this.condition = condition; + if (aCondition) { + this.condition = aCondition; } } BreakpointClient.prototype = { _actor: null, - get actor() { - return this._actor; - }, - get _transport() { - return this._client._transport; - }, + get actor() { return this._actor; }, + get _transport() { return this._client._transport; }, /** * Remove the breakpoint from the server. @@ -3133,8 +3074,9 @@ BreakpointClient.prototype = { // conditional breakpoints if (root.traits.conditionalBreakpoints) { return "condition" in this; + } else { + return "conditionalExpression" in this; } - return "conditionalExpression" in this; }, /** @@ -3148,14 +3090,15 @@ BreakpointClient.prototype = { let root = this._client.mainRoot; if (root.traits.conditionalBreakpoints) { return this.condition; + } else { + return this.conditionalExpression; } - return this.conditionalExpression; }, /** * Set the condition of this breakpoint */ - setCondition: function (gThreadClient, condition) { + setCondition: function (gThreadClient, aCondition) { let root = this._client.mainRoot; let deferred = promise.defer(); @@ -3163,31 +3106,32 @@ BreakpointClient.prototype = { let info = { line: this.location.line, column: this.location.column, - condition: condition + condition: aCondition }; // Remove the current breakpoint and add a new one with the // condition. - this.remove(response => { - if (response && response.error) { - deferred.reject(response); + this.remove(aResponse => { + if (aResponse && aResponse.error) { + deferred.reject(aResponse); return; } - this.source.setBreakpoint(info, (resp, newBreakpoint) => { - if (resp && resp.error) { - deferred.reject(resp); + this.source.setBreakpoint(info, (aResponse, aNewBreakpoint) => { + if (aResponse && aResponse.error) { + deferred.reject(aResponse); } else { - deferred.resolve(newBreakpoint); + deferred.resolve(aNewBreakpoint); } }); }); } else { // The property shouldn't even exist if the condition is blank - if (condition === "") { + if (aCondition === "") { delete this.conditionalExpression; - } else { - this.conditionalExpression = condition; + } + else { + this.conditionalExpression = aCondition; } deferred.resolve(this); } @@ -3201,14 +3145,14 @@ eventSource(BreakpointClient.prototype); /** * Environment clients are used to manipulate the lexical environment actors. * - * @param client DebuggerClient + * @param aClient DebuggerClient * The debugger client parent. - * @param form Object + * @param aForm Object * The form sent across the remote debugging protocol. */ -function EnvironmentClient(client, form) { - this._client = client; - this._form = form; +function EnvironmentClient(aClient, aForm) { + this._client = aClient; + this._form = aForm; this.request = this._client.request; } exports.EnvironmentClient = EnvironmentClient; @@ -3218,9 +3162,7 @@ EnvironmentClient.prototype = { get actor() { return this._form.actor; }, - get _transport() { - return this._client._transport; - }, + get _transport() { return this._client._transport; }, /** * Fetches the bindings introduced by this lexical environment. @@ -3235,8 +3177,8 @@ EnvironmentClient.prototype = { */ assign: DebuggerClient.requester({ type: "assign", - name: arg(0), - value: arg(1) + name: args(0), + value: args(1) }) }; diff --git a/devtools/shared/discovery/discovery.js b/devtools/shared/discovery/discovery.js index a07f21d445e7..d0b49f1290cd 100644 --- a/devtools/shared/discovery/discovery.js +++ b/devtools/shared/discovery/discovery.js @@ -47,8 +47,8 @@ const REPLY_TIMEOUT = 5000; const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {}); XPCOMUtils.defineLazyGetter(this, "converter", () => { - let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Ci.nsIScriptableUnicodeConverter); + let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]. + createInstance(Ci.nsIScriptableUnicodeConverter); conv.charset = "utf8"; return conv; }); @@ -77,8 +77,7 @@ function log(msg) { function Transport(port) { EventEmitter.decorate(this); try { - this.socket = new UDPSocket(port, false, - Services.scriptSecurityManager.getSystemPrincipal()); + this.socket = new UDPSocket(port, false, Services.scriptSecurityManager.getSystemPrincipal()); this.socket.joinMulticast(ADDRESS); this.socket.asyncListen(this); } catch (e) { @@ -147,8 +146,7 @@ function LocalDevice() { Cc["@mozilla.org/settingsService;1"].getService(Ci.nsISettingsService); Services.obs.addObserver(this, "mozsettings-changed", false); } - // Trigger |_get| to load name eagerly - this._get(); + this._get(); // Trigger |_get| to load name eagerly } LocalDevice.SETTING = "devtools.discovery.device"; @@ -346,8 +344,7 @@ Discovery.prototype = { _startListeningForScan: function () { if (this._transports.scan) { - // Already listening - return; + return; // Already listening } log("LISTEN FOR SCAN"); this._transports.scan = new this.Transport(SCAN_PORT); @@ -356,8 +353,7 @@ Discovery.prototype = { _stopListeningForScan: function () { if (!this._transports.scan) { - // Not listening - return; + return; // Not listening } this._transports.scan.off("message", this._onRemoteScan); this._transports.scan.destroy(); @@ -366,8 +362,7 @@ Discovery.prototype = { _startListeningForUpdate: function () { if (this._transports.update) { - // Already listening - return; + return; // Already listening } log("LISTEN FOR UPDATE"); this._transports.update = new this.Transport(UPDATE_PORT); @@ -376,8 +371,7 @@ Discovery.prototype = { _stopListeningForUpdate: function () { if (!this._transports.update) { - // Not listening - return; + return; // Not listening } this._transports.update.off("message", this._onRemoteUpdate); this._transports.update.destroy(); diff --git a/devtools/shared/discovery/tests/unit/.eslintrc.js b/devtools/shared/discovery/tests/unit/.eslintrc.js deleted file mode 100644 index f21b71f67ad0..000000000000 --- a/devtools/shared/discovery/tests/unit/.eslintrc.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = { - // Extend from the shared list of defined globals for mochitests. - "extends": "../../../../.eslintrc.xpcshell.js" -}; \ No newline at end of file diff --git a/devtools/shared/discovery/tests/unit/test_discovery.js b/devtools/shared/discovery/tests/unit/test_discovery.js index 56b0bc1e7c94..c31340b08966 100644 --- a/devtools/shared/discovery/tests/unit/test_discovery.js +++ b/devtools/shared/discovery/tests/unit/test_discovery.js @@ -8,6 +8,7 @@ var Cu = Components.utils; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); const Services = require("Services"); +const promise = require("promise"); const defer = require("devtools/shared/defer"); const EventEmitter = require("devtools/shared/event-emitter"); const discovery = require("devtools/shared/discovery/discovery"); diff --git a/devtools/shared/performance/recording-common.js b/devtools/shared/performance/recording-common.js index 8aa6440e4ee1..d0826bd1881e 100644 --- a/devtools/shared/performance/recording-common.js +++ b/devtools/shared/performance/recording-common.js @@ -9,7 +9,7 @@ * and LegacyPerformanceRecording for helper methods to access data. */ -exports.PerformanceRecordingCommon = { +const PerformanceRecordingCommon = exports.PerformanceRecordingCommon = { // Private fields, only needed when a recording is started or stopped. _console: false, _imported: false, @@ -35,32 +35,18 @@ exports.PerformanceRecordingCommon = { * Helper methods for returning the status of the recording. * These methods should be consistent on both the front and actor. */ - isRecording: function () { - return this._recording; - }, - isCompleted: function () { - return this._completed || this.isImported(); - }, - isFinalizing: function () { - return !this.isRecording() && !this.isCompleted(); - }, - isConsole: function () { - return this._console; - }, - isImported: function () { - return this._imported; - }, + isRecording: function () { return this._recording; }, + isCompleted: function () { return this._completed || this.isImported(); }, + isFinalizing: function () { return !this.isRecording() && !this.isCompleted(); }, + isConsole: function () { return this._console; }, + isImported: function () { return this._imported; }, /** * Helper methods for returning configuration for the recording. * These methods should be consistent on both the front and actor. */ - getConfiguration: function () { - return this._configuration; - }, - getLabel: function () { - return this._label; - }, + getConfiguration: function () { return this._configuration; }, + getLabel: function () { return this._label; }, /** * Gets duration of this recording, in milliseconds. @@ -73,43 +59,25 @@ exports.PerformanceRecordingCommon = { // the duration from the profiler; if between recording and being finalized, // use the last estimated duration. if (this.isRecording()) { - this._estimatedDuration = Date.now() - this._localStartTime; - return this._estimatedDuration; + return this._estimatedDuration = Date.now() - this._localStartTime; + } else { + return this._duration || this._estimatedDuration || 0; } - return this._duration || this._estimatedDuration || 0; }, /** * Helper methods for returning recording data. * These methods should be consistent on both the front and actor. */ - getMarkers: function () { - return this._markers; - }, - getFrames: function () { - return this._frames; - }, - getMemory: function () { - return this._memory; - }, - getTicks: function () { - return this._ticks; - }, - getAllocations: function () { - return this._allocations; - }, - getProfile: function () { - return this._profile; - }, - getHostSystemInfo: function () { - return this._systemHost; - }, - getClientSystemInfo: function () { - return this._systemClient; - }, - getStartingBufferStatus: function () { - return this._startingBufferStatus; - }, + getMarkers: function () { return this._markers; }, + getFrames: function () { return this._frames; }, + getMemory: function () { return this._memory; }, + getTicks: function () { return this._ticks; }, + getAllocations: function () { return this._allocations; }, + getProfile: function () { return this._profile; }, + getHostSystemInfo: function () { return this._systemHost; }, + getClientSystemInfo: function () { return this._systemClient; }, + getStartingBufferStatus: function () { return this._startingBufferStatus; }, getAllData: function () { let label = this.getLabel(); @@ -124,18 +92,6 @@ exports.PerformanceRecordingCommon = { let systemHost = this.getHostSystemInfo(); let systemClient = this.getClientSystemInfo(); - return { - label, - duration, - markers, - frames, - memory, - ticks, - allocations, - profile, - configuration, - systemHost, - systemClient - }; + return { label, duration, markers, frames, memory, ticks, allocations, profile, configuration, systemHost, systemClient }; }, }; diff --git a/devtools/shared/performance/recording-utils.js b/devtools/shared/performance/recording-utils.js index 3b9c4cbca0fd..64ed12c71f1c 100644 --- a/devtools/shared/performance/recording-utils.js +++ b/devtools/shared/performance/recording-utils.js @@ -3,6 +3,7 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; +const { Cc, Ci, Cu, Cr } = require("chrome"); loader.lazyRequireGetter(this, "extend", "sdk/util/object", true); @@ -15,8 +16,7 @@ function mapRecordingOptions(type, options) { if (type === "profiler") { return { entries: options.bufferSize, - interval: options.sampleFrequency ? (1000 / (options.sampleFrequency * 1000)) - : void 0 + interval: options.sampleFrequency ? (1000 / (options.sampleFrequency * 1000)) : void 0 }; } @@ -568,8 +568,7 @@ UniqueStacks.prototype.getOrAddFrameIndex = function (frame) { let implementationIndex = this.getOrAddStringIndex(frame.implementation); // Super dumb. - let hash = `${locationIndex} ${implementationIndex || ""} ` + - `${frame.line || ""} ${frame.category || ""}`; + let hash = `${locationIndex} ${implementationIndex || ""} ${frame.line || ""} ${frame.category || ""}`; let index = frameHash[hash]; if (index !== undefined) { diff --git a/devtools/shared/performance/test/.eslintrc.js b/devtools/shared/performance/test/.eslintrc.js deleted file mode 100644 index 90ed7706421b..000000000000 --- a/devtools/shared/performance/test/.eslintrc.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = { - // Extend from the shared list of defined globals for mochitests. - "extends": "../../../.eslintrc.xpcshell.js" -}; \ No newline at end of file diff --git a/devtools/shared/performance/test/head.js b/devtools/shared/performance/test/head.js index 414831c96443..9e7748055723 100644 --- a/devtools/shared/performance/test/head.js +++ b/devtools/shared/performance/test/head.js @@ -1,10 +1,7 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* exported require */ - "use strict"; -var { utils: Cu } = Components; +var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; var { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); diff --git a/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js b/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js index 141395652275..6429eff2d434 100644 --- a/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js +++ b/devtools/shared/performance/test/test_perf-utils-allocations-to-samples.js @@ -1,8 +1,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - /** * Tests if allocations data received from the performance actor is properly * converted to something that follows the same structure as the samples data @@ -67,15 +65,9 @@ var EXPECTED_OUTPUT = { }, "data": [ null, - - // x (A:1:2) - [ null, 1 ], - - // x (A:1:2) > y (B:3:4) - [ 1, 2 ], - - // x (A:1:2) > y (B:3:4) > C:5:6 - [ 2, 3 ] + [ null, 1 ], // x (A:1:2) + [ 1, 2 ], // x (A:1:2) > y (B:3:4) + [ 2, 3 ] // x (A:1:2) > y (B:3:4) > C:5:6 ] }, frameTable: { diff --git a/devtools/shared/qrcode/index.js b/devtools/shared/qrcode/index.js index 7bf97e1babc0..ec3442426402 100644 --- a/devtools/shared/qrcode/index.js +++ b/devtools/shared/qrcode/index.js @@ -4,6 +4,7 @@ "use strict"; +const { Cu } = require("chrome"); const promise = require("promise"); const defer = require("devtools/shared/defer"); diff --git a/devtools/shared/qrcode/tests/unit/.eslintrc.js b/devtools/shared/qrcode/tests/unit/.eslintrc.js deleted file mode 100644 index f21b71f67ad0..000000000000 --- a/devtools/shared/qrcode/tests/unit/.eslintrc.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = { - // Extend from the shared list of defined globals for mochitests. - "extends": "../../../../.eslintrc.xpcshell.js" -}; \ No newline at end of file diff --git a/devtools/shared/security/auth.js b/devtools/shared/security/auth.js index 52c9070b77bc..9272f602ebdc 100644 --- a/devtools/shared/security/auth.js +++ b/devtools/shared/security/auth.js @@ -8,6 +8,7 @@ var { Ci, Cc } = require("chrome"); var Services = require("Services"); +var promise = require("promise"); var defer = require("devtools/shared/defer"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); var { dumpn, dumpv } = DevToolsUtils; @@ -407,8 +408,7 @@ OOBCert.Client.prototype = { }), _createRandom() { - // 16 bytes / 128 bits - const length = 16; + const length = 16; // 16 bytes / 128 bits let rng = Cc["@mozilla.org/security/random-generator;1"] .createInstance(Ci.nsIRandomGenerator); let bytes = rng.generateRandomBytes(length); @@ -545,11 +545,9 @@ OOBCert.Server.prototype = { switch (authResult) { case AuthenticationResult.ALLOW_PERSIST: case AuthenticationResult.ALLOW: - // Further processing - break; + break; // Further processing default: - // Abort for any negative results - return authResult; + return authResult; // Abort for any negative results } // Examine additional data for authentication diff --git a/devtools/shared/security/cert.js b/devtools/shared/security/cert.js index 7c101f3dbf0e..7dbeded63116 100644 --- a/devtools/shared/security/cert.js +++ b/devtools/shared/security/cert.js @@ -7,6 +7,7 @@ "use strict"; var { Ci, Cc } = require("chrome"); +var promise = require("promise"); var defer = require("devtools/shared/defer"); var DevToolsUtils = require("devtools/shared/DevToolsUtils"); DevToolsUtils.defineLazyGetter(this, "localCertService", () => { diff --git a/devtools/shared/security/socket.js b/devtools/shared/security/socket.js index 64d882c01b5d..068a8ea81f0a 100644 --- a/devtools/shared/security/socket.js +++ b/devtools/shared/security/socket.js @@ -6,7 +6,7 @@ "use strict"; -var { Ci, Cc, CC, Cr } = require("chrome"); +var { Ci, Cc, CC, Cr, Cu } = require("chrome"); // Ensure PSM is initialized to support TLS sockets Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports); @@ -143,8 +143,7 @@ var _getTransport = Task.async(function* (settings) { let attempt = yield _attemptTransport(settings); if (attempt.transport) { - // Success - return attempt.transport; + return attempt.transport; // Success } // If the server cert failed validation, store a temporary override and make @@ -157,8 +156,7 @@ var _getTransport = Task.async(function* (settings) { attempt = yield _attemptTransport(settings); if (attempt.transport) { - // Success - return attempt.transport; + return attempt.transport; // Success } throw new Error("Connection failed even after cert override"); @@ -358,7 +356,7 @@ function _storeCertOverride(s, host, port) { let overrideBits = Ci.nsICertOverrideService.ERROR_UNTRUSTED | Ci.nsICertOverrideService.ERROR_MISMATCH; certOverrideService.rememberValidityOverride(host, port, cert, overrideBits, - true /* temporary */); // eslint-disable-line + true /* temporary */); } /** diff --git a/devtools/shared/security/tests/chrome/.eslintrc.js b/devtools/shared/security/tests/chrome/.eslintrc.js deleted file mode 100644 index 6dc0ab32b6e9..000000000000 --- a/devtools/shared/security/tests/chrome/.eslintrc.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = { - // Extend from the shared list of defined globals for mochitests. - "extends": "../../../../../testing/mochitest/chrome.eslintrc.js" -}; diff --git a/devtools/shared/security/tests/chrome/test_websocket-transport.html b/devtools/shared/security/tests/chrome/test_websocket-transport.html index edcb5b2ffad7..542206ecfbfe 100644 --- a/devtools/shared/security/tests/chrome/test_websocket-transport.html +++ b/devtools/shared/security/tests/chrome/test_websocket-transport.html @@ -9,9 +9,7 @@ diff --git a/devtools/shared/security/tests/unit/head_dbg.js b/devtools/shared/security/tests/unit/head_dbg.js index 790675c56dc7..f3b2a9a9744d 100644 --- a/devtools/shared/security/tests/unit/head_dbg.js +++ b/devtools/shared/security/tests/unit/head_dbg.js @@ -2,14 +2,20 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; +var Cc = Components.classes; +var Ci = Components.interfaces; +var Cu = Components.utils; +var Cr = Components.results; +var CC = Components.Constructor; -/* exported defer, DebuggerClient, initTestDebuggerServer */ - -const { classes: Cc, interfaces: Ci, utils: Cu } = Components; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); +const promise = require("promise"); const defer = require("devtools/shared/defer"); +const { Task } = require("devtools/shared/task"); + const Services = require("Services"); +const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const xpcInspector = require("xpcInspector"); const { DebuggerServer } = require("devtools/server/main"); const { DebuggerClient } = require("devtools/shared/client/main"); @@ -25,43 +31,43 @@ Services.prefs.setBoolPref("devtools.debugger.remote-enabled", true); // Fast timeout for TLS tests Services.prefs.setIntPref("devtools.remote.tls-handshake-timeout", 1000); -// Convert an nsIScriptError 'flags' value into an appropriate string. -function scriptErrorFlagsToKind(flags) { - let kind; - if (flags & Ci.nsIScriptError.warningFlag) { +// Convert an nsIScriptError 'aFlags' value into an appropriate string. +function scriptErrorFlagsToKind(aFlags) { + var kind; + if (aFlags & Ci.nsIScriptError.warningFlag) kind = "warning"; - } - if (flags & Ci.nsIScriptError.exceptionFlag) { + if (aFlags & Ci.nsIScriptError.exceptionFlag) kind = "exception"; - } else { + else kind = "error"; - } - if (flags & Ci.nsIScriptError.strictFlag) { + if (aFlags & Ci.nsIScriptError.strictFlag) kind = "strict " + kind; - } return kind; } // Register a console listener, so console messages don't just disappear // into the ether. +var errorCount = 0; var listener = { - observe: function (message) { - let string; + observe: function (aMessage) { + errorCount++; try { - message.QueryInterface(Ci.nsIScriptError); - dump(message.sourceName + ":" + message.lineNumber + ": " + - scriptErrorFlagsToKind(message.flags) + ": " + - message.errorMessage + "\n"); - string = message.errorMessage; - } catch (ex) { + // If we've been given an nsIScriptError, then we can print out + // something nicely formatted, for tools like Emacs to pick up. + var scriptError = aMessage.QueryInterface(Ci.nsIScriptError); + dump(aMessage.sourceName + ":" + aMessage.lineNumber + ": " + + scriptErrorFlagsToKind(aMessage.flags) + ": " + + aMessage.errorMessage + "\n"); + var string = aMessage.errorMessage; + } catch (x) { // Be a little paranoid with message, as the whole goal here is to lose // no information. try { - string = "" + message.message; - } catch (e) { - string = ""; + var string = "" + aMessage.message; + } catch (x) { + var string = ""; } } @@ -71,7 +77,7 @@ var listener = { } // Print in most cases, but ignore the "strict" messages - if (!(message.flags & Ci.nsIScriptError.strictFlag)) { + if (!(aMessage.flags & Ci.nsIScriptError.strictFlag)) { do_print("head_dbg.js got console message: " + string + "\n"); } } diff --git a/devtools/shared/security/tests/unit/test_oob_cert_auth.js b/devtools/shared/security/tests/unit/test_oob_cert_auth.js index e37a0f589d80..1e820af52b2e 100644 --- a/devtools/shared/security/tests/unit/test_oob_cert_auth.js +++ b/devtools/shared/security/tests/unit/test_oob_cert_auth.js @@ -38,8 +38,7 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - // Skip prompt for tests - serverAuth.receiveOOB = () => oobData.promise; + serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests let listener = DebuggerServer.createListener(); ok(listener, "Socket listener created"); @@ -99,8 +98,7 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - // Skip prompt for tests - serverAuth.receiveOOB = () => oobData.promise; + serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests let listener = DebuggerServer.createListener(); ok(listener, "Socket listener created"); @@ -163,8 +161,7 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - // Skip prompt for tests - serverAuth.receiveOOB = () => oobData.promise; + serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests let clientAuth = new AuthenticatorType.Client(); clientAuth.sendOOB = ({ oob }) => { @@ -218,8 +215,7 @@ add_task(function* () { serverAuth.allowConnection = () => { return DebuggerServer.AuthenticationResult.ALLOW; }; - // Skip prompt for tests - serverAuth.receiveOOB = () => oobData.promise; + serverAuth.receiveOOB = () => oobData.promise; // Skip prompt for tests let clientAuth = new AuthenticatorType.Client(); clientAuth.sendOOB = ({ oob }) => { diff --git a/devtools/shared/security/tests/unit/testactors.js b/devtools/shared/security/tests/unit/testactors.js index 1a170cba78e9..80d5d4e18abe 100644 --- a/devtools/shared/security/tests/unit/testactors.js +++ b/devtools/shared/security/tests/unit/testactors.js @@ -1,8 +1,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - const { ActorPool, appendExtraActors, createExtraActors } = require("devtools/server/actors/common"); const { RootActor } = require("devtools/server/actors/root"); @@ -11,8 +9,8 @@ const { DebuggerServer } = require("devtools/server/main"); const promise = require("promise"); var gTestGlobals = []; -DebuggerServer.addTestGlobal = function (global) { - gTestGlobals.push(global); +DebuggerServer.addTestGlobal = function (aGlobal) { + gTestGlobals.push(aGlobal); }; // A mock tab list, for use by tests. This simply presents each global in @@ -22,18 +20,18 @@ DebuggerServer.addTestGlobal = function (global) { // As implemented now, we consult gTestGlobals when we're constructed, not // when we're iterated over, so tests have to add their globals before the // root actor is created. -function TestTabList(connection) { - this.conn = connection; +function TestTabList(aConnection) { + this.conn = aConnection; // An array of actors for each global added with // DebuggerServer.addTestGlobal. this._tabActors = []; // A pool mapping those actors' names to the actors. - this._tabActorPool = new ActorPool(connection); + this._tabActorPool = new ActorPool(aConnection); for (let global of gTestGlobals) { - let actor = new TestTabActor(connection, global); + let actor = new TestTabActor(aConnection, global); actor.selected = false; this._tabActors.push(actor); this._tabActorPool.addActor(actor); @@ -42,7 +40,7 @@ function TestTabList(connection) { this._tabActors[0].selected = true; } - connection.addActorPool(this._tabActorPool); + aConnection.addActorPool(this._tabActorPool); } TestTabList.prototype = { @@ -52,18 +50,18 @@ TestTabList.prototype = { } }; -function createRootActor(connection) { - let root = new RootActor(connection, { - tabList: new TestTabList(connection), +function createRootActor(aConnection) { + let root = new RootActor(aConnection, { + tabList: new TestTabList(aConnection), globalActorFactories: DebuggerServer.globalActorFactories }); root.applicationType = "xpcshell-tests"; return root; } -function TestTabActor(connection, global) { - this.conn = connection; - this._global = global; +function TestTabActor(aConnection, aGlobal) { + this.conn = aConnection; + this._global = aGlobal; this._threadActor = new ThreadActor(this, this._global); this.conn.addActor(this._threadActor); this._attached = false; @@ -98,7 +96,7 @@ TestTabActor.prototype = { return response; }, - onAttach: function (request) { + onAttach: function (aRequest) { this._attached = true; let response = { type: "tabAttached", threadActor: this._threadActor.actorID }; @@ -107,9 +105,9 @@ TestTabActor.prototype = { return response; }, - onDetach: function (request) { + onDetach: function (aRequest) { if (!this._attached) { - return { "error": "wrongState" }; + return { "error":"wrongState" }; } return { type: "detached" }; }, diff --git a/devtools/shared/shims/event-emitter.js b/devtools/shared/shims/event-emitter.js index bf648e373ad4..6b3672162917 100644 --- a/devtools/shared/shims/event-emitter.js +++ b/devtools/shared/shims/event-emitter.js @@ -9,13 +9,10 @@ * specific path. */ -(function (factory) { - // Module boilerplate - if (this.module && module.id.indexOf("event-emitter") >= 0) { - // require +(function (factory) { // Module boilerplate + if (this.module && module.id.indexOf("event-emitter") >= 0) { // require factory.call(this, require, exports, module); - } else { - // Cu.import + } else { // Cu.import const Cu = Components.utils; const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); diff --git a/devtools/shared/tests/browser/browser_async_storage.js b/devtools/shared/tests/browser/browser_async_storage.js index 141965cf00b4..4329d639aee2 100644 --- a/devtools/shared/tests/browser/browser_async_storage.js +++ b/devtools/shared/tests/browser/browser_async_storage.js @@ -30,7 +30,7 @@ add_task(function* () { }); add_task(function* () { - let object = { + var object = { x: 1, y: "foo", z: true diff --git a/devtools/shared/tests/unit/exposeLoader.js b/devtools/shared/tests/unit/exposeLoader.js index 7c8acdd75945..949640a03e4e 100644 --- a/devtools/shared/tests/unit/exposeLoader.js +++ b/devtools/shared/tests/unit/exposeLoader.js @@ -1,8 +1,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - exports.exerciseLazyRequire = (name, path) => { const o = {}; loader.lazyRequireGetter(o, name, path); diff --git a/devtools/shared/tests/unit/head_devtools.js b/devtools/shared/tests/unit/head_devtools.js index 2854d9389758..f0f47c93ac15 100644 --- a/devtools/shared/tests/unit/head_devtools.js +++ b/devtools/shared/tests/unit/head_devtools.js @@ -1,12 +1,13 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -/* exported DevToolsUtils, DevToolsLoader */ - "use strict"; +var Cc = Components.classes; +var Ci = Components.interfaces; +var Cu = Components.utils; +var Cr = Components.results; -const { classes: Cc, interfaces: Ci, utils: Cu } = Components; -const { require, DevToolsLoader } = Cu.import("resource://devtools/shared/Loader.jsm", {}); +const {require, DevToolsLoader, devtools} = Cu.import("resource://devtools/shared/Loader.jsm", {}); const DevToolsUtils = require("devtools/shared/DevToolsUtils"); const flags = require("devtools/shared/flags"); @@ -22,22 +23,25 @@ do_register_cleanup(() => { // failures, set this to true. var ALLOW_CONSOLE_ERRORS = false; +var errorCount = 0; var listener = { - observe: function (message) { - let string; + observe: function (aMessage) { + errorCount++; try { - message.QueryInterface(Ci.nsIScriptError); - dump(message.sourceName + ":" + message.lineNumber + ": " + - scriptErrorFlagsToKind(message.flags) + ": " + - message.errorMessage + "\n"); - string = message.errorMessage; - } catch (ex) { + // If we've been given an nsIScriptError, then we can print out + // something nicely formatted, for tools like Emacs to pick up. + var scriptError = aMessage.QueryInterface(Ci.nsIScriptError); + dump(aMessage.sourceName + ":" + aMessage.lineNumber + ": " + + scriptErrorFlagsToKind(aMessage.flags) + ": " + + aMessage.errorMessage + "\n"); + var string = aMessage.errorMessage; + } catch (x) { // Be a little paranoid with message, as the whole goal here is to lose // no information. try { - string = "" + message.message; - } catch (e) { - string = ""; + var string = "" + aMessage.message; + } catch (x) { + var string = ""; } } diff --git a/devtools/shared/tests/unit/test_assert.js b/devtools/shared/tests/unit/test_assert.js index e5fe01974139..b871717511a4 100644 --- a/devtools/shared/tests/unit/test_assert.js +++ b/devtools/shared/tests/unit/test_assert.js @@ -2,8 +2,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test DevToolsUtils.assert ALLOW_CONSOLE_ERRORS = true; @@ -34,6 +32,5 @@ function run_test() { } ok(assertionFailed, - "The assertion should have failed, which should throw an error when assertions " + - "are enabled."); + "The assertion should have failed, which should throw an error when assertions are enabled."); } diff --git a/devtools/shared/tests/unit/test_async-utils.js b/devtools/shared/tests/unit/test_async-utils.js index 8c640c473bca..2b09b82608ca 100644 --- a/devtools/shared/tests/unit/test_async-utils.js +++ b/devtools/shared/tests/unit/test_async-utils.js @@ -2,8 +2,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test async-utils.js const {Task} = require("devtools/shared/task"); @@ -62,13 +60,12 @@ function test_async_return(async) { function test_async_throw(async) { let obj = { method: async(function* () { - throw new Error("boom"); + throw "boom"; }) }; return obj.method().then(null, error => { - do_check_true(error instanceof Error); - do_check_eq(error.message, "boom"); + do_check_eq(error, "boom"); }); } @@ -119,6 +116,7 @@ function test_async_once() { function test_async_invoke() { return Task.spawn(function* () { function func(a, b, expectedThis, callback) { + "use strict"; do_check_eq(a, "foo"); do_check_eq(b, "bar"); do_check_eq(this, expectedThis); @@ -129,11 +127,13 @@ function test_async_invoke() { let callResult = yield promiseCall(func, "foo", "bar", undefined); do_check_eq(callResult, "foobar"); + // Test invoke. let obj = { method: func }; let invokeResult = yield promiseInvoke(obj, obj.method, "foo", "bar", obj); do_check_eq(invokeResult, "foobar"); + // Test passing multiple values to the callback. function multipleResults(callback) { callback("foo", "bar"); @@ -144,14 +144,14 @@ function test_async_invoke() { do_check_eq(results[0], "foo"); do_check_eq(results[1], "bar"); + // Test throwing from the function. function thrower() { - throw new Error("boom"); + throw "boom"; } yield promiseCall(thrower).then(null, error => { - do_check_true(error instanceof Error); - do_check_eq(error.message, "boom"); + do_check_eq(error, "boom"); }); }); } diff --git a/devtools/shared/tests/unit/test_console_filtering.js b/devtools/shared/tests/unit/test_console_filtering.js index e126981d0cfa..6ee620ebbe6f 100644 --- a/devtools/shared/tests/unit/test_console_filtering.js +++ b/devtools/shared/tests/unit/test_console_filtering.js @@ -11,19 +11,19 @@ var seenMessages = 0; var seenTypes = 0; var callback = { - onConsoleAPICall: function (message) { - if (message.consoleID && message.consoleID == "addon/foo") { - do_check_eq(message.level, "warn"); - do_check_eq(message.arguments[0], "Warning from foo"); + onConsoleAPICall: function (aMessage) { + if (aMessage.consoleID && aMessage.consoleID == "addon/foo") { + do_check_eq(aMessage.level, "warn"); + do_check_eq(aMessage.arguments[0], "Warning from foo"); seenTypes |= 1; - } else if (message.originAttributes && - message.originAttributes.addonId == "bar") { - do_check_eq(message.level, "error"); - do_check_eq(message.arguments[0], "Error from bar"); + } else if (aMessage.originAttributes && + aMessage.originAttributes.addonId == "bar") { + do_check_eq(aMessage.level, "error"); + do_check_eq(aMessage.arguments[0], "Error from bar"); seenTypes |= 2; } else { - do_check_eq(message.level, "log"); - do_check_eq(message.arguments[0], "Hello from default console"); + do_check_eq(aMessage.level, "log"); + do_check_eq(aMessage.arguments[0], "Hello from default console"); seenTypes |= 4; } seenMessages++; diff --git a/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js b/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js index 452d01847306..d729e747398d 100644 --- a/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js +++ b/devtools/shared/tests/unit/test_defineLazyPrototypeGetter.js @@ -1,13 +1,13 @@ +/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test DevToolsUtils.defineLazyPrototypeGetter function Class() {} DevToolsUtils.defineLazyPrototypeGetter(Class.prototype, "foo", () => []); + function run_test() { test_prototype_attributes(); test_instance_attributes(); diff --git a/devtools/shared/tests/unit/test_executeSoon.js b/devtools/shared/tests/unit/test_executeSoon.js index 78bdcd6a4ea3..6154a3e67e35 100644 --- a/devtools/shared/tests/unit/test_executeSoon.js +++ b/devtools/shared/tests/unit/test_executeSoon.js @@ -11,6 +11,7 @@ */ var { executeSoon } = require("devtools/shared/DevToolsUtils"); +var promise = require("promise"); var defer = require("devtools/shared/defer"); var Services = require("Services"); diff --git a/devtools/shared/tests/unit/test_flatten.js b/devtools/shared/tests/unit/test_flatten.js index 11c2ac047479..f5a186770cc0 100644 --- a/devtools/shared/tests/unit/test_flatten.js +++ b/devtools/shared/tests/unit/test_flatten.js @@ -2,8 +2,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test ThreadSafeDevToolsUtils.flatten function run_test() { diff --git a/devtools/shared/tests/unit/test_independent_loaders.js b/devtools/shared/tests/unit/test_independent_loaders.js index 6d3aaead6935..20abed27d208 100644 --- a/devtools/shared/tests/unit/test_independent_loaders.js +++ b/devtools/shared/tests/unit/test_independent_loaders.js @@ -1,8 +1,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - /** * Ensure that each instance of the Dev Tools loader contains its own loader * instance, and also returns unique objects. This ensures there is no sharing diff --git a/devtools/shared/tests/unit/test_isSet.js b/devtools/shared/tests/unit/test_isSet.js index a9e1fcafa9ab..f85d6ae3c3f1 100644 --- a/devtools/shared/tests/unit/test_isSet.js +++ b/devtools/shared/tests/unit/test_isSet.js @@ -2,8 +2,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test ThreadSafeDevToolsUtils.isSet function run_test() { diff --git a/devtools/shared/tests/unit/test_require.js b/devtools/shared/tests/unit/test_require.js index 2d10d1e0f8c0..005e5665633e 100644 --- a/devtools/shared/tests/unit/test_require.js +++ b/devtools/shared/tests/unit/test_require.js @@ -1,8 +1,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test require // Ensure that DevtoolsLoader.require doesn't spawn multiple diff --git a/devtools/shared/tests/unit/test_require_lazy.js b/devtools/shared/tests/unit/test_require_lazy.js index d545653d6244..8ef5a7d23e7b 100644 --- a/devtools/shared/tests/unit/test_require_lazy.js +++ b/devtools/shared/tests/unit/test_require_lazy.js @@ -1,8 +1,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test devtools.lazyRequireGetter function run_test() { @@ -20,8 +18,7 @@ function run_test() { const o2 = {}; let loader = new DevToolsLoader(); - // We have to init the loader by loading any module before - // lazyRequireGetter is available + // We have to init the loader by loading any module before lazyRequireGetter is available loader.require("devtools/shared/DevToolsUtils"); loader.lazyRequireGetter(o2, name, path); diff --git a/devtools/shared/tests/unit/test_require_raw.js b/devtools/shared/tests/unit/test_require_raw.js index 1cfd0d3f3d22..5bec82b55bb0 100644 --- a/devtools/shared/tests/unit/test_require_raw.js +++ b/devtools/shared/tests/unit/test_require_raw.js @@ -1,8 +1,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test require using "raw!". function run_test() { diff --git a/devtools/shared/tests/unit/test_safeErrorString.js b/devtools/shared/tests/unit/test_safeErrorString.js index afde7d7c97c5..9892f34d1e63 100644 --- a/devtools/shared/tests/unit/test_safeErrorString.js +++ b/devtools/shared/tests/unit/test_safeErrorString.js @@ -2,8 +2,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test DevToolsUtils.safeErrorString function run_test() { diff --git a/devtools/shared/tests/unit/test_stack.js b/devtools/shared/tests/unit/test_stack.js index 7342526e45eb..ef747c83f6de 100644 --- a/devtools/shared/tests/unit/test_stack.js +++ b/devtools/shared/tests/unit/test_stack.js @@ -1,8 +1,6 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -"use strict"; - // Test stack.js. function run_test() { diff --git a/devtools/shared/touch/simulator-content.js b/devtools/shared/touch/simulator-content.js index 6c9f3f2bfdec..0b10579ca586 100644 --- a/devtools/shared/touch/simulator-content.js +++ b/devtools/shared/touch/simulator-content.js @@ -1,7 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - /* globals addMessageListener, sendAsyncMessage, docShell */ + /* globals addMessageListener, sendAsyncMessage */ "use strict"; const { utils: Cu } = Components; diff --git a/devtools/shared/touch/simulator-core.js b/devtools/shared/touch/simulator-core.js index 52ff5c124df2..6933f9207cbd 100644 --- a/devtools/shared/touch/simulator-core.js +++ b/devtools/shared/touch/simulator-core.js @@ -1,9 +1,6 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* global XPCNativeWrapper */ - "use strict"; const { Ci, Cu } = require("chrome"); @@ -275,14 +272,12 @@ SimulatorCore.prototype = { } } let unwrapped = XPCNativeWrapper.unwrap(target); - /* eslint-disable no-inline-comments */ unwrapped.sendTouchEvent(name, clone([0]), // event type, id clone([evt.clientX]), // x clone([evt.clientY]), // y clone([1]), clone([1]), // rx, ry clone([0]), clone([0]), // rotation, force 1); // count - /* eslint-enable no-inline-comments */ return; } let document = target.ownerDocument; @@ -344,10 +339,10 @@ SimulatorCore.prototype = { let utils = content.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils); - let allowZoom = {}; - let minZoom = {}; - let maxZoom = {}; - let autoSize = {}; + let allowZoom = {}, + minZoom = {}, + maxZoom = {}, + autoSize = {}; utils.getViewportInfo(content.innerWidth, content.innerHeight, {}, allowZoom, minZoom, maxZoom, {}, {}, autoSize); @@ -357,15 +352,14 @@ SimulatorCore.prototype = { // delay. But Firefox didn't support this property now, we can't get // this value from utils.getVisitedDependentComputedStyle() to check // if we should suppress 300ms delay. - /* eslint-disable no-inline-comments */ if (!allowZoom.value || // user-scalable = no minZoom.value === maxZoom.value || // minimum-scale = maximum-scale autoSize.value // width = device-width ) { - /* eslint-enable no-inline-comments */ return 0; + } else { + return 300; } - return 300; } }; From 5bbe0834de955a3e69a898c06d4856cf7dae17f3 Mon Sep 17 00:00:00 2001 From: Fred Lin Date: Tue, 27 Dec 2016 15:03:15 +0800 Subject: [PATCH 156/229] Bug 1325914 - fix react-dev warnings; r=rickychien MozReview-Commit-ID: GJ4ppGnXHLu --HG-- extra : rebase_source : 8095f9b6873b8a249e0f9ab8940f9eb77ec66679 --- devtools/client/netmonitor/components/filter-buttons.js | 5 +++-- .../client/netmonitor/shared/components/security-panel.js | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/devtools/client/netmonitor/components/filter-buttons.js b/devtools/client/netmonitor/components/filter-buttons.js index 97114dc13913..5fa69e1ebf90 100644 --- a/devtools/client/netmonitor/components/filter-buttons.js +++ b/devtools/client/netmonitor/components/filter-buttons.js @@ -21,6 +21,7 @@ function FilterButtons({ return button({ id: `requests-menu-filter-${type}-button`, + key: type, className: classList.join(" "), "data-key": type, onClick: toggleRequestFilterType, @@ -32,8 +33,8 @@ function FilterButtons({ } FilterButtons.propTypes = { - state: PropTypes.object.isRequired, - toggleRequestFilterType: PropTypes.func.iRequired, + requestFilterTypes: PropTypes.object.isRequired, + toggleRequestFilterType: PropTypes.func.isRequired, }; module.exports = connect( diff --git a/devtools/client/netmonitor/shared/components/security-panel.js b/devtools/client/netmonitor/shared/components/security-panel.js index 75d7373ed209..83a6a39081bd 100644 --- a/devtools/client/netmonitor/shared/components/security-panel.js +++ b/devtools/client/netmonitor/shared/components/security-panel.js @@ -104,8 +104,8 @@ function SecurityPanel({ SecurityPanel.displayName = "SecurityPanel"; SecurityPanel.propTypes = { - securityInfo: PropTypes.object.isRequired, - url: PropTypes.string.isRequired, + securityInfo: PropTypes.object, + url: PropTypes.string, }; function renderValue(weaknessReasons = [], props) { @@ -124,7 +124,7 @@ function renderValue(weaknessReasons = [], props) { // Display one line selectable text for security details input({ className: "textbox-input", - readonly: "true", + readOnly: "true", value, }) , From 4b4ad87d9acd869d4dbc3f5742c3aa67b9d5933d Mon Sep 17 00:00:00 2001 From: Phil Ringnalda Date: Thu, 29 Dec 2016 21:05:04 -0800 Subject: [PATCH 157/229] Backed out changeset 6f1dd8377713 (bug 1326340) for browser_parsable_css.js failure MozReview-Commit-ID: KVUOe1Pkiyq --- browser/extensions/pdfjs/README.mozilla | 2 +- browser/extensions/pdfjs/content/PdfJs.jsm | 1 + .../pdfjs/content/PdfJsTelemetry.jsm | 2 +- .../pdfjs/content/PdfStreamConverter.jsm | 1 + .../pdfjs/content/PdfjsChromeUtils.jsm | 1 + .../pdfjs/content/PdfjsContentUtils.jsm | 1 + browser/extensions/pdfjs/content/build/pdf.js | 52 +--------- .../pdfjs/content/build/pdf.worker.js | 94 +++---------------- .../pdfjs/content/pdfjschildbootstrap.js | 1 + browser/extensions/pdfjs/content/web/l10n.js | 1 + .../extensions/pdfjs/content/web/viewer.css | 18 +--- .../extensions/pdfjs/content/web/viewer.js | 24 ++--- 12 files changed, 36 insertions(+), 162 deletions(-) diff --git a/browser/extensions/pdfjs/README.mozilla b/browser/extensions/pdfjs/README.mozilla index 2e82c74f2c6a..b849113a5a09 100644 --- a/browser/extensions/pdfjs/README.mozilla +++ b/browser/extensions/pdfjs/README.mozilla @@ -1,3 +1,3 @@ This is the pdf.js project output, https://github.com/mozilla/pdf.js -Current extension version is: 1.6.418 +Current extension version is: 1.6.401 diff --git a/browser/extensions/pdfjs/content/PdfJs.jsm b/browser/extensions/pdfjs/content/PdfJs.jsm index d67a6c5f8486..c25804cdec48 100644 --- a/browser/extensions/pdfjs/content/PdfJs.jsm +++ b/browser/extensions/pdfjs/content/PdfJs.jsm @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils, PdfjsChromeUtils, PdfjsContentUtils, PdfStreamConverter */ diff --git a/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm b/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm index 0d34cd50e67c..275da9d87b31 100644 --- a/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm +++ b/browser/extensions/pdfjs/content/PdfJsTelemetry.jsm @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint max-len: ["error", 100] */ +/* jshint esnext:true, maxlen: 100 */ /* globals Components, Services */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/PdfStreamConverter.jsm b/browser/extensions/pdfjs/content/PdfStreamConverter.jsm index 128d8aad2ab0..3b9f9de26788 100644 --- a/browser/extensions/pdfjs/content/PdfStreamConverter.jsm +++ b/browser/extensions/pdfjs/content/PdfStreamConverter.jsm @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils, NetUtil, PrivateBrowsingUtils, dump, NetworkManager, PdfJsTelemetry, PdfjsContentUtils */ diff --git a/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm b/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm index 2d97206f967e..57f07af92ccd 100644 --- a/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm +++ b/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm b/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm index 4318fbfdf96e..3dec5f38902d 100644 --- a/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm +++ b/browser/extensions/pdfjs/content/PdfjsContentUtils.jsm @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* jshint esnext:true */ /* globals Components, Services, XPCOMUtils */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/build/pdf.js b/browser/extensions/pdfjs/content/build/pdf.js index 3183afb10e30..d5b17e9b3359 100644 --- a/browser/extensions/pdfjs/content/build/pdf.js +++ b/browser/extensions/pdfjs/content/build/pdf.js @@ -23,8 +23,8 @@ } }(this, function (exports) { 'use strict'; - var pdfjsVersion = '1.6.418'; - var pdfjsBuild = '59afb4b9'; + var pdfjsVersion = '1.6.401'; + var pdfjsBuild = 'b629be05'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { @@ -1808,15 +1808,6 @@ switch (fieldType) { case 'Tx': return new TextWidgetAnnotationElement(parameters); - case 'Btn': - if (parameters.data.radioButton) { - return new RadioButtonWidgetAnnotationElement(parameters); - } else if (parameters.data.checkBox) { - return new CheckboxWidgetAnnotationElement(parameters); - } else { - warn('Unimplemented button widget annotation: pushbutton'); - } - break; case 'Ch': return new ChoiceWidgetAnnotationElement(parameters); } @@ -2084,45 +2075,6 @@ }); return TextWidgetAnnotationElement; }(); - var CheckboxWidgetAnnotationElement = function CheckboxWidgetAnnotationElementClosure() { - function CheckboxWidgetAnnotationElement(parameters) { - WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); - } - Util.inherit(CheckboxWidgetAnnotationElement, WidgetAnnotationElement, { - render: function CheckboxWidgetAnnotationElement_render() { - this.container.className = 'buttonWidgetAnnotation checkBox'; - var element = document.createElement('input'); - element.disabled = this.data.readOnly; - element.type = 'checkbox'; - if (this.data.fieldValue && this.data.fieldValue !== 'Off') { - element.setAttribute('checked', true); - } - this.container.appendChild(element); - return this.container; - } - }); - return CheckboxWidgetAnnotationElement; - }(); - var RadioButtonWidgetAnnotationElement = function RadioButtonWidgetAnnotationElementClosure() { - function RadioButtonWidgetAnnotationElement(parameters) { - WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); - } - Util.inherit(RadioButtonWidgetAnnotationElement, WidgetAnnotationElement, { - render: function RadioButtonWidgetAnnotationElement_render() { - this.container.className = 'buttonWidgetAnnotation radioButton'; - var element = document.createElement('input'); - element.disabled = this.data.readOnly; - element.type = 'radio'; - element.name = this.data.fieldName; - if (this.data.fieldValue === this.data.buttonValue) { - element.setAttribute('checked', true); - } - this.container.appendChild(element); - return this.container; - } - }); - return RadioButtonWidgetAnnotationElement; - }(); var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() { function ChoiceWidgetAnnotationElement(parameters) { WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms); diff --git a/browser/extensions/pdfjs/content/build/pdf.worker.js b/browser/extensions/pdfjs/content/build/pdf.worker.js index 53587e11b279..14746010d357 100644 --- a/browser/extensions/pdfjs/content/build/pdf.worker.js +++ b/browser/extensions/pdfjs/content/build/pdf.worker.js @@ -23,8 +23,8 @@ } }(this, function (exports) { 'use strict'; - var pdfjsVersion = '1.6.418'; - var pdfjsBuild = '59afb4b9'; + var pdfjsVersion = '1.6.401'; + var pdfjsBuild = 'b629be05'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { @@ -45245,10 +45245,10 @@ } if (!font.vertical) { textChunk.lastAdvanceWidth = width; - textChunk.width += width; + textChunk.width += width * textChunk.textAdvanceScale; } else { textChunk.lastAdvanceHeight = height; - textChunk.height += Math.abs(height); + textChunk.height += Math.abs(height * textChunk.textAdvanceScale); } return textChunk; } @@ -45269,8 +45269,6 @@ if (!textContentItem.initialized) { return; } - textContentItem.width *= textContentItem.textAdvanceScale; - textContentItem.height *= textContentItem.textAdvanceScale; textContent.items.push(runBidiTransform(textContentItem)); textContentItem.initialized = false; textContentItem.str.length = 0; @@ -45383,16 +45381,16 @@ advance = items[j] * textState.fontSize / 1000; var breakTextRun = false; if (textState.font.vertical) { - offset = advance; - textState.translateTextMatrix(0, offset); + offset = advance * (textState.textHScale * textState.textMatrix[2] + textState.textMatrix[3]); + textState.translateTextMatrix(0, advance); breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax; if (!breakTextRun) { textContentItem.height += offset; } } else { advance = -advance; - offset = advance * textState.textHScale; - textState.translateTextMatrix(offset, 0); + offset = advance * (textState.textHScale * textState.textMatrix[0] + textState.textMatrix[1]); + textState.translateTextMatrix(advance, 0); breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax; if (!breakTextRun) { textContentItem.width += offset; @@ -45886,16 +45884,7 @@ } else if (isRef(entry)) { hash.update(entry.toString()); } else if (isArray(entry)) { - var diffLength = entry.length, diffBuf = new Array(diffLength); - for (var j = 0; j < diffLength; j++) { - var diffEntry = entry[j]; - if (isName(diffEntry)) { - diffBuf[j] = diffEntry.name; - } else if (isNum(diffEntry) || isRef(diffEntry)) { - diffBuf[j] = diffEntry.toString(); - } - } - hash.update(diffBuf.join()); + hash.update(entry.length.toString()); } } } @@ -47171,8 +47160,6 @@ switch (fieldType) { case 'Tx': return new TextWidgetAnnotation(parameters); - case 'Btn': - return new ButtonWidgetAnnotation(parameters); case 'Ch': return new ChoiceWidgetAnnotation(parameters); } @@ -47600,72 +47587,17 @@ }); return TextWidgetAnnotation; }(); - var ButtonWidgetAnnotation = function ButtonWidgetAnnotationClosure() { - function ButtonWidgetAnnotation(params) { - WidgetAnnotation.call(this, params); - this.data.checkBox = !this.hasFieldFlag(AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); - if (this.data.checkBox) { - if (!isName(this.data.fieldValue)) { - return; - } - this.data.fieldValue = this.data.fieldValue.name; - } - this.data.radioButton = this.hasFieldFlag(AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); - if (this.data.radioButton) { - this.data.fieldValue = this.data.buttonValue = null; - var fieldParent = params.dict.get('Parent'); - if (!isDict(fieldParent) || !fieldParent.has('V')) { - return; - } - var fieldParentValue = fieldParent.get('V'); - if (!isName(fieldParentValue)) { - return; - } - this.data.fieldValue = fieldParentValue.name; - var appearanceStates = params.dict.get('AP'); - if (!isDict(appearanceStates)) { - return; - } - var normalAppearanceState = appearanceStates.get('N'); - if (!isDict(normalAppearanceState)) { - return; - } - var keys = normalAppearanceState.getKeys(); - for (var i = 0, ii = keys.length; i < ii; i++) { - if (keys[i] !== 'Off') { - this.data.buttonValue = keys[i]; - break; - } - } - } - } - Util.inherit(ButtonWidgetAnnotation, WidgetAnnotation, { - getOperatorList: function ButtonWidgetAnnotation_getOperatorList(evaluator, task, renderForms) { - var operatorList = new OperatorList(); - if (renderForms) { - return Promise.resolve(operatorList); - } - if (this.appearance) { - return Annotation.prototype.getOperatorList.call(this, evaluator, task, renderForms); - } - return Promise.resolve(operatorList); - } - }); - return ButtonWidgetAnnotation; - }(); var ChoiceWidgetAnnotation = function ChoiceWidgetAnnotationClosure() { function ChoiceWidgetAnnotation(params) { WidgetAnnotation.call(this, params); this.data.options = []; - var options = params.dict.get('Opt'); + var options = params.dict.getArray('Opt'); if (isArray(options)) { - var xref = params.xref; for (var i = 0, ii = options.length; i < ii; i++) { - var option = xref.fetchIfRef(options[i]); - var isOptionArray = isArray(option); + var option = options[i]; this.data.options[i] = { - exportValue: isOptionArray ? xref.fetchIfRef(option[0]) : option, - displayValue: isOptionArray ? xref.fetchIfRef(option[1]) : option + exportValue: isArray(option) ? option[0] : option, + displayValue: isArray(option) ? option[1] : option }; } } diff --git a/browser/extensions/pdfjs/content/pdfjschildbootstrap.js b/browser/extensions/pdfjs/content/pdfjschildbootstrap.js index 2051e3055d56..1f44b9c2e8d8 100644 --- a/browser/extensions/pdfjs/content/pdfjschildbootstrap.js +++ b/browser/extensions/pdfjs/content/pdfjschildbootstrap.js @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* jshint esnext:true */ /* globals Components, PdfjsContentUtils, PdfJs, Services */ 'use strict'; diff --git a/browser/extensions/pdfjs/content/web/l10n.js b/browser/extensions/pdfjs/content/web/l10n.js index e45cf200a5b9..04346ee1d650 100644 --- a/browser/extensions/pdfjs/content/web/l10n.js +++ b/browser/extensions/pdfjs/content/web/l10n.js @@ -1,3 +1,4 @@ + 'use strict'; // Small subset of the webL10n API by Fabien Cazenave for pdf.js extension. diff --git a/browser/extensions/pdfjs/content/web/viewer.css b/browser/extensions/pdfjs/content/web/viewer.css index 158842ac69fe..cafa90738577 100644 --- a/browser/extensions/pdfjs/content/web/viewer.css +++ b/browser/extensions/pdfjs/content/web/viewer.css @@ -103,9 +103,7 @@ .annotationLayer .textWidgetAnnotation input, .annotationLayer .textWidgetAnnotation textarea, -.annotationLayer .choiceWidgetAnnotation select, -.annotationLayer .buttonWidgetAnnotation.checkBox input, -.annotationLayer .buttonWidgetAnnotation.radioButton input { +.annotationLayer .choiceWidgetAnnotation select { background-color: rgba(0, 54, 255, 0.13); border: 1px solid transparent; box-sizing: border-box; @@ -124,9 +122,7 @@ .annotationLayer .textWidgetAnnotation input[disabled], .annotationLayer .textWidgetAnnotation textarea[disabled], -.annotationLayer .choiceWidgetAnnotation select[disabled], -.annotationLayer .buttonWidgetAnnotation.checkBox input[disabled], -.annotationLayer .buttonWidgetAnnotation.radioButton input[disabled] { +.annotationLayer .choiceWidgetAnnotation select[disabled] { background: none; border: 1px solid transparent; cursor: not-allowed; @@ -134,9 +130,7 @@ .annotationLayer .textWidgetAnnotation input:hover, .annotationLayer .textWidgetAnnotation textarea:hover, -.annotationLayer .choiceWidgetAnnotation select:hover, -.annotationLayer .buttonWidgetAnnotation.checkBox input:hover, -.annotationLayer .buttonWidgetAnnotation.radioButton input:hover { +.annotationLayer .choiceWidgetAnnotation select:hover { border: 1px solid #000; } @@ -163,12 +157,6 @@ width: 115%; } -.annotationLayer .buttonWidgetAnnotation.checkBox input, -.annotationLayer .buttonWidgetAnnotation.radioButton input { - -moz-appearance: none; - appearance: none; -} - .annotationLayer .popupWrapper { position: absolute; width: 20em; diff --git a/browser/extensions/pdfjs/content/web/viewer.js b/browser/extensions/pdfjs/content/web/viewer.js index 1ee979322a8a..f853da16b7b9 100644 --- a/browser/extensions/pdfjs/content/web/viewer.js +++ b/browser/extensions/pdfjs/content/web/viewer.js @@ -4119,7 +4119,7 @@ var pdfjsWebLibs; } if (error === 'cancelled') { self.error = null; - return Promise.resolve(undefined); + return; } self.renderingState = RenderingStates.FINISHED; if (self.loadingIconDiv) { @@ -4145,25 +4145,21 @@ var pdfjsWebLibs; pageNumber: self.id, cssTransform: false }); - if (error) { - return Promise.reject(error); - } - return Promise.resolve(undefined); }; var paintTask = this.renderer === RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper); paintTask.onRenderContinue = renderContinueCallback; this.paintTask = paintTask; var resultPromise = paintTask.promise.then(function () { - return finishPaintTask(null).then(function () { - if (textLayer) { - pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) { - textLayer.setTextContent(textContent); - textLayer.render(TEXT_LAYER_RENDER_DELAY); - }); - } - }); + finishPaintTask(null); + if (textLayer) { + pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) { + textLayer.setTextContent(textContent); + textLayer.render(TEXT_LAYER_RENDER_DELAY); + }); + } }, function (reason) { - return finishPaintTask(reason); + finishPaintTask(reason); + throw reason; }); if (this.annotationLayerFactory) { if (!this.annotationLayer) { From abfe13cbc56d358da754362da30cda13a59be03d Mon Sep 17 00:00:00 2001 From: Randell Jesup Date: Fri, 30 Dec 2016 00:11:59 -0500 Subject: [PATCH 158/229] Bug 1326288: Restore patches for bug 1237023 and bug 1315283 - lost in 49 update r=pkerr --- .../video_coding/codecs/vp9/vp9_impl.cc | 64 +++++++++++++++++-- .../video_coding/codecs/vp9/vp9_impl.h | 5 ++ 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/media/webrtc/trunk/webrtc/modules/video_coding/codecs/vp9/vp9_impl.cc b/media/webrtc/trunk/webrtc/modules/video_coding/codecs/vp9/vp9_impl.cc index 6e9f0b91e751..eba8c82450bd 100644 --- a/media/webrtc/trunk/webrtc/modules/video_coding/codecs/vp9/vp9_impl.cc +++ b/media/webrtc/trunk/webrtc/modules/video_coding/codecs/vp9/vp9_impl.cc @@ -507,6 +507,13 @@ int VP9EncoderImpl::Encode(const VideoFrame& input_image, if (frame_types && frame_types->size() > 0) { frame_type = (*frame_types)[0]; } + if (input_image.width() != codec_.width || + input_image.height() != codec_.height) { + int ret = UpdateCodecFrameSize(input_image); + if (ret < 0) { + return ret; + } + } RTC_DCHECK_EQ(input_image.width(), static_cast(raw_->d_w)); RTC_DCHECK_EQ(input_image.height(), static_cast(raw_->d_h)); @@ -567,6 +574,44 @@ int VP9EncoderImpl::Encode(const VideoFrame& input_image, return WEBRTC_VIDEO_CODEC_OK; } +int VP9EncoderImpl::UpdateCodecFrameSize( + const VideoFrame& input_image) { + fprintf(stderr, "Reconfiging VP( from %dx%d to %dx%d\n", + codec_.width, codec_.height, input_image.width(), input_image.height()); + // Preserve latest bitrate/framerate setting + uint32_t old_bitrate_kbit = config_->rc_target_bitrate; + uint32_t old_framerate = codec_.maxFramerate; + + codec_.width = input_image.width(); + codec_.height = input_image.height(); + + vpx_img_free(raw_); + raw_ = vpx_img_wrap(NULL, VPX_IMG_FMT_I420, codec_.width, codec_.height, + 1, NULL); + // Update encoder context for new frame size. + config_->g_w = codec_.width; + config_->g_h = codec_.height; + + // Determine number of threads based on the image size and #cores. + config_->g_threads = NumberOfThreads(codec_.width, codec_.height, + num_cores_); + // Update the cpu_speed setting for resolution change. + cpu_speed_ = GetCpuSpeed(codec_.width, codec_.height); + + // NOTE: We would like to do this the same way vp8 does it + // (with vpx_codec_enc_config_set()), but that causes asserts + // in AQ 3 (cyclic); and in AQ 0 it works, but on a resize to smaller + // than 1/2 x 1/2 original it asserts in convolve(). Given these + // bugs in trying to do it the "right" way, we basically re-do + // the initialization. + vpx_codec_destroy(encoder_); // clean up old state + int result = InitAndSetControlSettings(&codec_); + if (result == WEBRTC_VIDEO_CODEC_OK) { + return SetRates(old_bitrate_kbit, old_framerate); + } + return result; +} + void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific, const vpx_codec_cx_pkt& pkt, uint32_t timestamp) { @@ -963,6 +1008,7 @@ int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img, uint32_t timestamp) { return WEBRTC_VIDEO_CODEC_NO_OUTPUT; } +#ifdef USE_WRAPPED_I420_BUFFER // This buffer contains all of |img|'s image data, a reference counted // Vp9FrameBuffer. (libvpx is done with the buffers after a few // vpx_codec_decode calls or vpx_codec_destroy). @@ -972,6 +1018,7 @@ int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img, uint32_t timestamp) { // using a WrappedI420Buffer. rtc::scoped_refptr img_wrapped_buffer( new rtc::RefCountedObject( + img->d_w, img->d_h, img->d_w, img->d_h, img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V], @@ -981,10 +1028,19 @@ int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img, uint32_t timestamp) { // release |img_buffer|. rtc::KeepRefUntilDone(img_buffer))); - VideoFrame decoded_image; - decoded_image.set_video_frame_buffer(img_wrapped_buffer); - decoded_image.set_timestamp(timestamp); - int ret = decode_complete_callback_->Decoded(decoded_image); + VideoFrame decoded_image_; + decoded_image_.set_video_frame_buffer(img_wrapped_buffer); +#else + decoded_image_.CreateFrame(img->planes[VPX_PLANE_Y], + img->planes[VPX_PLANE_U], + img->planes[VPX_PLANE_V], + img->d_w, img->d_h, + img->stride[VPX_PLANE_Y], + img->stride[VPX_PLANE_U], + img->stride[VPX_PLANE_V]); +#endif + decoded_image_.set_timestamp(timestamp); + int ret = decode_complete_callback_->Decoded(decoded_image_); if (ret != 0) return ret; return WEBRTC_VIDEO_CODEC_OK; diff --git a/media/webrtc/trunk/webrtc/modules/video_coding/codecs/vp9/vp9_impl.h b/media/webrtc/trunk/webrtc/modules/video_coding/codecs/vp9/vp9_impl.h index b83d292e4f1e..b313ebd71214 100644 --- a/media/webrtc/trunk/webrtc/modules/video_coding/codecs/vp9/vp9_impl.h +++ b/media/webrtc/trunk/webrtc/modules/video_coding/codecs/vp9/vp9_impl.h @@ -166,6 +166,11 @@ class VP9DecoderImpl : public VP9Decoder { private: int ReturnFrame(const vpx_image_t* img, uint32_t timeStamp); +#ifndef USE_WRAPPED_I420_BUFFER + // Temporarily keep VideoFrame in a separate buffer + // Once we debug WrappedI420VideoFrame usage, we can get rid of this + VideoFrame decoded_image_; +#endif // Memory pool used to share buffers between libvpx and webrtc. Vp9FrameBufferPool frame_buffer_pool_; DecodedImageCallback* decode_complete_callback_; From cd875e79a619c64d889345f0c1af9aee7806524b Mon Sep 17 00:00:00 2001 From: Cameron McCormack Date: Wed, 28 Dec 2016 17:50:44 +0800 Subject: [PATCH 159/229] Bug 1326023 - Make Element::GetBindingURL return a strong reference. r=smaug MozReview-Commit-ID: 5QI6UuvwDrE --- dom/base/Element.cpp | 64 +++++++++++++++++++++----------------------- dom/base/Element.h | 2 +- 2 files changed, 31 insertions(+), 35 deletions(-) diff --git a/dom/base/Element.cpp b/dom/base/Element.cpp index 634ff3304ad2..7849a98f9ba8 100644 --- a/dom/base/Element.cpp +++ b/dom/base/Element.cpp @@ -448,7 +448,6 @@ Element::GetBindingURL(nsIDocument *aDocument, css::URLValue **aResult) nsCOMPtr shell = aDocument->GetShell(); if (!shell || GetPrimaryFrame() || !isXULorPluginElement) { *aResult = nullptr; - return true; } @@ -457,8 +456,7 @@ Element::GetBindingURL(nsIDocument *aDocument, css::URLValue **aResult) nsComputedDOMStyle::GetStyleContextForElementNoFlush(this, nullptr, shell); NS_ENSURE_TRUE(sc, false); - *aResult = sc->StyleDisplay()->mBinding; - + NS_IF_ADDREF(*aResult = sc->StyleDisplay()->mBinding); return true; } @@ -535,42 +533,40 @@ Element::WrapObject(JSContext *aCx, JS::Handle aGivenProto) // Make sure the style context goes away _before_ we load the binding // since that can destroy the relevant presshell. - mozilla::css::URLValue *bindingURL; - bool ok = GetBindingURL(doc, &bindingURL); - if (!ok) { - dom::Throw(aCx, NS_ERROR_FAILURE); - return nullptr; - } - - if (!bindingURL) { - // No binding, nothing left to do here. - return obj; - } - - nsCOMPtr uri = bindingURL->GetURI(); - nsCOMPtr principal = bindingURL->mOriginPrincipal.get(); - - // We have a binding that must be installed. - bool dummy; - - nsXBLService* xblService = nsXBLService::GetInstance(); - if (!xblService) { - dom::Throw(aCx, NS_ERROR_NOT_AVAILABLE); - return nullptr; - } { // Make a scope so that ~nsRefPtr can GC before returning obj. - RefPtr binding; - xblService->LoadBindings(this, uri, principal, getter_AddRefs(binding), &dummy); + RefPtr bindingURL; + bool ok = GetBindingURL(doc, getter_AddRefs(bindingURL)); + if (!ok) { + dom::Throw(aCx, NS_ERROR_FAILURE); + return nullptr; + } - if (binding) { - if (nsContentUtils::IsSafeToRunScript()) { - binding->ExecuteAttachedHandler(); + if (bindingURL) { + nsCOMPtr uri = bindingURL->GetURI(); + nsCOMPtr principal = bindingURL->mOriginPrincipal.get(); + + // We have a binding that must be installed. + bool dummy; + + nsXBLService* xblService = nsXBLService::GetInstance(); + if (!xblService) { + dom::Throw(aCx, NS_ERROR_NOT_AVAILABLE); + return nullptr; } - else { - nsContentUtils::AddScriptRunner( - NewRunnableMethod(binding, &nsXBLBinding::ExecuteAttachedHandler)); + + RefPtr binding; + xblService->LoadBindings(this, uri, principal, getter_AddRefs(binding), + &dummy); + + if (binding) { + if (nsContentUtils::IsSafeToRunScript()) { + binding->ExecuteAttachedHandler(); + } else { + nsContentUtils::AddScriptRunner( + NewRunnableMethod(binding, &nsXBLBinding::ExecuteAttachedHandler)); + } } } } diff --git a/dom/base/Element.h b/dom/base/Element.h index 05e9044c67ba..b115a31f5aa7 100644 --- a/dom/base/Element.h +++ b/dom/base/Element.h @@ -387,7 +387,7 @@ public: } } - bool GetBindingURL(nsIDocument *aDocument, css::URLValue **aResult); + bool GetBindingURL(nsIDocument* aDocument, css::URLValue **aResult); // The bdi element defaults to dir=auto if it has no dir attribute set. // Other elements will only have dir=auto if they have an explicit dir=auto, From 50240b9c12bd09c6e5ff3a6025e5580bee72591a Mon Sep 17 00:00:00 2001 From: Kilik Kuo Date: Thu, 29 Dec 2016 23:33:53 +0800 Subject: [PATCH 160/229] Bug 1326220 - [WPT] Remove out-of-date sub tests and unexpected results in clearkey-mp4-requestmediakeysystemaccess.html.ini r=jwwang MozReview-Commit-ID: Cj6bC6KRnIO --HG-- extra : rebase_source : 967fdacd30e824c06dd83a9360517c51ba9ed47c --- .../clearkey-mp4-requestmediakeysystemaccess.html.ini | 7 ------- 1 file changed, 7 deletions(-) diff --git a/testing/web-platform/meta/encrypted-media/clearkey-mp4-requestmediakeysystemaccess.html.ini b/testing/web-platform/meta/encrypted-media/clearkey-mp4-requestmediakeysystemaccess.html.ini index 01503c6147d1..acbc7b7a7e26 100644 --- a/testing/web-platform/meta/encrypted-media/clearkey-mp4-requestmediakeysystemaccess.html.ini +++ b/testing/web-platform/meta/encrypted-media/clearkey-mp4-requestmediakeysystemaccess.html.ini @@ -90,10 +90,3 @@ if debug and not e10s and (os == "win") and (version == "5.1.2600") and (processor == "x86") and (bits == 32): FAIL if debug and e10s and (os == "win") and (version == "5.1.2600") and (processor == "x86") and (bits == 32): FAIL if not debug and not e10s and (os == "win") and (version == "5.1.2600") and (processor == "x86") and (bits == 32): FAIL - - [org.w3.clearkey, requestMediaKeySystemAccess: Empty Key System () should result in InvalidAccessError] - expected: FAIL - - [org.w3.clearkey, requestMediaKeySystemAccess: Empty supportedConfigurations should result in InvalidAccessError] - expected: FAIL - From 77ca13f62749c87da6bdf3e8880ed39c82e6e71b Mon Sep 17 00:00:00 2001 From: Ray Lin Date: Fri, 30 Dec 2016 11:01:59 +0800 Subject: [PATCH 161/229] Bug 1326040 - Align text color of selected item in closed caption menu with spec. r=jaws MozReview-Commit-ID: 5ondXdNPRL6 --HG-- extra : rebase_source : 3e2764cb7971db11ae502a837400e4ccd4dacf62 --- toolkit/themes/shared/media/videocontrols.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/toolkit/themes/shared/media/videocontrols.css b/toolkit/themes/shared/media/videocontrols.css index 5b5d389f2aa2..b56170036c37 100644 --- a/toolkit/themes/shared/media/videocontrols.css +++ b/toolkit/themes/shared/media/videocontrols.css @@ -331,7 +331,7 @@ audio > xul|videocontrols { } .textTrackList > .textTrackItem[on] { - color: #00b6f0; + color: #48a0f7; } .positionLabel, From c08a6438f117a1f7d3aa7878770d25bc0cbde591 Mon Sep 17 00:00:00 2001 From: Sylvestre Ledru Date: Thu, 29 Dec 2016 19:44:57 +0100 Subject: [PATCH 162/229] Bug 1292649 - Use default-jdk instead of an explicit version of the jdk r=nalexander Should be pretty safe as Java compa is usually very good. This will fix the issue on Debian testing not having openjdk-7-jdk and current Debian stable having it. (same with Ubuntu) MozReview-Commit-ID: Alxg4K4PwQ4 --HG-- extra : rebase_source : 920cdb1618ba587a4776e33ef7857415a59c53b9 --- python/mozboot/mozboot/debian.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/mozboot/mozboot/debian.py b/python/mozboot/mozboot/debian.py index 6e33e9e5bf3a..f5b91259e7bb 100644 --- a/python/mozboot/mozboot/debian.py +++ b/python/mozboot/mozboot/debian.py @@ -74,7 +74,7 @@ class DebianBootstrapper(BaseBootstrapper): # (mobile/android) for all Debian-derived distros (such as Ubuntu). MOBILE_ANDROID_COMMON_PACKAGES = [ 'zlib1g-dev', # mobile/android requires system zlib. - 'openjdk-7-jdk', + 'default-jdk', 'wget', # For downloading the Android SDK and NDK. 'libncurses5:i386', # See comments about i386 below. 'libstdc++6:i386', From ab2ce0d4b3f9427640e773d80ab252d3fa1d4643 Mon Sep 17 00:00:00 2001 From: Masatoshi Kimura Date: Fri, 30 Dec 2016 10:28:18 +0900 Subject: [PATCH 163/229] Bug 1321705 - Remove "network.standard-url.(escape|encode)-utf8". r=valentin.gosu MozReview-Commit-ID: D6fRD9ElrBd --HG-- extra : rebase_source : 6414effcf9e68859781de004e06eedea378e92ca --- modules/libpref/init/all.js | 8 -------- netwerk/base/nsStandardURL.cpp | 25 ++----------------------- netwerk/base/nsStandardURL.h | 3 --- 3 files changed, 2 insertions(+), 34 deletions(-) diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js index 210787ce86f7..713563e04552 100644 --- a/modules/libpref/init/all.js +++ b/modules/libpref/init/all.js @@ -1851,14 +1851,6 @@ pref("network.dns.localDomains", ""); // Contols whether or not "localhost" should resolve when offline pref("network.dns.offline-localhost", true); -// This preference controls whether or not URLs with UTF-8 characters are -// escaped. Set this preference to TRUE for strict RFC2396 conformance. -pref("network.standard-url.escape-utf8", true); - -// This preference controls whether or not URLs are always encoded and sent as -// UTF-8. -pref("network.standard-url.encode-utf8", true); - // The maximum allowed length for a URL - 1MB default pref("network.standard-url.max-length", 1048576); diff --git a/netwerk/base/nsStandardURL.cpp b/netwerk/base/nsStandardURL.cpp index 4c5311a7b121..d151bf5984eb 100644 --- a/netwerk/base/nsStandardURL.cpp +++ b/netwerk/base/nsStandardURL.cpp @@ -140,8 +140,6 @@ static NS_DEFINE_CID(kStandardURLCID, NS_STANDARDURL_CID); nsIIDNService *nsStandardURL::gIDN = nullptr; bool nsStandardURL::gInitialized = false; -bool nsStandardURL::gEscapeUTF8 = true; -bool nsStandardURL::gAlwaysEncodeInUTF8 = true; char nsStandardURL::gHostLimitDigits[] = { '/', '\\', '?', '#', 0 }; //---------------------------------------------------------------------------- @@ -158,8 +156,6 @@ char nsStandardURL::gHostLimitDigits[] = { '/', '\\', '?', '#', 0 }; // nsStandardURL::nsPrefObserver //---------------------------------------------------------------------------- -#define NS_NET_PREF_ESCAPEUTF8 "network.standard-url.escape-utf8" -#define NS_NET_PREF_ALWAYSENCODEINUTF8 "network.standard-url.encode-utf8" #define NS_NET_PREF_ENABLE_RUST "network.standard-url.enable-rust" NS_IMPL_ISUPPORTS(nsStandardURL::nsPrefObserver, nsIObserver) @@ -225,13 +221,10 @@ nsSegmentEncoder::EncodeSegmentCount(const char *str, } } - // escape per RFC2396 unless UTF-8 and allowed by preferences - int16_t escapeFlags = (gEscapeUTF8 || mEncoder) ? 0 : esc_OnlyASCII; - uint32_t initLen = result.Length(); // now perform any required escaping - if (NS_EscapeURL(str + pos, len, mask | escapeFlags, result)) { + if (NS_EscapeURL(str + pos, len, mask, result)) { len = result.Length() - initLen; appended = true; } @@ -280,7 +273,7 @@ nsSegmentEncoder::InitUnicodeEncoder() nsSegmentEncoder name(useUTF8 ? nullptr : mOriginCharset.get()) #define GET_SEGMENT_ENCODER(name) \ - GET_SEGMENT_ENCODER_INTERNAL(name, gAlwaysEncodeInUTF8) + GET_SEGMENT_ENCODER_INTERNAL(name, true) #define GET_QUERY_ENCODER(name) \ GET_SEGMENT_ENCODER_INTERNAL(name, false) @@ -372,8 +365,6 @@ nsStandardURL::InitGlobalObjects() nsCOMPtr prefBranch( do_GetService(NS_PREFSERVICE_CONTRACTID) ); if (prefBranch) { nsCOMPtr obs( new nsPrefObserver() ); - prefBranch->AddObserver(NS_NET_PREF_ESCAPEUTF8, obs.get(), false); - prefBranch->AddObserver(NS_NET_PREF_ALWAYSENCODEINUTF8, obs.get(), false); #ifdef MOZ_RUST_URLPARSE prefBranch->AddObserver(NS_NET_PREF_ENABLE_RUST, obs.get(), false); #endif @@ -1185,18 +1176,6 @@ nsStandardURL::PrefsChanged(nsIPrefBranch *prefs, const char *pref) #define PREF_CHANGED(p) ((pref == nullptr) || !strcmp(pref, p)) #define GOT_PREF(p, b) (NS_SUCCEEDED(prefs->GetBoolPref(p, &b))) - if (PREF_CHANGED(NS_NET_PREF_ESCAPEUTF8)) { - if (GOT_PREF(NS_NET_PREF_ESCAPEUTF8, val)) - gEscapeUTF8 = val; - LOG(("escape UTF-8 %s\n", gEscapeUTF8 ? "enabled" : "disabled")); - } - - if (PREF_CHANGED(NS_NET_PREF_ALWAYSENCODEINUTF8)) { - if (GOT_PREF(NS_NET_PREF_ALWAYSENCODEINUTF8, val)) - gAlwaysEncodeInUTF8 = val; - LOG(("encode in UTF-8 %s\n", gAlwaysEncodeInUTF8 ? "enabled" : "disabled")); - } - #ifdef MOZ_RUST_URLPARSE if (PREF_CHANGED(NS_NET_PREF_ENABLE_RUST)) { if (GOT_PREF(NS_NET_PREF_ENABLE_RUST, val)) { diff --git a/netwerk/base/nsStandardURL.h b/netwerk/base/nsStandardURL.h index c73697fc6104..5ef807335f32 100644 --- a/netwerk/base/nsStandardURL.h +++ b/netwerk/base/nsStandardURL.h @@ -302,9 +302,6 @@ private: static nsIIDNService *gIDN; static char gHostLimitDigits[]; static bool gInitialized; - static bool gEscapeUTF8; - static bool gAlwaysEncodeInUTF8; - static bool gEncodeQueryInUTF8; public: #ifdef DEBUG_DUMP_URLS_AT_SHUTDOWN From 0c6dc2ea7360b618d191016c9a67916e9f70297c Mon Sep 17 00:00:00 2001 From: Masatoshi Kimura Date: Wed, 28 Dec 2016 20:40:21 +0900 Subject: [PATCH 164/229] Bug 1323683 - Fold nsIURIWithQuery into nsIURI. r=valentin.gosu MozReview-Commit-ID: BFfgr42sNyx --HG-- extra : rebase_source : a28d6a3c96f0c86dd7269147f130b3195b1f1faf --- caps/nsNullPrincipalURI.cpp | 26 ++++++++++++++ dom/base/Location.cpp | 14 +++----- dom/url/URL.cpp | 40 +++++---------------- image/decoders/icon/nsIconURI.cpp | 26 ++++++++++++++ modules/libjar/nsJARURI.cpp | 1 - modules/libjar/nsJARURI.h | 1 - netwerk/base/RustURL.cpp | 1 - netwerk/base/RustURL.h | 1 - netwerk/base/moz.build | 1 - netwerk/base/nsIURI.idl | 60 ++++++++++++++++++++----------- netwerk/base/nsIURIWithQuery.idl | 30 ---------------- netwerk/base/nsIURL.idl | 6 ++-- netwerk/base/nsSimpleURI.cpp | 6 +--- netwerk/base/nsSimpleURI.h | 4 +-- netwerk/base/nsStandardURL.cpp | 1 - netwerk/base/nsStandardURL.h | 1 - 16 files changed, 110 insertions(+), 109 deletions(-) delete mode 100644 netwerk/base/nsIURIWithQuery.idl diff --git a/caps/nsNullPrincipalURI.cpp b/caps/nsNullPrincipalURI.cpp index 020d2a1a7c84..c643b3adb1c0 100644 --- a/caps/nsNullPrincipalURI.cpp +++ b/caps/nsNullPrincipalURI.cpp @@ -165,6 +165,32 @@ nsNullPrincipalURI::SetPath(const nsACString &aPath) return NS_ERROR_NOT_IMPLEMENTED; } +NS_IMETHODIMP +nsNullPrincipalURI::GetFilePath(nsACString &aFilePath) +{ + aFilePath.Truncate(); + return NS_ERROR_NOT_IMPLEMENTED; +} + +NS_IMETHODIMP +nsNullPrincipalURI::SetFilePath(const nsACString &aFilePath) +{ + return NS_ERROR_NOT_IMPLEMENTED; +} + +NS_IMETHODIMP +nsNullPrincipalURI::GetQuery(nsACString &aQuery) +{ + aQuery.Truncate(); + return NS_ERROR_NOT_IMPLEMENTED; +} + +NS_IMETHODIMP +nsNullPrincipalURI::SetQuery(const nsACString &aQuery) +{ + return NS_ERROR_NOT_IMPLEMENTED; +} + NS_IMETHODIMP nsNullPrincipalURI::GetRef(nsACString &_ref) { diff --git a/dom/base/Location.cpp b/dom/base/Location.cpp index e3b614931a5e..bdae4d07c0bd 100644 --- a/dom/base/Location.cpp +++ b/dom/base/Location.cpp @@ -581,15 +581,12 @@ Location::GetPathname(nsAString& aPathname) result = GetURI(getter_AddRefs(uri)); - nsCOMPtr url(do_QueryInterface(uri)); - if (url) { - nsAutoCString file; + nsAutoCString file; - result = url->GetFilePath(file); + result = uri->GetFilePath(file); - if (NS_SUCCEEDED(result)) { - AppendUTF8toUTF16(file, aPathname); - } + if (NS_SUCCEEDED(result)) { + AppendUTF8toUTF16(file, aPathname); } return result; @@ -604,8 +601,7 @@ Location::SetPathname(const nsAString& aPathname) return rv; } - nsCOMPtr url(do_QueryInterface(uri)); - if (url && NS_SUCCEEDED(url->SetFilePath(NS_ConvertUTF16toUTF8(aPathname)))) { + if (NS_SUCCEEDED(uri->SetFilePath(NS_ConvertUTF16toUTF8(aPathname)))) { return SetURI(uri); } diff --git a/dom/url/URL.cpp b/dom/url/URL.cpp index 1f15e115142e..c8724c3597b0 100644 --- a/dom/url/URL.cpp +++ b/dom/url/URL.cpp @@ -17,7 +17,6 @@ #include "nsEscape.h" #include "nsHostObjectProtocolHandler.h" #include "nsIIOService.h" -#include "nsIURIWithQuery.h" #include "nsIURL.h" #include "nsNetCID.h" #include "nsNetUtil.h" @@ -525,21 +524,10 @@ URLMainThread::GetPathname(nsAString& aPathname, ErrorResult& aRv) const // Do not throw! Not having a valid URI or URL should result in an empty // string. - nsCOMPtr url(do_QueryInterface(mURI)); - if (url) { - nsAutoCString file; - nsresult rv = url->GetFilePath(file); - if (NS_SUCCEEDED(rv)) { - CopyUTF8toUTF16(file, aPathname); - } - - return; - } - - nsAutoCString path; - nsresult rv = mURI->GetPath(path); + nsAutoCString file; + nsresult rv = mURI->GetFilePath(file); if (NS_SUCCEEDED(rv)) { - CopyUTF8toUTF16(path, aPathname); + CopyUTF8toUTF16(file, aPathname); } } @@ -548,11 +536,7 @@ URLMainThread::SetPathname(const nsAString& aPathname, ErrorResult& aRv) { // Do not throw! - nsCOMPtr url(do_QueryInterface(mURI)); - if (url) { - url->SetFilePath(NS_ConvertUTF16toUTF8(aPathname)); - return; - } + mURI->SetFilePath(NS_ConvertUTF16toUTF8(aPathname)); } void @@ -566,13 +550,9 @@ URLMainThread::GetSearch(nsAString& aSearch, ErrorResult& aRv) const nsAutoCString search; nsresult rv; - nsCOMPtr url(do_QueryInterface(mURI)); - if (url) { - rv = url->GetQuery(search); - if (NS_SUCCEEDED(rv) && !search.IsEmpty()) { - CopyUTF8toUTF16(NS_LITERAL_CSTRING("?") + search, aSearch); - } - return; + rv = mURI->GetQuery(search); + if (NS_SUCCEEDED(rv) && !search.IsEmpty()) { + CopyUTF8toUTF16(NS_LITERAL_CSTRING("?") + search, aSearch); } } @@ -603,11 +583,7 @@ URLMainThread::SetSearchInternal(const nsAString& aSearch, ErrorResult& aRv) { // Ignore failures to be compatible with NS4. - nsCOMPtr uriWithQuery(do_QueryInterface(mURI)); - if (uriWithQuery) { - uriWithQuery->SetQuery(NS_ConvertUTF16toUTF8(aSearch)); - return; - } + mURI->SetQuery(NS_ConvertUTF16toUTF8(aSearch)); } } // anonymous namespace diff --git a/image/decoders/icon/nsIconURI.cpp b/image/decoders/icon/nsIconURI.cpp index 2c2788c8f1ed..632a733fe9a6 100644 --- a/image/decoders/icon/nsIconURI.cpp +++ b/image/decoders/icon/nsIconURI.cpp @@ -371,6 +371,32 @@ nsMozIconURI::SetPath(const nsACString& aPath) return NS_ERROR_FAILURE; } +NS_IMETHODIMP +nsMozIconURI::GetFilePath(nsACString& aFilePath) +{ + aFilePath.Truncate(); + return NS_OK; +} + +NS_IMETHODIMP +nsMozIconURI::SetFilePath(const nsACString& aFilePath) +{ + return NS_ERROR_FAILURE; +} + +NS_IMETHODIMP +nsMozIconURI::GetQuery(nsACString& aQuery) +{ + aQuery.Truncate(); + return NS_OK; +} + +NS_IMETHODIMP +nsMozIconURI::SetQuery(const nsACString& aQuery) +{ + return NS_ERROR_FAILURE; +} + NS_IMETHODIMP nsMozIconURI::GetRef(nsACString& aRef) { diff --git a/modules/libjar/nsJARURI.cpp b/modules/libjar/nsJARURI.cpp index e46e51467159..d1e4b5a593c2 100644 --- a/modules/libjar/nsJARURI.cpp +++ b/modules/libjar/nsJARURI.cpp @@ -41,7 +41,6 @@ NS_IMPL_RELEASE(nsJARURI) NS_INTERFACE_MAP_BEGIN(nsJARURI) NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIJARURI) NS_INTERFACE_MAP_ENTRY(nsIURI) - NS_INTERFACE_MAP_ENTRY(nsIURIWithQuery) NS_INTERFACE_MAP_ENTRY(nsIURL) NS_INTERFACE_MAP_ENTRY(nsIJARURI) NS_INTERFACE_MAP_ENTRY(nsISerializable) diff --git a/modules/libjar/nsJARURI.h b/modules/libjar/nsJARURI.h index 31271e4ac110..d2608a5c6d0d 100644 --- a/modules/libjar/nsJARURI.h +++ b/modules/libjar/nsJARURI.h @@ -41,7 +41,6 @@ class nsJARURI final : public nsIJARURI, public: NS_DECL_THREADSAFE_ISUPPORTS NS_DECL_NSIURI - NS_DECL_NSIURIWITHQUERY NS_DECL_NSIURL NS_DECL_NSIJARURI NS_DECL_NSISERIALIZABLE diff --git a/netwerk/base/RustURL.cpp b/netwerk/base/RustURL.cpp index 10c551bdb2fa..b7df783e793a 100644 --- a/netwerk/base/RustURL.cpp +++ b/netwerk/base/RustURL.cpp @@ -17,7 +17,6 @@ NS_IMPL_RELEASE(RustURL) NS_INTERFACE_MAP_BEGIN(RustURL) NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStandardURL) NS_INTERFACE_MAP_ENTRY(nsIURI) - NS_INTERFACE_MAP_ENTRY(nsIURIWithQuery) NS_INTERFACE_MAP_ENTRY(nsIURL) // NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIFileURL, mSupportsFileURL) NS_INTERFACE_MAP_ENTRY(nsIStandardURL) diff --git a/netwerk/base/RustURL.h b/netwerk/base/RustURL.h index 06007da4d2f0..b86db6defec4 100644 --- a/netwerk/base/RustURL.h +++ b/netwerk/base/RustURL.h @@ -31,7 +31,6 @@ class RustURL { NS_DECL_ISUPPORTS NS_DECL_NSIURI - NS_DECL_NSIURIWITHQUERY NS_DECL_NSIURL NS_DECL_NSIFILEURL NS_DECL_NSISTANDARDURL diff --git a/netwerk/base/moz.build b/netwerk/base/moz.build index 577e3d2bac66..4b86a697d753 100644 --- a/netwerk/base/moz.build +++ b/netwerk/base/moz.build @@ -132,7 +132,6 @@ XPIDL_SOURCES += [ 'nsIURIClassifier.idl', 'nsIURIWithBlobImpl.idl', 'nsIURIWithPrincipal.idl', - 'nsIURIWithQuery.idl', 'nsIURL.idl', 'nsIURLParser.idl', 'nsPILoadGroupInternal.idl', diff --git a/netwerk/base/nsIURI.idl b/netwerk/base/nsIURI.idl index 2384c5fd9953..ef163813aa37 100644 --- a/netwerk/base/nsIURI.idl +++ b/netwerk/base/nsIURI.idl @@ -10,18 +10,18 @@ * provides accessors to set and query the most basic components of an URI. * Subclasses, including nsIURL, impose greater structure on the URI. * - * This interface follows Tim Berners-Lee's URI spec (RFC2396) [1], where the + * This interface follows Tim Berners-Lee's URI spec (RFC3986) [1], where the * basic URI components are defined as such: *
- *      ftp://username:password@hostname:portnumber/pathname#ref
- *      \ /   \               / \      / \        /\         \ /
- *       -     ---------------   ------   --------  |         -
- *       |            |             |        |      |         |
- *       |            |             |        |      |        Ref
- *       |            |             |       Port    \        /
- *       |            |            Host      /       --------
- *       |         UserPass                 /	         |
- *     Scheme                              /	        Path
+ *      ftp://username:password@hostname:portnumber/pathname?query#ref
+ *      \ /   \               / \      / \        /\       / \   / \ /
+ *       -     ---------------   ------   --------  -------   ---   -
+ *       |            |             |        |         |       |    |
+ *       |            |             |        |      FilePath Query Ref
+ *       |            |             |       Port       \            /
+ *       |            |            Host      /          ------------
+ *       |         UserPass                 /	              |
+ *     Scheme                              /	             Path
  *       \                                /
  *        --------------------------------
  *                       |
@@ -30,13 +30,9 @@
  * The definition of the URI components has been extended to allow for
  * internationalized domain names [2] and the more generic IRI structure [3].
  *
- * Note also that the RFC defines #-separated fragment identifiers as being
- * "not part of the URI".  Despite this, we bundle them as part of the URI, for
- * convenience.
- *
- * [1] http://www.ietf.org/rfc/rfc2396.txt
- * [2] http://www.ietf.org/internet-drafts/draft-ietf-idn-idna-06.txt
- * [3] http://www.ietf.org/internet-drafts/draft-masinter-url-i18n-08.txt
+ * [1] https://tools.ietf.org/html/rfc3986
+ * [2] https://tools.ietf.org/html/rfc5890
+ * [3] https://tools.ietf.org/html/rfc3987
  */
 
 %{C++
@@ -116,7 +112,7 @@ interface nsIURI : nsISupports
 
     /**
      * The Scheme is the protocol to which this URI refers.  The scheme is
-     * restricted to the US-ASCII charset per RFC2396.  Setting this is
+     * restricted to the US-ASCII charset per RFC3986.  Setting this is
      * highly discouraged outside of a protocol handler implementation, since
      * that will generally lead to incorrect results.
      */
@@ -174,6 +170,9 @@ interface nsIURI : nsISupports
      * empty, depending on the protocol).
      *
      * Some characters may be escaped.
+     *
+     * This attribute contains query and ref parts for historical reasons.
+     * Use the 'filePath' attribute if you do not want those parts included.
      */
     attribute AUTF8String path;
 
@@ -281,10 +280,31 @@ interface nsIURI : nsISupports
     /**
      * returns a string for the current URI with the ref element cleared.
      */
-   readonly attribute AUTF8String specIgnoringRef;
+    readonly attribute AUTF8String specIgnoringRef;
 
     /**
      * Returns if there is a reference portion (the part after the "#") of the URI.
      */
-   readonly attribute boolean hasRef;
+    readonly attribute boolean hasRef;
+
+    /************************************************************************
+     * Additional attributes added for .query support:
+     */
+
+    /**
+     * Returns a path including the directory and file portions of a
+     * URL.  For example, the filePath of "http://host/foo/bar.html#baz"
+     * is "/foo/bar.html".
+     *
+     * Some characters may be escaped.
+     */
+    attribute AUTF8String filePath;
+
+    /**
+     * Returns the query portion (the part after the "?") of the URL.
+     * If there isn't one, an empty string is returned.
+     *
+     * Some characters may be escaped.
+     */
+    attribute AUTF8String query;
 };
diff --git a/netwerk/base/nsIURIWithQuery.idl b/netwerk/base/nsIURIWithQuery.idl
deleted file mode 100644
index 749b2773d8e3..000000000000
--- a/netwerk/base/nsIURIWithQuery.idl
+++ /dev/null
@@ -1,30 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsIURI.idl"
-
-/**
- * nsIURIWithQuery is implemented by URIs which have a query parameter.
- * This is useful for the URL API.
- */
-[scriptable, uuid(367510ee-8556-435a-8f99-b5fd357e08cc)]
-interface nsIURIWithQuery : nsIURI
-{
-    /**
-     * Returns a path including the directory and file portions of a
-     * URL.  For example, the filePath of "http://host/foo/bar.html#baz"
-     * is "/foo/bar.html".
-     *
-     * Some characters may be escaped.
-     */
-    attribute AUTF8String filePath;
-
-    /**
-     * Returns the query portion (the part after the "?") of the URL.
-     * If there isn't one, an empty string is returned.
-     *
-     * Some characters may be escaped.
-     */
-    attribute AUTF8String query;
-};
diff --git a/netwerk/base/nsIURL.idl b/netwerk/base/nsIURL.idl
index aeaa3f6949c7..9ff6c3dcda34 100644
--- a/netwerk/base/nsIURL.idl
+++ b/netwerk/base/nsIURL.idl
@@ -3,7 +3,7 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "nsIURIWithQuery.idl"
+#include "nsIURI.idl"
 
 /**
  * The nsIURL interface provides convenience methods that further
@@ -20,7 +20,7 @@
  *                        filePath
  */
 [scriptable, uuid(86adcd89-0b70-47a2-b0fe-5bb2c5f37e31)]
-interface nsIURL : nsIURIWithQuery
+interface nsIURL : nsIURI
 {
     /*************************************************************************
      * The URL path is broken down into the following principal components:
@@ -28,7 +28,7 @@ interface nsIURL : nsIURIWithQuery
      * attribute AUTF8String filePath;
      * attribute AUTF8String query;
      *
-     * These are inherited from nsIURIWithQuery.
+     * These are inherited from nsIURI.
      */
 
     /*************************************************************************
diff --git a/netwerk/base/nsSimpleURI.cpp b/netwerk/base/nsSimpleURI.cpp
index 59845ba3ec38..bd78fb555e76 100644
--- a/netwerk/base/nsSimpleURI.cpp
+++ b/netwerk/base/nsSimpleURI.cpp
@@ -48,7 +48,7 @@ nsSimpleURI::~nsSimpleURI()
 NS_IMPL_ADDREF(nsSimpleURI)
 NS_IMPL_RELEASE(nsSimpleURI)
 NS_INTERFACE_TABLE_HEAD(nsSimpleURI)
-NS_INTERFACE_TABLE(nsSimpleURI, nsIURI, nsIURIWithQuery, nsISerializable,
+NS_INTERFACE_TABLE(nsSimpleURI, nsIURI, nsISerializable,
                    nsIClassInfo, nsIMutable, nsIIPCSerializableURI)
 NS_INTERFACE_TABLE_TO_MAP_SEGUE
   if (aIID.Equals(kThisSimpleURIImplementationCID))
@@ -782,10 +782,6 @@ nsSimpleURI::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
   return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
 }
 
-//----------------------------------------------------------------------------
-// nsSimpleURI::nsIURIWithQuery
-//----------------------------------------------------------------------------
-
 NS_IMETHODIMP
 nsSimpleURI::GetFilePath(nsACString& aFilePath)
 {
diff --git a/netwerk/base/nsSimpleURI.h b/netwerk/base/nsSimpleURI.h
index 29bc9b313962..842136ed635a 100644
--- a/netwerk/base/nsSimpleURI.h
+++ b/netwerk/base/nsSimpleURI.h
@@ -8,7 +8,6 @@
 
 #include "mozilla/MemoryReporting.h"
 #include "nsIURI.h"
-#include "nsIURIWithQuery.h"
 #include "nsISerializable.h"
 #include "nsString.h"
 #include "nsIClassInfo.h"
@@ -28,7 +27,7 @@ namespace net {
 }
 
 class nsSimpleURI
-    : public nsIURIWithQuery
+    : public nsIURI
     , public nsISerializable
     , public nsIClassInfo
     , public nsIMutable
@@ -41,7 +40,6 @@ protected:
 public:
     NS_DECL_ISUPPORTS
     NS_DECL_NSIURI
-    NS_DECL_NSIURIWITHQUERY
     NS_DECL_NSISERIALIZABLE
     NS_DECL_NSICLASSINFO
     NS_DECL_NSIMUTABLE
diff --git a/netwerk/base/nsStandardURL.cpp b/netwerk/base/nsStandardURL.cpp
index d151bf5984eb..1f09742fc3b5 100644
--- a/netwerk/base/nsStandardURL.cpp
+++ b/netwerk/base/nsStandardURL.cpp
@@ -1232,7 +1232,6 @@ NS_IMPL_RELEASE(nsStandardURL)
 NS_INTERFACE_MAP_BEGIN(nsStandardURL)
     NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStandardURL)
     NS_INTERFACE_MAP_ENTRY(nsIURI)
-    NS_INTERFACE_MAP_ENTRY(nsIURIWithQuery)
     NS_INTERFACE_MAP_ENTRY(nsIURL)
     NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIFileURL, mSupportsFileURL)
     NS_INTERFACE_MAP_ENTRY(nsIStandardURL)
diff --git a/netwerk/base/nsStandardURL.h b/netwerk/base/nsStandardURL.h
index 5ef807335f32..3c06e0cc0137 100644
--- a/netwerk/base/nsStandardURL.h
+++ b/netwerk/base/nsStandardURL.h
@@ -55,7 +55,6 @@ protected:
 public:
     NS_DECL_ISUPPORTS
     NS_DECL_NSIURI
-    NS_DECL_NSIURIWITHQUERY
     NS_DECL_NSIURL
     NS_DECL_NSIFILEURL
     NS_DECL_NSISTANDARDURL

From 84f0acd454670ab20ab0e0273c5747d0cde156df Mon Sep 17 00:00:00 2001
From: Benjamin Bouvier 
Date: Thu, 29 Dec 2016 11:47:33 +0100
Subject: [PATCH 165/229] Bug 1326179: wasm: Disable parallel compilation on
 machines with 1 CPU; r=luke

MozReview-Commit-ID: EEGWa2u9U2X

--HG--
extra : rebase_source : b953c4c87bc2702929c474a55082781ff65201e3
extra : amend_source : aef6268c43ef4e2d9452315d459094779cd465c1
---
 js/src/wasm/WasmGenerator.cpp | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/js/src/wasm/WasmGenerator.cpp b/js/src/wasm/WasmGenerator.cpp
index a2551c871d8f..dcda4ab4519f 100644
--- a/js/src/wasm/WasmGenerator.cpp
+++ b/js/src/wasm/WasmGenerator.cpp
@@ -836,7 +836,10 @@ ModuleGenerator::startFuncDefs()
     MOZ_ASSERT(threads.threadCount > 1);
 
     uint32_t numTasks;
-    if (CanUseExtraThreads() && threads.wasmCompilationInProgress.compareExchange(false, true)) {
+    if (CanUseExtraThreads() &&
+        threads.cpuCount > 1 &&
+        threads.wasmCompilationInProgress.compareExchange(false, true))
+    {
 #ifdef DEBUG
         {
             AutoLockHelperThreadState lock;

From 73ec7c660f36c02c78dc66c276663eff7efcade5 Mon Sep 17 00:00:00 2001
From: Benjamin Bouvier 
Date: Fri, 30 Dec 2016 10:35:47 +0100
Subject: [PATCH 166/229] Bug 1326027: Remove RawF32 and RawF64; r=luke

MozReview-Commit-ID: ArjweiIrq0j

--HG--
extra : rebase_source : bfd12340181f8e7f475164e33a076c687e5d8c8c
extra : histedit_source : 8c3691d4fc5fea29fa71130655bce79d6fc7e087%2Ce1b529902b4474cc0a0eb56b465a1fcb8a1eefd8
---
 js/src/jit/MIR.cpp                            | 48 ++++++++----------
 js/src/jit/MIR.h                              | 16 ++----
 js/src/jit/arm/Assembler-arm.cpp              |  6 +--
 js/src/jit/arm/Assembler-arm.h                |  4 +-
 js/src/jit/arm/MacroAssembler-arm.cpp         | 29 ++++-------
 js/src/jit/arm/MacroAssembler-arm.h           |  6 +--
 js/src/jit/arm64/MacroAssembler-arm64.h       |  6 ---
 .../MacroAssembler-mips-shared.cpp            |  9 ----
 .../mips-shared/MacroAssembler-mips-shared.h  |  1 -
 js/src/jit/mips32/MacroAssembler-mips32.cpp   | 34 -------------
 js/src/jit/mips32/MacroAssembler-mips32.h     |  2 -
 js/src/jit/mips64/MacroAssembler-mips64.cpp   | 15 ------
 js/src/jit/mips64/MacroAssembler-mips64.h     |  2 -
 js/src/jit/none/MacroAssembler-none.h         |  2 -
 js/src/jit/shared/LIR-shared.h                | 12 ++---
 js/src/jit/shared/Lowering-shared.cpp         |  4 +-
 js/src/jit/shared/Lowering-shared.h           |  4 +-
 js/src/jit/x64/MacroAssembler-x64.cpp         | 20 ++------
 js/src/jit/x64/MacroAssembler-x64.h           |  2 -
 .../x86-shared/MacroAssembler-x86-shared.cpp  |  8 +--
 .../x86-shared/MacroAssembler-x86-shared.h    | 20 ++++----
 js/src/jit/x86/MacroAssembler-x86-inl.h       |  2 +-
 js/src/jit/x86/MacroAssembler-x86.cpp         | 20 ++------
 js/src/jit/x86/MacroAssembler-x86.h           |  2 -
 js/src/wasm/AsmJS.cpp                         | 17 ++++---
 js/src/wasm/WasmBaselineCompile.cpp           | 31 +++++++-----
 js/src/wasm/WasmBinaryIterator.h              | 20 ++++----
 js/src/wasm/WasmBinaryToAST.cpp               |  4 +-
 js/src/wasm/WasmBinaryToExperimentalText.cpp  | 12 ++---
 js/src/wasm/WasmBinaryToText.cpp              | 12 ++---
 js/src/wasm/WasmIonCompile.cpp                | 40 +++++++--------
 js/src/wasm/WasmJS.cpp                        | 14 ++++--
 js/src/wasm/WasmModule.cpp                    | 10 ++--
 js/src/wasm/WasmTextToBinary.cpp              |  9 ++--
 js/src/wasm/WasmTextUtils.cpp                 | 14 +++---
 js/src/wasm/WasmTextUtils.h                   |  5 +-
 js/src/wasm/WasmTypes.h                       | 49 +++----------------
 js/src/wasm/WasmValidate.cpp                  |  4 +-
 js/src/wasm/WasmValidate.h                    | 32 +++++-------
 39 files changed, 191 insertions(+), 356 deletions(-)

diff --git a/js/src/jit/MIR.cpp b/js/src/jit/MIR.cpp
index b49322871b03..e999c434e742 100644
--- a/js/src/jit/MIR.cpp
+++ b/js/src/jit/MIR.cpp
@@ -160,9 +160,9 @@ EvaluateConstantOperands(TempAllocator& alloc, MBinaryInstruction* ins, bool* pt
     // bits. This isn't strictly required for either ES or wasm, but it does
     // avoid making constant-folding observable.
     if (ins->type() == MIRType::Double)
-        return MConstant::New(alloc, wasm::RawF64(ret));
+        return MConstant::NewRawDouble(alloc, ret);
     if (ins->type() == MIRType::Float32)
-        return MConstant::New(alloc, wasm::RawF32(float(ret)));
+        return MConstant::NewRawFloat32(alloc, float(ret));
 
     Value retVal;
     retVal.setNumber(JS::CanonicalizeNaN(ret));
@@ -812,6 +812,18 @@ MConstant::New(TempAllocator::Fallible alloc, const Value& v, CompilerConstraint
     return new(alloc) MConstant(v, constraints);
 }
 
+MConstant*
+MConstant::NewRawFloat32(TempAllocator& alloc, float f)
+{
+    return new(alloc) MConstant(f);
+}
+
+MConstant*
+MConstant::NewRawDouble(TempAllocator& alloc, double d)
+{
+    return new(alloc) MConstant(d);
+}
+
 MConstant*
 MConstant::NewFloat32(TempAllocator& alloc, double d)
 {
@@ -819,22 +831,6 @@ MConstant::NewFloat32(TempAllocator& alloc, double d)
     return new(alloc) MConstant(float(d));
 }
 
-MConstant*
-MConstant::New(TempAllocator& alloc, wasm::RawF32 f)
-{
-    auto* c = new(alloc) MConstant(Int32Value(f.bits()), nullptr);
-    c->setResultType(MIRType::Float32);
-    return c;
-}
-
-MConstant*
-MConstant::New(TempAllocator& alloc, wasm::RawF64 d)
-{
-    auto* c = new(alloc) MConstant(int64_t(d.bits()));
-    c->setResultType(MIRType::Double);
-    return c;
-}
-
 MConstant*
 MConstant::NewInt64(TempAllocator& alloc, int64_t i)
 {
@@ -3299,10 +3295,10 @@ MMinMax::foldsTo(TempAllocator& alloc)
             if (mozilla::NumberEqualsInt32(result, &cast))
                 return MConstant::New(alloc, Int32Value(cast));
         } else if (type() == MIRType::Float32) {
-            return MConstant::New(alloc, wasm::RawF32(float(result)));
+            return MConstant::NewRawFloat32(alloc, float(result));
         } else {
             MOZ_ASSERT(type() == MIRType::Double);
-            return MConstant::New(alloc, wasm::RawF64(result));
+            return MConstant::NewRawDouble(alloc, result);
         }
     }
 
@@ -4340,10 +4336,8 @@ MToDouble::foldsTo(TempAllocator& alloc)
     if (input->type() == MIRType::Double)
         return input;
 
-    if (input->isConstant() && input->toConstant()->isTypeRepresentableAsDouble()) {
-        double out = input->toConstant()->numberToDouble();
-        return MConstant::New(alloc, wasm::RawF64(out));
-    }
+    if (input->isConstant() && input->toConstant()->isTypeRepresentableAsDouble())
+        return MConstant::NewRawDouble(alloc, input->toConstant()->numberToDouble());
 
     return this;
 }
@@ -4366,10 +4360,8 @@ MToFloat32::foldsTo(TempAllocator& alloc)
         return input->toToDouble()->input();
     }
 
-    if (input->isConstant() && input->toConstant()->isTypeRepresentableAsDouble()) {
-        float out = float(input->toConstant()->numberToDouble());
-        return MConstant::New(alloc, wasm::RawF32(out));
-    }
+    if (input->isConstant() && input->toConstant()->isTypeRepresentableAsDouble())
+        return MConstant::NewRawFloat32(alloc, float(input->toConstant()->numberToDouble()));
 
     return this;
 }
diff --git a/js/src/jit/MIR.h b/js/src/jit/MIR.h
index c79443e7c9aa..1651816cf5ce 100644
--- a/js/src/jit/MIR.h
+++ b/js/src/jit/MIR.h
@@ -1581,8 +1581,8 @@ class MConstant : public MNullaryInstruction
     static MConstant* New(TempAllocator::Fallible alloc, const Value& v,
                           CompilerConstraintList* constraints = nullptr);
     static MConstant* New(TempAllocator& alloc, const Value& v, MIRType type);
-    static MConstant* New(TempAllocator& alloc, wasm::RawF32 bits);
-    static MConstant* New(TempAllocator& alloc, wasm::RawF64 bits);
+    static MConstant* NewRawFloat32(TempAllocator& alloc, float f);
+    static MConstant* NewRawDouble(TempAllocator& alloc, double d);
     static MConstant* NewFloat32(TempAllocator& alloc, double d);
     static MConstant* NewInt64(TempAllocator& alloc, int64_t i);
     static MConstant* NewConstraintlessObject(TempAllocator& alloc, JSObject* v);
@@ -1650,22 +1650,14 @@ class MConstant : public MNullaryInstruction
     bool isInt32(int32_t i) const {
         return type() == MIRType::Int32 && payload_.i32 == i;
     }
-    double toDouble() const {
+    const double& toDouble() const {
         MOZ_ASSERT(type() == MIRType::Double);
         return payload_.d;
     }
-    wasm::RawF64 toRawF64() const {
-        MOZ_ASSERT(type() == MIRType::Double);
-        return wasm::RawF64::fromBits(payload_.i64);
-    }
-    float toFloat32() const {
+    const float& toFloat32() const {
         MOZ_ASSERT(type() == MIRType::Float32);
         return payload_.f;
     }
-    wasm::RawF32 toRawF32() const {
-        MOZ_ASSERT(type() == MIRType::Float32);
-        return wasm::RawF32::fromBits(payload_.i32);
-    }
     JSString* toString() const {
         MOZ_ASSERT(type() == MIRType::String);
         return payload_.str;
diff --git a/js/src/jit/arm/Assembler-arm.cpp b/js/src/jit/arm/Assembler-arm.cpp
index 261c70a8682f..9f0aa88afd00 100644
--- a/js/src/jit/arm/Assembler-arm.cpp
+++ b/js/src/jit/arm/Assembler-arm.cpp
@@ -2210,17 +2210,16 @@ Assembler::as_BranchPool(uint32_t value, RepatchLabel* label, ARMBuffer::PoolEnt
 }
 
 BufferOffset
-Assembler::as_FImm64Pool(VFPRegister dest, wasm::RawF64 value, Condition c)
+Assembler::as_FImm64Pool(VFPRegister dest, double d, Condition c)
 {
     MOZ_ASSERT(dest.isDouble());
     PoolHintPun php;
     php.phd.init(0, c, PoolHintData::PoolVDTR, dest);
-    uint64_t d = value.bits();
     return allocEntry(1, 2, (uint8_t*)&php.raw, (uint8_t*)&d);
 }
 
 BufferOffset
-Assembler::as_FImm32Pool(VFPRegister dest, wasm::RawF32 value, Condition c)
+Assembler::as_FImm32Pool(VFPRegister dest, float f, Condition c)
 {
     // Insert floats into the double pool as they have the same limitations on
     // immediate offset. This wastes 4 bytes padding per float. An alternative
@@ -2228,7 +2227,6 @@ Assembler::as_FImm32Pool(VFPRegister dest, wasm::RawF32 value, Condition c)
     MOZ_ASSERT(dest.isSingle());
     PoolHintPun php;
     php.phd.init(0, c, PoolHintData::PoolVDTR, dest);
-    uint32_t f = value.bits();
     return allocEntry(1, 1, (uint8_t*)&php.raw, (uint8_t*)&f);
 }
 
diff --git a/js/src/jit/arm/Assembler-arm.h b/js/src/jit/arm/Assembler-arm.h
index 4ccb2cb71d07..22a25f5d3a1a 100644
--- a/js/src/jit/arm/Assembler-arm.h
+++ b/js/src/jit/arm/Assembler-arm.h
@@ -1551,9 +1551,9 @@ class Assembler : public AssemblerShared
                                Label* documentation = nullptr);
 
     // Load a 64 bit floating point immediate from a pool into a register.
-    BufferOffset as_FImm64Pool(VFPRegister dest, wasm::RawF64 value, Condition c = Always);
+    BufferOffset as_FImm64Pool(VFPRegister dest, double value, Condition c = Always);
     // Load a 32 bit floating point immediate from a pool into a register.
-    BufferOffset as_FImm32Pool(VFPRegister dest, wasm::RawF32 value, Condition c = Always);
+    BufferOffset as_FImm32Pool(VFPRegister dest, float value, Condition c = Always);
 
     // Atomic instructions: ldrex, ldrexh, ldrexb, strex, strexh, strexb.
     //
diff --git a/js/src/jit/arm/MacroAssembler-arm.cpp b/js/src/jit/arm/MacroAssembler-arm.cpp
index 98817d7be88f..e6cce5d880c4 100644
--- a/js/src/jit/arm/MacroAssembler-arm.cpp
+++ b/js/src/jit/arm/MacroAssembler-arm.cpp
@@ -25,6 +25,7 @@ using namespace jit;
 
 using mozilla::Abs;
 using mozilla::BitwiseCast;
+using mozilla::IsPositiveZero;
 
 bool
 isValueDTRDCandidate(ValueOperand& val)
@@ -1527,19 +1528,19 @@ MacroAssemblerARM::ma_vsqrt_f32(FloatRegister src, FloatRegister dest, Condition
 }
 
 static inline uint32_t
-DoubleHighWord(wasm::RawF64 value)
+DoubleHighWord(double d)
 {
-    return static_cast(value.bits() >> 32);
+    return static_cast(BitwiseCast(d) >> 32);
 }
 
 static inline uint32_t
-DoubleLowWord(wasm::RawF64 value)
+DoubleLowWord(double d)
 {
-    return value.bits() & uint32_t(0xffffffff);
+    return static_cast(BitwiseCast(d)) & uint32_t(0xffffffff);
 }
 
 void
-MacroAssemblerARM::ma_vimm(wasm::RawF64 value, FloatRegister dest, Condition cc)
+MacroAssemblerARM::ma_vimm(double value, FloatRegister dest, Condition cc)
 {
     if (HasVFPv3()) {
         if (DoubleLowWord(value) == 0) {
@@ -1562,11 +1563,11 @@ MacroAssemblerARM::ma_vimm(wasm::RawF64 value, FloatRegister dest, Condition cc)
 }
 
 void
-MacroAssemblerARM::ma_vimm_f32(wasm::RawF32 value, FloatRegister dest, Condition cc)
+MacroAssemblerARM::ma_vimm_f32(float value, FloatRegister dest, Condition cc)
 {
     VFPRegister vd = VFPRegister(dest).singleOverlay();
     if (HasVFPv3()) {
-        if (value.bits() == 0) {
+        if (IsPositiveZero(value)) {
             // To zero a register, load 1.0, then execute sN <- sN - sN.
             as_vimm(vd, VFPImm::One, cc);
             as_vsub(vd, vd, vd, cc);
@@ -1580,7 +1581,7 @@ MacroAssemblerARM::ma_vimm_f32(wasm::RawF32 value, FloatRegister dest, Condition
         // paths. It is still necessary to firstly check that the double low
         // word is zero because some float32 numbers set these bits and this can
         // not be ignored.
-        wasm::RawF64 doubleValue(double(value.fp()));
+        double doubleValue(value);
         if (DoubleLowWord(doubleValue) == 0) {
             VFPImm enc(DoubleHighWord(doubleValue));
             if (enc.isValid()) {
@@ -3161,12 +3162,6 @@ MacroAssemblerARMCompat::int32ValueToFloat32(const ValueOperand& operand, FloatR
 
 void
 MacroAssemblerARMCompat::loadConstantFloat32(float f, FloatRegister dest)
-{
-    loadConstantFloat32(wasm::RawF32(f), dest);
-}
-
-void
-MacroAssemblerARMCompat::loadConstantFloat32(wasm::RawF32 f, FloatRegister dest)
 {
     ma_vimm_f32(f, dest);
 }
@@ -3231,12 +3226,6 @@ MacroAssemblerARMCompat::loadInt32OrDouble(Register base, Register index,
 
 void
 MacroAssemblerARMCompat::loadConstantDouble(double dp, FloatRegister dest)
-{
-    loadConstantDouble(wasm::RawF64(dp), dest);
-}
-
-void
-MacroAssemblerARMCompat::loadConstantDouble(wasm::RawF64 dp, FloatRegister dest)
 {
     ma_vimm(dp, dest);
 }
diff --git a/js/src/jit/arm/MacroAssembler-arm.h b/js/src/jit/arm/MacroAssembler-arm.h
index 1a7aad4462ea..f48517ca673c 100644
--- a/js/src/jit/arm/MacroAssembler-arm.h
+++ b/js/src/jit/arm/MacroAssembler-arm.h
@@ -376,8 +376,8 @@ class MacroAssemblerARM : public Assembler
     void ma_vsqrt(FloatRegister src, FloatRegister dest, Condition cc = Always);
     void ma_vsqrt_f32(FloatRegister src, FloatRegister dest, Condition cc = Always);
 
-    void ma_vimm(wasm::RawF64 value, FloatRegister dest, Condition cc = Always);
-    void ma_vimm_f32(wasm::RawF32 value, FloatRegister dest, Condition cc = Always);
+    void ma_vimm(double value, FloatRegister dest, Condition cc = Always);
+    void ma_vimm_f32(float value, FloatRegister dest, Condition cc = Always);
 
     void ma_vcmp(FloatRegister src1, FloatRegister src2, Condition cc = Always);
     void ma_vcmp_f32(FloatRegister src1, FloatRegister src2, Condition cc = Always);
@@ -793,7 +793,6 @@ class MacroAssemblerARMCompat : public MacroAssemblerARM
     void loadInt32OrDouble(Register base, Register index,
                            FloatRegister dest, int32_t shift = defaultShift);
     void loadConstantDouble(double dp, FloatRegister dest);
-    void loadConstantDouble(wasm::RawF64 dp, FloatRegister dest);
 
     // Treat the value as a boolean, and set condition codes accordingly.
     Condition testInt32Truthy(bool truthy, const ValueOperand& operand);
@@ -804,7 +803,6 @@ class MacroAssemblerARMCompat : public MacroAssemblerARM
     void boolValueToFloat32(const ValueOperand& operand, FloatRegister dest);
     void int32ValueToFloat32(const ValueOperand& operand, FloatRegister dest);
     void loadConstantFloat32(float f, FloatRegister dest);
-    void loadConstantFloat32(wasm::RawF32 f, FloatRegister dest);
 
     void moveValue(const Value& val, Register type, Register data);
 
diff --git a/js/src/jit/arm64/MacroAssembler-arm64.h b/js/src/jit/arm64/MacroAssembler-arm64.h
index 5fde70b65908..5e86fb962eab 100644
--- a/js/src/jit/arm64/MacroAssembler-arm64.h
+++ b/js/src/jit/arm64/MacroAssembler-arm64.h
@@ -1403,12 +1403,6 @@ class MacroAssemblerCompat : public vixl::MacroAssembler
         convertInt32ToFloat32(operand.valueReg(), dest);
     }
 
-    void loadConstantDouble(wasm::RawF64 d, FloatRegister dest) {
-        loadConstantDouble(d.fp(), dest);
-    }
-    void loadConstantFloat32(wasm::RawF32 f, FloatRegister dest) {
-        loadConstantFloat32(f.fp(), dest);
-    }
     void loadConstantDouble(double d, FloatRegister dest) {
         Fmov(ARMFPRegister(dest, 64), d);
     }
diff --git a/js/src/jit/mips-shared/MacroAssembler-mips-shared.cpp b/js/src/jit/mips-shared/MacroAssembler-mips-shared.cpp
index 658cafd36c68..29f89584bf10 100644
--- a/js/src/jit/mips-shared/MacroAssembler-mips-shared.cpp
+++ b/js/src/jit/mips-shared/MacroAssembler-mips-shared.cpp
@@ -1007,15 +1007,6 @@ MacroAssemblerMIPSShared::ma_lis(FloatRegister dest, float value)
     moveToFloat32(ScratchRegister, dest);
 }
 
-void
-MacroAssemblerMIPSShared::ma_lis(FloatRegister dest, wasm::RawF32 value)
-{
-    Imm32 imm(value.bits());
-
-    ma_li(ScratchRegister, imm);
-    moveToFloat32(ScratchRegister, dest);
-}
-
 void
 MacroAssemblerMIPSShared::ma_liNegZero(FloatRegister dest)
 {
diff --git a/js/src/jit/mips-shared/MacroAssembler-mips-shared.h b/js/src/jit/mips-shared/MacroAssembler-mips-shared.h
index 73b81fdf95fa..60e945753c4b 100644
--- a/js/src/jit/mips-shared/MacroAssembler-mips-shared.h
+++ b/js/src/jit/mips-shared/MacroAssembler-mips-shared.h
@@ -164,7 +164,6 @@ class MacroAssemblerMIPSShared : public Assembler
 
     // fp instructions
     void ma_lis(FloatRegister dest, float value);
-    void ma_lis(FloatRegister dest, wasm::RawF32 value);
     void ma_liNegZero(FloatRegister dest);
 
     void ma_sd(FloatRegister fd, BaseIndex address);
diff --git a/js/src/jit/mips32/MacroAssembler-mips32.cpp b/js/src/jit/mips32/MacroAssembler-mips32.cpp
index d3d3a75d11c5..2215d722857d 100644
--- a/js/src/jit/mips32/MacroAssembler-mips32.cpp
+++ b/js/src/jit/mips32/MacroAssembler-mips32.cpp
@@ -1401,12 +1401,6 @@ MacroAssemblerMIPSCompat::loadConstantFloat32(float f, FloatRegister dest)
     ma_lis(dest, f);
 }
 
-void
-MacroAssemblerMIPSCompat::loadConstantFloat32(wasm::RawF32 f, FloatRegister dest)
-{
-    ma_lis(dest, f);
-}
-
 void
 MacroAssemblerMIPSCompat::loadInt32OrDouble(const Address& src, FloatRegister dest)
 {
@@ -1457,34 +1451,6 @@ MacroAssemblerMIPSCompat::loadConstantDouble(double dp, FloatRegister dest)
     ma_lid(dest, dp);
 }
 
-void
-MacroAssemblerMIPSCompat::loadConstantDouble(wasm::RawF64 d, FloatRegister dest)
-{
-    struct DoubleStruct {
-        uint32_t lo;
-        uint32_t hi;
-    } ;
-    DoubleStruct intStruct = mozilla::BitwiseCast(d.bits());
-
-    // put hi part of 64 bit value into the odd register
-    if (intStruct.hi == 0) {
-        moveToDoubleHi(zero, dest);
-    } else {
-        ScratchRegisterScope scratch(asMasm());
-        ma_li(scratch, Imm32(intStruct.hi));
-        moveToDoubleHi(scratch, dest);
-    }
-
-    // put low part of 64 bit value into the even register
-    if (intStruct.lo == 0) {
-        moveToDoubleLo(zero, dest);
-    } else {
-        ScratchRegisterScope scratch(asMasm());
-        ma_li(scratch, Imm32(intStruct.lo));
-        moveToDoubleLo(scratch, dest);
-    }
-}
-
 Register
 MacroAssemblerMIPSCompat::extractObject(const Address& address, Register scratch)
 {
diff --git a/js/src/jit/mips32/MacroAssembler-mips32.h b/js/src/jit/mips32/MacroAssembler-mips32.h
index 9b846e25d606..7748f3978cc3 100644
--- a/js/src/jit/mips32/MacroAssembler-mips32.h
+++ b/js/src/jit/mips32/MacroAssembler-mips32.h
@@ -360,12 +360,10 @@ class MacroAssemblerMIPSCompat : public MacroAssemblerMIPS
     void loadInt32OrDouble(Register base, Register index,
                            FloatRegister dest, int32_t shift = defaultShift);
     void loadConstantDouble(double dp, FloatRegister dest);
-    void loadConstantDouble(wasm::RawF64 d, FloatRegister dest);
 
     void boolValueToFloat32(const ValueOperand& operand, FloatRegister dest);
     void int32ValueToFloat32(const ValueOperand& operand, FloatRegister dest);
     void loadConstantFloat32(float f, FloatRegister dest);
-    void loadConstantFloat32(wasm::RawF32 f, FloatRegister dest);
 
     void testNullSet(Condition cond, const ValueOperand& value, Register dest);
 
diff --git a/js/src/jit/mips64/MacroAssembler-mips64.cpp b/js/src/jit/mips64/MacroAssembler-mips64.cpp
index efdaac8d4a74..b7d6ba318dc0 100644
--- a/js/src/jit/mips64/MacroAssembler-mips64.cpp
+++ b/js/src/jit/mips64/MacroAssembler-mips64.cpp
@@ -1664,12 +1664,6 @@ MacroAssemblerMIPS64Compat::loadConstantFloat32(float f, FloatRegister dest)
     ma_lis(dest, f);
 }
 
-void
-MacroAssemblerMIPS64Compat::loadConstantFloat32(wasm::RawF32 f, FloatRegister dest)
-{
-    ma_lis(dest, f);
-}
-
 void
 MacroAssemblerMIPS64Compat::loadInt32OrDouble(const Address& src, FloatRegister dest)
 {
@@ -1720,15 +1714,6 @@ MacroAssemblerMIPS64Compat::loadConstantDouble(double dp, FloatRegister dest)
     ma_lid(dest, dp);
 }
 
-void
-MacroAssemblerMIPS64Compat::loadConstantDouble(wasm::RawF64 d, FloatRegister dest)
-{
-    ImmWord imm(d.bits());
-
-    ma_li(ScratchRegister, imm);
-    moveToDouble(ScratchRegister, dest);
-}
-
 Register
 MacroAssemblerMIPS64Compat::extractObject(const Address& address, Register scratch)
 {
diff --git a/js/src/jit/mips64/MacroAssembler-mips64.h b/js/src/jit/mips64/MacroAssembler-mips64.h
index 6b98f1f2c05c..208bee0bc37b 100644
--- a/js/src/jit/mips64/MacroAssembler-mips64.h
+++ b/js/src/jit/mips64/MacroAssembler-mips64.h
@@ -409,12 +409,10 @@ class MacroAssemblerMIPS64Compat : public MacroAssemblerMIPS64
     void loadInt32OrDouble(const Address& src, FloatRegister dest);
     void loadInt32OrDouble(const BaseIndex& addr, FloatRegister dest);
     void loadConstantDouble(double dp, FloatRegister dest);
-    void loadConstantDouble(wasm::RawF64 d, FloatRegister dest);
 
     void boolValueToFloat32(const ValueOperand& operand, FloatRegister dest);
     void int32ValueToFloat32(const ValueOperand& operand, FloatRegister dest);
     void loadConstantFloat32(float f, FloatRegister dest);
-    void loadConstantFloat32(wasm::RawF32 f, FloatRegister dest);
 
     void testNullSet(Condition cond, const ValueOperand& value, Register dest);
 
diff --git a/js/src/jit/none/MacroAssembler-none.h b/js/src/jit/none/MacroAssembler-none.h
index add8ae28c54c..51d626f08604 100644
--- a/js/src/jit/none/MacroAssembler-none.h
+++ b/js/src/jit/none/MacroAssembler-none.h
@@ -393,8 +393,6 @@ class MacroAssemblerNone : public Assembler
 
     void loadConstantDouble(double, FloatRegister) { MOZ_CRASH(); }
     void loadConstantFloat32(float, FloatRegister) { MOZ_CRASH(); }
-    void loadConstantDouble(wasm::RawF64, FloatRegister) { MOZ_CRASH(); }
-    void loadConstantFloat32(wasm::RawF32, FloatRegister) { MOZ_CRASH(); }
     Condition testInt32Truthy(bool, ValueOperand) { MOZ_CRASH(); }
     Condition testStringTruthy(bool, ValueOperand) { MOZ_CRASH(); }
 
diff --git a/js/src/jit/shared/LIR-shared.h b/js/src/jit/shared/LIR-shared.h
index 24780ab232f1..5f9f82296de9 100644
--- a/js/src/jit/shared/LIR-shared.h
+++ b/js/src/jit/shared/LIR-shared.h
@@ -858,14 +858,14 @@ class LPointer : public LInstructionHelper<1, 0, 0>
 // Constant double.
 class LDouble : public LInstructionHelper<1, 0, 0>
 {
-    wasm::RawF64 d_;
+    double d_;
   public:
     LIR_HEADER(Double);
 
-    explicit LDouble(wasm::RawF64 d) : d_(d)
+    explicit LDouble(double d) : d_(d)
     { }
 
-    wasm::RawF64 getDouble() const {
+    const double& getDouble() const {
         return d_;
     }
 };
@@ -873,15 +873,15 @@ class LDouble : public LInstructionHelper<1, 0, 0>
 // Constant float32.
 class LFloat32 : public LInstructionHelper<1, 0, 0>
 {
-    wasm::RawF32 f_;
+    float f_;
   public:
     LIR_HEADER(Float32);
 
-    explicit LFloat32(wasm::RawF32 f)
+    explicit LFloat32(float f)
       : f_(f)
     { }
 
-    wasm::RawF32 getFloat() const {
+    const float& getFloat() const {
         return f_;
     }
 };
diff --git a/js/src/jit/shared/Lowering-shared.cpp b/js/src/jit/shared/Lowering-shared.cpp
index 9e903bc285a3..9b4d5cdbb1ef 100644
--- a/js/src/jit/shared/Lowering-shared.cpp
+++ b/js/src/jit/shared/Lowering-shared.cpp
@@ -81,10 +81,10 @@ LIRGeneratorShared::visitConstant(MConstant* ins)
 
     switch (ins->type()) {
       case MIRType::Double:
-        define(new(alloc()) LDouble(ins->toRawF64()), ins);
+        define(new(alloc()) LDouble(ins->toDouble()), ins);
         break;
       case MIRType::Float32:
-        define(new(alloc()) LFloat32(ins->toRawF32()), ins);
+        define(new(alloc()) LFloat32(ins->toFloat32()), ins);
         break;
       case MIRType::Boolean:
         define(new(alloc()) LInteger(ins->toBoolean()), ins);
diff --git a/js/src/jit/shared/Lowering-shared.h b/js/src/jit/shared/Lowering-shared.h
index f862df5a0308..4bc3b84351ce 100644
--- a/js/src/jit/shared/Lowering-shared.h
+++ b/js/src/jit/shared/Lowering-shared.h
@@ -271,10 +271,10 @@ class LIRGeneratorShared : public MDefinitionVisitor
 
   public:
     void lowerConstantDouble(double d, MInstruction* mir) {
-        define(new(alloc()) LDouble(wasm::RawF64(d)), mir);
+        define(new(alloc()) LDouble(d), mir);
     }
     void lowerConstantFloat32(float f, MInstruction* mir) {
-        define(new(alloc()) LFloat32(wasm::RawF32(f)), mir);
+        define(new(alloc()) LFloat32(f), mir);
     }
 
     void visitConstant(MConstant* ins) override;
diff --git a/js/src/jit/x64/MacroAssembler-x64.cpp b/js/src/jit/x64/MacroAssembler-x64.cpp
index bc05bb963d81..f86c7b252f74 100644
--- a/js/src/jit/x64/MacroAssembler-x64.cpp
+++ b/js/src/jit/x64/MacroAssembler-x64.cpp
@@ -19,7 +19,7 @@ using namespace js;
 using namespace js::jit;
 
 void
-MacroAssemblerX64::loadConstantDouble(wasm::RawF64 d, FloatRegister dest)
+MacroAssemblerX64::loadConstantDouble(double d, FloatRegister dest)
 {
     if (maybeInlineDouble(d, dest))
         return;
@@ -36,7 +36,7 @@ MacroAssemblerX64::loadConstantDouble(wasm::RawF64 d, FloatRegister dest)
 }
 
 void
-MacroAssemblerX64::loadConstantFloat32(wasm::RawF32 f, FloatRegister dest)
+MacroAssemblerX64::loadConstantFloat32(float f, FloatRegister dest)
 {
     if (maybeInlineFloat(f, dest))
         return;
@@ -60,18 +60,6 @@ MacroAssemblerX64::loadConstantSimd128Int(const SimdConstant& v, FloatRegister d
     propagateOOM(val->uses.append(CodeOffset(j.offset())));
 }
 
-void
-MacroAssemblerX64::loadConstantFloat32(float f, FloatRegister dest)
-{
-    loadConstantFloat32(wasm::RawF32(f), dest);
-}
-
-void
-MacroAssemblerX64::loadConstantDouble(double d, FloatRegister dest)
-{
-    loadConstantDouble(wasm::RawF64(d), dest);
-}
-
 void
 MacroAssemblerX64::loadConstantSimd128Float(const SimdConstant&v, FloatRegister dest)
 {
@@ -265,14 +253,14 @@ MacroAssemblerX64::finish()
         masm.haltingAlign(sizeof(double));
     for (const Double& d : doubles_) {
         bindOffsets(d.uses);
-        masm.int64Constant(d.value);
+        masm.doubleConstant(d.value);
     }
 
     if (!floats_.empty())
         masm.haltingAlign(sizeof(float));
     for (const Float& f : floats_) {
         bindOffsets(f.uses);
-        masm.int32Constant(f.value);
+        masm.floatConstant(f.value);
     }
 
     // SIMD memory values must be suitably aligned.
diff --git a/js/src/jit/x64/MacroAssembler-x64.h b/js/src/jit/x64/MacroAssembler-x64.h
index a1d6c6c9029a..168c95f33bdb 100644
--- a/js/src/jit/x64/MacroAssembler-x64.h
+++ b/js/src/jit/x64/MacroAssembler-x64.h
@@ -857,8 +857,6 @@ class MacroAssemblerX64 : public MacroAssemblerX86Shared
 
     void loadConstantDouble(double d, FloatRegister dest);
     void loadConstantFloat32(float f, FloatRegister dest);
-    void loadConstantDouble(wasm::RawF64 d, FloatRegister dest);
-    void loadConstantFloat32(wasm::RawF32 f, FloatRegister dest);
 
     void loadConstantSimd128Int(const SimdConstant& v, FloatRegister dest);
     void loadConstantSimd128Float(const SimdConstant& v, FloatRegister dest);
diff --git a/js/src/jit/x86-shared/MacroAssembler-x86-shared.cpp b/js/src/jit/x86-shared/MacroAssembler-x86-shared.cpp
index 5841f933682e..8fc07d17bcc2 100644
--- a/js/src/jit/x86-shared/MacroAssembler-x86-shared.cpp
+++ b/js/src/jit/x86-shared/MacroAssembler-x86-shared.cpp
@@ -254,15 +254,15 @@ MacroAssemblerX86Shared::getConstant(const typename T::Pod& value, Map& map,
 }
 
 MacroAssemblerX86Shared::Float*
-MacroAssemblerX86Shared::getFloat(wasm::RawF32 f)
+MacroAssemblerX86Shared::getFloat(float f)
 {
-    return getConstant(f.bits(), floatMap_, floats_);
+    return getConstant(f, floatMap_, floats_);
 }
 
 MacroAssemblerX86Shared::Double*
-MacroAssemblerX86Shared::getDouble(wasm::RawF64 d)
+MacroAssemblerX86Shared::getDouble(double d)
 {
-    return getConstant(d.bits(), doubleMap_, doubles_);
+    return getConstant(d, doubleMap_, doubles_);
 }
 
 MacroAssemblerX86Shared::SimdData*
diff --git a/js/src/jit/x86-shared/MacroAssembler-x86-shared.h b/js/src/jit/x86-shared/MacroAssembler-x86-shared.h
index 8a0e154f154d..c5ea3f9e578b 100644
--- a/js/src/jit/x86-shared/MacroAssembler-x86-shared.h
+++ b/js/src/jit/x86-shared/MacroAssembler-x86-shared.h
@@ -66,14 +66,14 @@ class MacroAssemblerX86Shared : public Assembler
     // Containers use SystemAllocPolicy since wasm releases memory after each
     // function is compiled, and these need to live until after all functions
     // are compiled.
-    using Double = Constant;
+    using Double = Constant;
     Vector doubles_;
-    typedef HashMap, SystemAllocPolicy> DoubleMap;
+    typedef HashMap, SystemAllocPolicy> DoubleMap;
     DoubleMap doubleMap_;
 
-    using Float = Constant;
+    using Float = Constant;
     Vector floats_;
-    typedef HashMap, SystemAllocPolicy> FloatMap;
+    typedef HashMap, SystemAllocPolicy> FloatMap;
     FloatMap floatMap_;
 
     struct SimdData : public Constant {
@@ -90,8 +90,8 @@ class MacroAssemblerX86Shared : public Assembler
     template
     T* getConstant(const typename T::Pod& value, Map& map, Vector& vec);
 
-    Float* getFloat(wasm::RawF32 f);
-    Double* getDouble(wasm::RawF64 d);
+    Float* getFloat(float f);
+    Double* getDouble(double d);
     SimdData* getSimdData(const SimdConstant& v);
 
   public:
@@ -1210,9 +1210,9 @@ class MacroAssemblerX86Shared : public Assembler
 
     inline void clampIntToUint8(Register reg);
 
-    bool maybeInlineDouble(wasm::RawF64 d, FloatRegister dest) {
+    bool maybeInlineDouble(double d, FloatRegister dest) {
         // Loading zero with xor is specially optimized in hardware.
-        if (d.bits() == 0) {
+        if (mozilla::IsPositiveZero(d)) {
             zeroDouble(dest);
             return true;
         }
@@ -1228,9 +1228,9 @@ class MacroAssemblerX86Shared : public Assembler
         return false;
     }
 
-    bool maybeInlineFloat(wasm::RawF32 f, FloatRegister dest) {
+    bool maybeInlineFloat(float f, FloatRegister dest) {
         // See comment above
-        if (f.bits() == 0) {
+        if (mozilla::IsPositiveZero(f)) {
             zeroFloat32(dest);
             return true;
         }
diff --git a/js/src/jit/x86/MacroAssembler-x86-inl.h b/js/src/jit/x86/MacroAssembler-x86-inl.h
index 30f134a70116..546873f01001 100644
--- a/js/src/jit/x86/MacroAssembler-x86-inl.h
+++ b/js/src/jit/x86/MacroAssembler-x86-inl.h
@@ -184,7 +184,7 @@ MacroAssembler::add64(Imm64 imm, Register64 dest)
 void
 MacroAssembler::addConstantDouble(double d, FloatRegister dest)
 {
-    Double* dbl = getDouble(wasm::RawF64(d));
+    Double* dbl = getDouble(d);
     if (!dbl)
         return;
     masm.vaddsd_mr(nullptr, dest.encoding(), dest.encoding());
diff --git a/js/src/jit/x86/MacroAssembler-x86.cpp b/js/src/jit/x86/MacroAssembler-x86.cpp
index dec1e6d2bd69..3259e2c2a620 100644
--- a/js/src/jit/x86/MacroAssembler-x86.cpp
+++ b/js/src/jit/x86/MacroAssembler-x86.cpp
@@ -111,7 +111,7 @@ MacroAssemblerX86::convertUInt64ToDouble(Register64 src, FloatRegister dest, Reg
 }
 
 void
-MacroAssemblerX86::loadConstantDouble(wasm::RawF64 d, FloatRegister dest)
+MacroAssemblerX86::loadConstantDouble(double d, FloatRegister dest)
 {
     if (maybeInlineDouble(d, dest))
         return;
@@ -123,13 +123,7 @@ MacroAssemblerX86::loadConstantDouble(wasm::RawF64 d, FloatRegister dest)
 }
 
 void
-MacroAssemblerX86::loadConstantDouble(double d, FloatRegister dest)
-{
-    loadConstantDouble(wasm::RawF64(d), dest);
-}
-
-void
-MacroAssemblerX86::loadConstantFloat32(wasm::RawF32 f, FloatRegister dest)
+MacroAssemblerX86::loadConstantFloat32(float f, FloatRegister dest)
 {
     if (maybeInlineFloat(f, dest))
         return;
@@ -140,12 +134,6 @@ MacroAssemblerX86::loadConstantFloat32(wasm::RawF32 f, FloatRegister dest)
     propagateOOM(flt->uses.append(CodeOffset(masm.size())));
 }
 
-void
-MacroAssemblerX86::loadConstantFloat32(float f, FloatRegister dest)
-{
-    loadConstantFloat32(wasm::RawF32(f), dest);
-}
-
 void
 MacroAssemblerX86::loadConstantSimd128Int(const SimdConstant& v, FloatRegister dest)
 {
@@ -179,7 +167,7 @@ MacroAssemblerX86::finish()
         CodeOffset cst(masm.currentOffset());
         for (CodeOffset use : d.uses)
             addCodeLabel(CodeLabel(use, cst));
-        masm.int64Constant(d.value);
+        masm.doubleConstant(d.value);
         if (!enoughMemory_)
             return;
     }
@@ -190,7 +178,7 @@ MacroAssemblerX86::finish()
         CodeOffset cst(masm.currentOffset());
         for (CodeOffset use : f.uses)
             addCodeLabel(CodeLabel(use, cst));
-        masm.int32Constant(f.value);
+        masm.floatConstant(f.value);
         if (!enoughMemory_)
             return;
     }
diff --git a/js/src/jit/x86/MacroAssembler-x86.h b/js/src/jit/x86/MacroAssembler-x86.h
index 2b2507c77701..de5e26957b03 100644
--- a/js/src/jit/x86/MacroAssembler-x86.h
+++ b/js/src/jit/x86/MacroAssembler-x86.h
@@ -779,8 +779,6 @@ class MacroAssemblerX86 : public MacroAssemblerX86Shared
 
     void loadConstantDouble(double d, FloatRegister dest);
     void loadConstantFloat32(float f, FloatRegister dest);
-    void loadConstantDouble(wasm::RawF64 d, FloatRegister dest);
-    void loadConstantFloat32(wasm::RawF32 f, FloatRegister dest);
 
     void loadConstantSimd128Int(const SimdConstant& v, FloatRegister dest);
     void loadConstantSimd128Float(const SimdConstant& v, FloatRegister dest);
diff --git a/js/src/wasm/AsmJS.cpp b/js/src/wasm/AsmJS.cpp
index 84c7179306a8..372b63322274 100644
--- a/js/src/wasm/AsmJS.cpp
+++ b/js/src/wasm/AsmJS.cpp
@@ -59,6 +59,7 @@ using mozilla::Compression::LZ4;
 using mozilla::HashGeneric;
 using mozilla::IsNaN;
 using mozilla::IsNegativeZero;
+using mozilla::IsPositiveZero;
 using mozilla::IsPowerOfTwo;
 using mozilla::Maybe;
 using mozilla::Move;
@@ -888,14 +889,14 @@ class NumLit
         return (uint32_t)toInt32();
     }
 
-    RawF64 toDouble() const {
+    double toDouble() const {
         MOZ_ASSERT(which_ == Double);
-        return RawF64(u.scalar_.toDouble());
+        return u.scalar_.toDouble();
     }
 
-    RawF32 toFloat() const {
+    float toFloat() const {
         MOZ_ASSERT(which_ == Float);
-        return RawF32(float(u.scalar_.toDouble()));
+        return float(u.scalar_.toDouble());
     }
 
     Value scalarValue() const {
@@ -928,9 +929,9 @@ class NumLit
           case NumLit::BigUnsigned:
             return toInt32() == 0;
           case NumLit::Double:
-            return toDouble().bits() == 0;
+            return IsPositiveZero(toDouble());
           case NumLit::Float:
-            return toFloat().bits() == 0;
+            return IsPositiveZero(toFloat());
           case NumLit::Int8x16:
           case NumLit::Uint8x16:
           case NumLit::Bool8x16:
@@ -7516,14 +7517,14 @@ ValidateGlobalVariable(JSContext* cx, const AsmJSGlobal& global, HandleValue imp
             float f;
             if (!RoundFloat32(cx, v, &f))
                 return false;
-            *val = Val(RawF32(f));
+            *val = Val(f);
             return true;
           }
           case ValType::F64: {
             double d;
             if (!ToNumber(cx, v, &d))
                 return false;
-            *val = Val(RawF64(d));
+            *val = Val(d);
             return true;
           }
           case ValType::I8x16: {
diff --git a/js/src/wasm/WasmBaselineCompile.cpp b/js/src/wasm/WasmBaselineCompile.cpp
index 2b748b2ee104..dbd7a3737592 100644
--- a/js/src/wasm/WasmBaselineCompile.cpp
+++ b/js/src/wasm/WasmBaselineCompile.cpp
@@ -877,8 +877,8 @@ class BaseCompiler
             RegF64   f64reg_;
             int32_t  i32val_;
             int64_t  i64val_;
-            RawF32   f32val_;
-            RawF64   f64val_;
+            float    f32val_;
+            double   f64val_;
             uint32_t slot_;
             uint32_t offs_;
         };
@@ -894,8 +894,11 @@ class BaseCompiler
         RegF64   f64reg() const { MOZ_ASSERT(kind_ == RegisterF64); return f64reg_; }
         int32_t  i32val() const { MOZ_ASSERT(kind_ == ConstI32); return i32val_; }
         int64_t  i64val() const { MOZ_ASSERT(kind_ == ConstI64); return i64val_; }
-        RawF32   f32val() const { MOZ_ASSERT(kind_ == ConstF32); return f32val_; }
-        RawF64   f64val() const { MOZ_ASSERT(kind_ == ConstF64); return f64val_; }
+        // For these two, use an out-param instead of simply returning, to
+        // use the normal stack and not the x87 FP stack (which has effect on
+        // NaNs with the signaling bit set).
+        void     f32val(float* out) const { MOZ_ASSERT(kind_ == ConstF32); *out = f32val_; }
+        void     f64val(double* out) const { MOZ_ASSERT(kind_ == ConstF64); *out = f64val_; }
         uint32_t slot() const { MOZ_ASSERT(kind_ > MemLast && kind_ <= LocalLast); return slot_; }
         uint32_t offs() const { MOZ_ASSERT(isMem()); return offs_; }
 
@@ -905,8 +908,8 @@ class BaseCompiler
         void setF64Reg(RegF64 r) { kind_ = RegisterF64; f64reg_ = r; }
         void setI32Val(int32_t v) { kind_ = ConstI32; i32val_ = v; }
         void setI64Val(int64_t v) { kind_ = ConstI64; i64val_ = v; }
-        void setF32Val(RawF32 v) { kind_ = ConstF32; f32val_ = v; }
-        void setF64Val(RawF64 v) { kind_ = ConstF64; f64val_ = v; }
+        void setF32Val(float v) { kind_ = ConstF32; f32val_ = v; }
+        void setF64Val(double v) { kind_ = ConstF64; f64val_ = v; }
         void setSlot(Kind k, uint32_t v) { MOZ_ASSERT(k > MemLast && k <= LocalLast); kind_ = k; slot_ = v; }
         void setOffs(Kind k, uint32_t v) { MOZ_ASSERT(k <= MemLast); kind_ = k; offs_ = v; }
     };
@@ -1116,7 +1119,9 @@ class BaseCompiler
     }
 
     void loadConstF64(FloatRegister r, Stk &src) {
-        masm.loadConstantDouble(src.f64val(), r);
+        double d;
+        src.f64val(&d);
+        masm.loadConstantDouble(d, r);
     }
 
     void loadMemF64(FloatRegister r, Stk& src) {
@@ -1133,7 +1138,9 @@ class BaseCompiler
     }
 
     void loadConstF32(FloatRegister r, Stk &src) {
-        masm.loadConstantFloat32(src.f32val(), r);
+        float f;
+        src.f32val(&f);
+        masm.loadConstantFloat32(f, r);
     }
 
     void loadMemF32(FloatRegister r, Stk& src) {
@@ -1447,12 +1454,12 @@ class BaseCompiler
         x.setI64Val(v);
     }
 
-    void pushF64(RawF64 v) {
+    void pushF64(double v) {
         Stk& x = push();
         x.setF64Val(v);
     }
 
-    void pushF32(RawF32 v) {
+    void pushF32(float v) {
         Stk& x = push();
         x.setF32Val(v);
     }
@@ -7168,7 +7175,7 @@ BaseCompiler::emitBody()
 
           // F32
           case uint16_t(Op::F32Const): {
-            RawF32 f32;
+            float f32;
             CHECK(iter_.readF32Const(&f32));
             if (!deadCode_)
                 pushF32(f32);
@@ -7237,7 +7244,7 @@ BaseCompiler::emitBody()
 
           // F64
           case uint16_t(Op::F64Const): {
-            RawF64 f64;
+            double f64;
             CHECK(iter_.readF64Const(&f64));
             if (!deadCode_)
                 pushF64(f64);
diff --git a/js/src/wasm/WasmBinaryIterator.h b/js/src/wasm/WasmBinaryIterator.h
index 93f446b03a59..5c98c9900c89 100644
--- a/js/src/wasm/WasmBinaryIterator.h
+++ b/js/src/wasm/WasmBinaryIterator.h
@@ -308,16 +308,16 @@ class MOZ_STACK_CLASS OpIter : private Policy
         *out = d_.uncheckedReadVarU64();
         return true;
     }
-    MOZ_MUST_USE bool readFixedF32(RawF32* out) {
+    MOZ_MUST_USE bool readFixedF32(float* out) {
         if (Validate)
             return d_.readFixedF32(out);
-        *out = d_.uncheckedReadFixedF32();
+        d_.uncheckedReadFixedF32(out);
         return true;
     }
-    MOZ_MUST_USE bool readFixedF64(RawF64* out) {
+    MOZ_MUST_USE bool readFixedF64(double* out) {
         if (Validate)
             return d_.readFixedF64(out);
-        *out = d_.uncheckedReadFixedF64();
+        d_.uncheckedReadFixedF64(out);
         return true;
     }
     MOZ_MUST_USE bool readFixedI8x16(I8x16* out) {
@@ -575,8 +575,8 @@ class MOZ_STACK_CLASS OpIter : private Policy
     MOZ_MUST_USE bool readTeeGlobal(const GlobalDescVector& globals, uint32_t* id, Value* value);
     MOZ_MUST_USE bool readI32Const(int32_t* i32);
     MOZ_MUST_USE bool readI64Const(int64_t* i64);
-    MOZ_MUST_USE bool readF32Const(RawF32* f32);
-    MOZ_MUST_USE bool readF64Const(RawF64* f64);
+    MOZ_MUST_USE bool readF32Const(float* f32);
+    MOZ_MUST_USE bool readF64Const(double* f64);
     MOZ_MUST_USE bool readI8x16Const(I8x16* i8x16);
     MOZ_MUST_USE bool readI16x8Const(I16x8* i16x8);
     MOZ_MUST_USE bool readI32x4Const(I32x4* i32x4);
@@ -1618,11 +1618,11 @@ OpIter::readI64Const(int64_t* i64)
 
 template 
 inline bool
-OpIter::readF32Const(RawF32* f32)
+OpIter::readF32Const(float* f32)
 {
     MOZ_ASSERT(Classify(op_) == OpKind::F32);
 
-    RawF32 unused;
+    float unused;
     if (!readFixedF32(Output ? f32 : &unused))
         return false;
 
@@ -1634,11 +1634,11 @@ OpIter::readF32Const(RawF32* f32)
 
 template 
 inline bool
-OpIter::readF64Const(RawF64* f64)
+OpIter::readF64Const(double* f64)
 {
     MOZ_ASSERT(Classify(op_) == OpKind::F64);
 
-    RawF64 unused;
+    double unused;
     if (!readFixedF64(Output ? f64 : &unused))
        return false;
 
diff --git a/js/src/wasm/WasmBinaryToAST.cpp b/js/src/wasm/WasmBinaryToAST.cpp
index 2e90e36a319d..49b0ee1698e5 100644
--- a/js/src/wasm/WasmBinaryToAST.cpp
+++ b/js/src/wasm/WasmBinaryToAST.cpp
@@ -1044,7 +1044,7 @@ AstDecodeExpr(AstDecodeContext& c)
             return false;
         break;
       case uint16_t(Op::F32Const): {
-        RawF32 f32;
+        float f32;
         if (!c.iter().readF32Const(&f32))
             return false;
         tmp = new(c.lifo) AstConst(Val(f32));
@@ -1053,7 +1053,7 @@ AstDecodeExpr(AstDecodeContext& c)
         break;
       }
       case uint16_t(Op::F64Const): {
-        RawF64 f64;
+        double f64;
         if (!c.iter().readF64Const(&f64))
             return false;
         tmp = new(c.lifo) AstConst(Val(f64));
diff --git a/js/src/wasm/WasmBinaryToExperimentalText.cpp b/js/src/wasm/WasmBinaryToExperimentalText.cpp
index 29f79981b697..190827f77594 100644
--- a/js/src/wasm/WasmBinaryToExperimentalText.cpp
+++ b/js/src/wasm/WasmBinaryToExperimentalText.cpp
@@ -164,13 +164,12 @@ PrintInt64(WasmPrintContext& c, int64_t num)
 }
 
 static bool
-PrintDouble(WasmPrintContext& c, RawF64 num)
+PrintDouble(WasmPrintContext& c, double d)
 {
-    double d = num.fp();
     if (IsNegativeZero(d))
         return c.buffer.append("-0.0");
     if (IsNaN(d))
-        return RenderNaN(c.sb(), num);
+        return RenderNaN(c.sb(), d);
     if (IsInfinite(d)) {
         if (d > 0)
             return c.buffer.append("infinity");
@@ -192,12 +191,11 @@ PrintDouble(WasmPrintContext& c, RawF64 num)
 }
 
 static bool
-PrintFloat32(WasmPrintContext& c, RawF32 num)
+PrintFloat32(WasmPrintContext& c, float f)
 {
-    float f = num.fp();
     if (IsNaN(f))
-        return RenderNaN(c.sb(), num) && c.buffer.append(".f");
-    return PrintDouble(c, RawF64(double(f))) &&
+        return RenderNaN(c.sb(), f) && c.buffer.append(".f");
+    return PrintDouble(c, double(f)) &&
            c.buffer.append("f");
 }
 
diff --git a/js/src/wasm/WasmBinaryToText.cpp b/js/src/wasm/WasmBinaryToText.cpp
index 023ff56ebb4f..9280d11486fd 100644
--- a/js/src/wasm/WasmBinaryToText.cpp
+++ b/js/src/wasm/WasmBinaryToText.cpp
@@ -101,11 +101,10 @@ RenderInt64(WasmRenderContext& c, int64_t num)
 }
 
 static bool
-RenderDouble(WasmRenderContext& c, RawF64 num)
+RenderDouble(WasmRenderContext& c, double d)
 {
-    double d = num.fp();
     if (IsNaN(d))
-        return RenderNaN(c.sb(), num);
+        return RenderNaN(c.sb(), d);
     if (IsNegativeZero(d))
         return c.buffer.append("-0");
     if (IsInfinite(d)) {
@@ -117,12 +116,11 @@ RenderDouble(WasmRenderContext& c, RawF64 num)
 }
 
 static bool
-RenderFloat32(WasmRenderContext& c, RawF32 num)
+RenderFloat32(WasmRenderContext& c, float f)
 {
-    float f = num.fp();
     if (IsNaN(f))
-        return RenderNaN(c.sb(), num);
-    return RenderDouble(c, RawF64(double(f)));
+        return RenderNaN(c.sb(), f);
+    return RenderDouble(c, double(f));
 }
 
 static bool
diff --git a/js/src/wasm/WasmIonCompile.cpp b/js/src/wasm/WasmIonCompile.cpp
index db0f99cc3a27..565196d9d19f 100644
--- a/js/src/wasm/WasmIonCompile.cpp
+++ b/js/src/wasm/WasmIonCompile.cpp
@@ -343,6 +343,24 @@ class FunctionCompiler
         return constant;
     }
 
+    MDefinition* constant(float f)
+    {
+        if (inDeadCode())
+            return nullptr;
+        MConstant* constant = MConstant::NewRawFloat32(alloc(), f);
+        curBlock_->add(constant);
+        return constant;
+    }
+
+    MDefinition* constant(double d)
+    {
+        if (inDeadCode())
+            return nullptr;
+        MConstant* constant = MConstant::NewRawDouble(alloc(), d);
+        curBlock_->add(constant);
+        return constant;
+    }
+
     MDefinition* constant(int64_t i)
     {
         if (inDeadCode())
@@ -352,24 +370,6 @@ class FunctionCompiler
         return constant;
     }
 
-    MDefinition* constant(RawF32 f)
-    {
-        if (inDeadCode())
-            return nullptr;
-        MConstant* constant = MConstant::New(alloc(), f);
-        curBlock_->add(constant);
-        return constant;
-    }
-
-    MDefinition* constant(RawF64 d)
-    {
-        if (inDeadCode())
-            return nullptr;
-        MConstant* constant = MConstant::New(alloc(), d);
-        curBlock_->add(constant);
-        return constant;
-    }
-
     template 
     MDefinition* unary(MDefinition* op)
     {
@@ -3334,7 +3334,7 @@ EmitExpr(FunctionCompiler& f)
 
       // F32
       case Op::F32Const: {
-        RawF32 f32;
+        float f32;
         if (!f.iter().readF32Const(&f32))
             return false;
 
@@ -3392,7 +3392,7 @@ EmitExpr(FunctionCompiler& f)
 
       // F64
       case Op::F64Const: {
-        RawF64 f64;
+        double f64;
         if (!f.iter().readF64Const(&f64))
             return false;
 
diff --git a/js/src/wasm/WasmJS.cpp b/js/src/wasm/WasmJS.cpp
index a19451a39099..63aaac59f777 100644
--- a/js/src/wasm/WasmJS.cpp
+++ b/js/src/wasm/WasmJS.cpp
@@ -41,6 +41,8 @@
 using namespace js;
 using namespace js::jit;
 using namespace js::wasm;
+
+using mozilla::BitwiseCast;
 using mozilla::CheckedInt;
 using mozilla::IsNaN;
 using mozilla::IsSame;
@@ -304,7 +306,9 @@ GetImports(JSContext* cx,
                     uint32_t bits;
                     if (!ReadCustomFloat32NaNObject(cx, v, &bits))
                         return false;
-                    val = Val(RawF32::fromBits(bits));
+                    float f;
+                    BitwiseCast(bits, &f);
+                    val = Val(f);
                     break;
                 }
                 if (!v.isNumber())
@@ -312,7 +316,7 @@ GetImports(JSContext* cx,
                 double d;
                 if (!ToNumber(cx, v, &d))
                     return false;
-                val = Val(RawF32(float(d)));
+                val = Val(float(d));
                 break;
               }
               case ValType::F64: {
@@ -320,7 +324,9 @@ GetImports(JSContext* cx,
                     uint64_t bits;
                     if (!ReadCustomDoubleNaNObject(cx, v, &bits))
                         return false;
-                    val = Val(RawF64::fromBits(bits));
+                    double d;
+                    BitwiseCast(bits, &d);
+                    val = Val(d);
                     break;
                 }
                 if (!v.isNumber())
@@ -328,7 +334,7 @@ GetImports(JSContext* cx,
                 double d;
                 if (!ToNumber(cx, v, &d))
                     return false;
-                val = Val(RawF64(d));
+                val = Val(d);
                 break;
               }
               default: {
diff --git a/js/src/wasm/WasmModule.cpp b/js/src/wasm/WasmModule.cpp
index f7d33debb1f4..69b60f5f80b4 100644
--- a/js/src/wasm/WasmModule.cpp
+++ b/js/src/wasm/WasmModule.cpp
@@ -766,10 +766,9 @@ GetGlobalExport(JSContext* cx, const GlobalDescVector& globals, uint32_t globalI
         return true;
       }
       case ValType::F32: {
-        float f = val.f32().fp();
+        float f = val.f32();
         if (JitOptions.wasmTestMode && IsNaN(f)) {
-            uint32_t bits = val.f32().bits();
-            RootedObject obj(cx, CreateCustomNaNObject(cx, (float*)&bits));
+            RootedObject obj(cx, CreateCustomNaNObject(cx, &f));
             if (!obj)
                 return false;
             jsval.set(ObjectValue(*obj));
@@ -779,10 +778,9 @@ GetGlobalExport(JSContext* cx, const GlobalDescVector& globals, uint32_t globalI
         return true;
       }
       case ValType::F64: {
-        double d = val.f64().fp();
+        double d = val.f64();
         if (JitOptions.wasmTestMode && IsNaN(d)) {
-            uint64_t bits = val.f64().bits();
-            RootedObject obj(cx, CreateCustomNaNObject(cx, (double*)&bits));
+            RootedObject obj(cx, CreateCustomNaNObject(cx, &d));
             if (!obj)
                 return false;
             jsval.set(ObjectValue(*obj));
diff --git a/js/src/wasm/WasmTextToBinary.cpp b/js/src/wasm/WasmTextToBinary.cpp
index 3035cb08c061..d081b2469ae3 100644
--- a/js/src/wasm/WasmTextToBinary.cpp
+++ b/js/src/wasm/WasmTextToBinary.cpp
@@ -1780,7 +1780,10 @@ ParseNaNLiteral(WasmParseContext& c, WasmToken token, const char16_t* cur, bool
     }
 
     value = (isNegated ? Traits::kSignBit : 0) | Traits::kExponentBits | value;
-    return new (c.lifo) AstConst(Val(Raw::fromBits(value)));
+
+    Float flt;
+    BitwiseCast(value, &flt);
+    return new (c.lifo) AstConst(Val(flt));
 
   error:
     c.ts.generateError(token, c.error);
@@ -1932,7 +1935,7 @@ ParseFloatLiteral(WasmParseContext& c, WasmToken token)
     }
 
     if (token.kind() != WasmToken::Float)
-        return new (c.lifo) AstConst(Val(Raw(result)));
+        return new (c.lifo) AstConst(Val(Float(result)));
 
     const char16_t* begin = token.begin();
     const char16_t* end = token.end();
@@ -1983,7 +1986,7 @@ ParseFloatLiteral(WasmParseContext& c, WasmToken token)
     if (isNegated)
         result = -result;
 
-    return new (c.lifo) AstConst(Val(Raw(result)));
+    return new (c.lifo) AstConst(Val(Float(result)));
 }
 
 static AstConst*
diff --git a/js/src/wasm/WasmTextUtils.cpp b/js/src/wasm/WasmTextUtils.cpp
index 818f63e6d98f..757eb5d96e9a 100644
--- a/js/src/wasm/WasmTextUtils.cpp
+++ b/js/src/wasm/WasmTextUtils.cpp
@@ -54,18 +54,20 @@ template bool wasm::RenderInBase<10>(StringBuffer& sb, uint64_t num);
 
 template
 bool
-wasm::RenderNaN(StringBuffer& sb, Raw num)
+wasm::RenderNaN(StringBuffer& sb, T num)
 {
     typedef typename mozilla::SelectTrait Traits;
+    typedef typename Traits::Bits Bits;
 
-    MOZ_ASSERT(IsNaN(num.fp()));
+    MOZ_ASSERT(IsNaN(num));
 
-    if ((num.bits() & Traits::kSignBit) && !sb.append("-"))
+    Bits bits = mozilla::BitwiseCast(num);
+    if ((bits & Traits::kSignBit) && !sb.append("-"))
         return false;
     if (!sb.append("nan"))
         return false;
 
-    typename Traits::Bits payload = num.bits() & Traits::kSignificandBits;
+    Bits payload = bits & Traits::kSignificandBits;
     // Only render the payload if it's not the spec's default NaN.
     if (payload == ((Traits::kSignificandBits + 1) >> 1))
         return true;
@@ -74,5 +76,5 @@ wasm::RenderNaN(StringBuffer& sb, Raw num)
            RenderInBase<16>(sb, payload);
 }
 
-template MOZ_MUST_USE bool wasm::RenderNaN(StringBuffer& b, Raw num);
-template MOZ_MUST_USE bool wasm::RenderNaN(StringBuffer& b, Raw num);
+template MOZ_MUST_USE bool wasm::RenderNaN(StringBuffer& b, float num);
+template MOZ_MUST_USE bool wasm::RenderNaN(StringBuffer& b, double num);
diff --git a/js/src/wasm/WasmTextUtils.h b/js/src/wasm/WasmTextUtils.h
index 1bc1eecfdff6..876abd39777e 100644
--- a/js/src/wasm/WasmTextUtils.h
+++ b/js/src/wasm/WasmTextUtils.h
@@ -30,12 +30,9 @@ template
 MOZ_MUST_USE bool
 RenderInBase(StringBuffer& sb, uint64_t num);
 
-template
-class Raw;
-
 template
 MOZ_MUST_USE bool
-RenderNaN(StringBuffer& sb, Raw num);
+RenderNaN(StringBuffer& sb, T num);
 
 // Helper class, StringBuffer wrapper, to track the position (line and column)
 // within the generated source.
diff --git a/js/src/wasm/WasmTypes.h b/js/src/wasm/WasmTypes.h
index 8954439f8bd0..babc80617ca0 100644
--- a/js/src/wasm/WasmTypes.h
+++ b/js/src/wasm/WasmTypes.h
@@ -337,41 +337,6 @@ ToCString(ValType type)
     return ToCString(ToExprType(type));
 }
 
-// Because WebAssembly allows one to define the payload of a NaN value,
-// including the signal/quiet bit (highest order bit of payload), another
-// represenation of floating-point values is required: on some platforms (x86
-// without SSE2), passing a floating-point argument to a function call may use
-// the x87 stack, which has the side-effect of clearing the signal/quiet bit.
-// Because the signal/quiet bit must be preserved (by spec), we use the raw
-// punned integer representation of floating points instead, in function calls.
-//
-// When we leave the WebAssembly sandbox back to JS, NaNs are canonicalized, so
-// this isn't observable from JS.
-
-template
-class Raw
-{
-    typedef typename mozilla::FloatingPoint::Bits Bits;
-    Bits value_;
-
-  public:
-    Raw() : value_(0) {}
-
-    explicit Raw(T value)
-      : value_(mozilla::BitwiseCast(value))
-    {}
-
-    template MOZ_IMPLICIT Raw(U) = delete;
-
-    static Raw fromBits(Bits bits) { Raw r; r.value_ = bits; return r; }
-
-    Bits bits() const { return value_; }
-    T fp() const { return mozilla::BitwiseCast(value_); }
-};
-
-using RawF64 = Raw;
-using RawF32 = Raw;
-
 // The Val class represents a single WebAssembly value of a given value type,
 // mostly for the purpose of numeric literals and initializers. A Val does not
 // directly map to a JS value since there is not (currently) a precise
@@ -385,8 +350,8 @@ class Val
     union U {
         uint32_t i32_;
         uint64_t i64_;
-        RawF32 f32_;
-        RawF64 f64_;
+        float f32_;
+        double f64_;
         I8x16 i8x16_;
         I16x8 i16x8_;
         I32x4 i32x4_;
@@ -400,10 +365,8 @@ class Val
     explicit Val(uint32_t i32) : type_(ValType::I32) { u.i32_ = i32; }
     explicit Val(uint64_t i64) : type_(ValType::I64) { u.i64_ = i64; }
 
-    explicit Val(RawF32 f32) : type_(ValType::F32) { u.f32_ = f32; }
-    explicit Val(RawF64 f64) : type_(ValType::F64) { u.f64_ = f64; }
-    MOZ_IMPLICIT Val(float) = delete;
-    MOZ_IMPLICIT Val(double) = delete;
+    explicit Val(float f32) : type_(ValType::F32) { u.f32_ = f32; }
+    explicit Val(double f64) : type_(ValType::F64) { u.f64_ = f64; }
 
     explicit Val(const I8x16& i8x16, ValType type = ValType::I8x16) : type_(type) {
         MOZ_ASSERT(type_ == ValType::I8x16 || type_ == ValType::B8x16);
@@ -426,8 +389,8 @@ class Val
 
     uint32_t i32() const { MOZ_ASSERT(type_ == ValType::I32); return u.i32_; }
     uint64_t i64() const { MOZ_ASSERT(type_ == ValType::I64); return u.i64_; }
-    RawF32 f32() const { MOZ_ASSERT(type_ == ValType::F32); return u.f32_; }
-    RawF64 f64() const { MOZ_ASSERT(type_ == ValType::F64); return u.f64_; }
+    const float& f32() const { MOZ_ASSERT(type_ == ValType::F32); return u.f32_; }
+    const double& f64() const { MOZ_ASSERT(type_ == ValType::F64); return u.f64_; }
 
     const I8x16& i8x16() const {
         MOZ_ASSERT(type_ == ValType::I8x16 || type_ == ValType::B8x16);
diff --git a/js/src/wasm/WasmValidate.cpp b/js/src/wasm/WasmValidate.cpp
index 3e51e266272e..4c17c9d9a30e 100644
--- a/js/src/wasm/WasmValidate.cpp
+++ b/js/src/wasm/WasmValidate.cpp
@@ -1139,14 +1139,14 @@ DecodeInitializerExpression(Decoder& d, const GlobalDescVector& globals, ValType
         break;
       }
       case uint16_t(Op::F32Const): {
-        RawF32 f32;
+        float f32;
         if (!d.readFixedF32(&f32))
             return d.fail("failed to read initializer f32 expression");
         *init = InitExpr(Val(f32));
         break;
       }
       case uint16_t(Op::F64Const): {
-        RawF64 f64;
+        double f64;
         if (!d.readFixedF64(&f64))
             return d.fail("failed to read initializer f64 expression");
         *init = InitExpr(Val(f64));
diff --git a/js/src/wasm/WasmValidate.h b/js/src/wasm/WasmValidate.h
index 4ddeba5a242c..bf756e85e715 100644
--- a/js/src/wasm/WasmValidate.h
+++ b/js/src/wasm/WasmValidate.h
@@ -198,11 +198,11 @@ class Encoder
     MOZ_MUST_USE bool writeFixedU32(uint32_t i) {
         return write(i);
     }
-    MOZ_MUST_USE bool writeFixedF32(RawF32 f) {
-        return write(f.bits());
+    MOZ_MUST_USE bool writeFixedF32(float f) {
+        return write(f);
     }
-    MOZ_MUST_USE bool writeFixedF64(RawF64 d) {
-        return write(d.bits());
+    MOZ_MUST_USE bool writeFixedF64(double d) {
+        return write(d);
     }
     MOZ_MUST_USE bool writeFixedI8x16(const I8x16& i8x16) {
         return write(i8x16);
@@ -437,19 +437,11 @@ class Decoder
     MOZ_MUST_USE bool readFixedU32(uint32_t* u) {
         return read(u);
     }
-    MOZ_MUST_USE bool readFixedF32(RawF32* f) {
-        uint32_t u;
-        if (!read(&u))
-            return false;
-        *f = RawF32::fromBits(u);
-        return true;
+    MOZ_MUST_USE bool readFixedF32(float* f) {
+        return read(f);
     }
-    MOZ_MUST_USE bool readFixedF64(RawF64* d) {
-        uint64_t u;
-        if (!read(&u))
-            return false;
-        *d = RawF64::fromBits(u);
-        return true;
+    MOZ_MUST_USE bool readFixedF64(double* d) {
+        return read(d);
     }
     MOZ_MUST_USE bool readFixedI8x16(I8x16* i8x16) {
         return read(i8x16);
@@ -556,11 +548,11 @@ class Decoder
     uint32_t uncheckedReadFixedU32() {
         return uncheckedRead();
     }
-    RawF32 uncheckedReadFixedF32() {
-        return RawF32::fromBits(uncheckedRead());
+    void uncheckedReadFixedF32(float* out) {
+        uncheckedRead(out);
     }
-    RawF64 uncheckedReadFixedF64() {
-        return RawF64::fromBits(uncheckedRead());
+    void uncheckedReadFixedF64(double* out) {
+        uncheckedRead(out);
     }
     template 
     UInt uncheckedReadVarU() {

From 963bd869375abd0b2760ecada638e1cb54ffcc0a Mon Sep 17 00:00:00 2001
From: Benjamin Bouvier 
Date: Thu, 29 Dec 2016 10:31:38 +0100
Subject: [PATCH 167/229] Bug 1326027: include SSE2 flags in autospider;
 r=sfink

MozReview-Commit-ID: KWDBsmU798J

--HG--
extra : rebase_source : 3c7ce36f9ecaab0dd70b4ddcc1e9715e1ee8b8c9
extra : histedit_source : 42cced527e07d09a90994a19188bb812803003f3
---
 js/src/devtools/automation/autospider.py | 9 +++++++++
 js/src/moz.build                         | 3 ---
 2 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/js/src/devtools/automation/autospider.py b/js/src/devtools/automation/autospider.py
index 08de8c372025..288c88edf835 100755
--- a/js/src/devtools/automation/autospider.py
+++ b/js/src/devtools/automation/autospider.py
@@ -216,6 +216,15 @@ if word_bits == 32:
     elif platform.system() == 'Linux':
         if UNAME_M != 'arm':
             CONFIGURE_ARGS += ' --target=i686-pc-linux --host=i686-pc-linux'
+
+    # Add SSE2 support for x86/x64 architectures.
+    if UNAME_M != 'arm':
+        if platform.system() == 'Windows':
+            sse_flags = '-arch:SSE2'
+        else:
+            sse_flags = '-msse -msse2 -mfpmath=sse'
+        env['CCFLAGS'] = '{0} {1}'.format(env.get('CCFLAGS', ''), sse_flags)
+        env['CXXFLAGS'] = '{0} {1}'.format(env.get('CXXFLAGS', ''), sse_flags)
 else:
     if platform.system() == 'Windows':
         CONFIGURE_ARGS += ' --target=x86_64-pc-mingw32 --host=x86_64-pc-mingw32'
diff --git a/js/src/moz.build b/js/src/moz.build
index 786fc068b92a..a89ab6a55e30 100644
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -498,9 +498,6 @@ elif CONFIG['JS_CODEGEN_ARM']:
         UNIFIED_SOURCES += [
             'jit/arm/Simulator-arm.cpp'
         ]
-        # Configuration used only for testing.
-        if CONFIG['OS_ARCH'] == 'Linux' or CONFIG['OS_ARCH'] == 'Darwin':
-            CXXFLAGS += [ '-msse2', '-mfpmath=sse' ]
     elif CONFIG['OS_ARCH'] == 'Darwin':
         SOURCES += [
             'jit/arm/llvm-compiler-rt/arm/aeabi_idivmod.S',

From 70cf8ed90810b080c864ac7ad729344bfe0cf1f4 Mon Sep 17 00:00:00 2001
From: Xidorn Quan 
Date: Fri, 30 Dec 2016 01:58:13 +1100
Subject: [PATCH 168/229] Bug 1326209 part 1 - Make
 nsCSSRendering::DrawTableBorderSegment take nscolor for background color.
 r=dholbert

MozReview-Commit-ID: sSPtxzIf9H

--HG--
extra : rebase_source : 7d0f60f14f63ddba840037e12637ab9b56b6a6fe
---
 layout/painting/nsCSSRendering.cpp | 27 +++++++++++++--------------
 layout/painting/nsCSSRendering.h   | 22 +++++++++++-----------
 layout/tables/nsTableFrame.cpp     |  4 ++--
 3 files changed, 26 insertions(+), 27 deletions(-)

diff --git a/layout/painting/nsCSSRendering.cpp b/layout/painting/nsCSSRendering.cpp
index fb1e04e9a3ec..a81d8ba02581 100644
--- a/layout/painting/nsCSSRendering.cpp
+++ b/layout/painting/nsCSSRendering.cpp
@@ -4464,17 +4464,17 @@ GetDashInfo(nscoord  aBorderLength,
 }
 
 void
-nsCSSRendering::DrawTableBorderSegment(DrawTarget&              aDrawTarget,
-                                       uint8_t                  aBorderStyle,
-                                       nscolor                  aBorderColor,
-                                       const nsStyleBackground* aBGColor,
-                                       const nsRect&            aBorder,
-                                       int32_t                  aAppUnitsPerDevPixel,
-                                       int32_t                  aAppUnitsPerCSSPixel,
-                                       uint8_t                  aStartBevelSide,
-                                       nscoord                  aStartBevelOffset,
-                                       uint8_t                  aEndBevelSide,
-                                       nscoord                  aEndBevelOffset)
+nsCSSRendering::DrawTableBorderSegment(DrawTarget&   aDrawTarget,
+                                       uint8_t       aBorderStyle,
+                                       nscolor       aBorderColor,
+                                       nscolor       aBGColor,
+                                       const nsRect& aBorder,
+                                       int32_t       aAppUnitsPerDevPixel,
+                                       int32_t       aAppUnitsPerCSSPixel,
+                                       uint8_t       aStartBevelSide,
+                                       nscoord       aStartBevelOffset,
+                                       uint8_t       aEndBevelSide,
+                                       nscoord       aEndBevelOffset)
 {
   bool horizontal = ((eSideTop == aStartBevelSide) || (eSideBottom == aStartBevelSide));
   nscoord twipsPerPixel = NSIntPixelsToAppUnits(1, aAppUnitsPerCSSPixel);
@@ -4564,8 +4564,7 @@ nsCSSRendering::DrawTableBorderSegment(DrawTarget&              aDrawTarget,
       // FIXME: In theory, this should use the visited-dependent
       // background color, but I don't care.
       nscolor bevelColor = MakeBevelColor(ridgeGrooveSide, ridgeGroove,
-                                          aBGColor->mBackgroundColor,
-                                          aBorderColor);
+                                          aBGColor, aBorderColor);
       nsRect rect(aBorder);
       nscoord half;
       if (horizontal) { // top, bottom
@@ -4604,7 +4603,7 @@ nsCSSRendering::DrawTableBorderSegment(DrawTarget&              aDrawTarget,
       // FIXME: In theory, this should use the visited-dependent
       // background color, but I don't care.
       bevelColor = MakeBevelColor(ridgeGrooveSide, ridgeGroove,
-                                  aBGColor->mBackgroundColor, aBorderColor);
+                                  aBGColor, aBorderColor);
       if (horizontal) {
         rect.y = rect.y + half;
         rect.height = aBorder.height - half;
diff --git a/layout/painting/nsCSSRendering.h b/layout/painting/nsCSSRendering.h
index ea1347a7e250..ca40ffa16e44 100644
--- a/layout/painting/nsCSSRendering.h
+++ b/layout/painting/nsCSSRendering.h
@@ -714,17 +714,17 @@ struct nsCSSRendering {
 
   // Draw a border segment in the table collapsing border model without
   // beveling corners
-  static void DrawTableBorderSegment(DrawTarget&          aDrawTarget,
-                                     uint8_t              aBorderStyle,
-                                     nscolor              aBorderColor,
-                                     const nsStyleBackground* aBGColor,
-                                     const nsRect&        aBorderRect,
-                                     int32_t              aAppUnitsPerDevPixel,
-                                     int32_t              aAppUnitsPerCSSPixel,
-                                     uint8_t              aStartBevelSide = 0,
-                                     nscoord              aStartBevelOffset = 0,
-                                     uint8_t              aEndBevelSide = 0,
-                                     nscoord              aEndBevelOffset = 0);
+  static void DrawTableBorderSegment(DrawTarget&   aDrawTarget,
+                                     uint8_t       aBorderStyle,
+                                     nscolor       aBorderColor,
+                                     nscolor       aBGColor,
+                                     const nsRect& aBorderRect,
+                                     int32_t       aAppUnitsPerDevPixel,
+                                     int32_t       aAppUnitsPerCSSPixel,
+                                     uint8_t       aStartBevelSide = 0,
+                                     nscoord       aStartBevelOffset = 0,
+                                     uint8_t       aEndBevelSide = 0,
+                                     nscoord       aEndBevelOffset = 0);
 
   // NOTE: pt, dirtyRect, lineSize, ascent, offset in the following
   //       structs are non-rounded device pixels, not app units.
diff --git a/layout/tables/nsTableFrame.cpp b/layout/tables/nsTableFrame.cpp
index 6f98dd65e934..b223e84ea17c 100644
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -6362,7 +6362,7 @@ public:
   nsTableCellMap*       mTableCellMap;
   nsCellMap*            mCellMap;
   WritingMode           mTableWM;
-  const nsStyleBackground* mTableBgColor;
+  nscolor               mTableBgColor;
   nsTableFrame::RowGroupArray mRowGroups;
 
   nsTableRowGroupFrame* mPrevRg;
@@ -6480,7 +6480,7 @@ BCPaintBorderIterator::BCPaintBorderIterator(nsTableFrame* aTable)
 
   nsIFrame* bgFrame =
     nsCSSRendering::FindNonTransparentBackgroundFrame(aTable);
-  mTableBgColor = bgFrame->StyleBackground();
+  mTableBgColor = bgFrame->StyleBackground()->mBackgroundColor;
 }
 
 bool

From c26fcf05e4ceed83f71ca24a4d421dc5a9e10843 Mon Sep 17 00:00:00 2001
From: Xidorn Quan 
Date: Fri, 30 Dec 2016 02:03:29 +1100
Subject: [PATCH 169/229] Bug 1326209 part 2 - Change background-color to use
 complex color. r=dholbert

MozReview-Commit-ID: 1n3TC3CVY7U

--HG--
extra : rebase_source : 6b402a2493f58d114a9898a4d556587fdc98a9ee
---
 accessible/base/TextAttrs.cpp                 |  7 ++---
 accessible/html/HTMLTableAccessible.cpp       |  2 +-
 .../windows/ia2/ia2AccessibleComponent.cpp    |  5 ++--
 layout/base/nsLayoutUtils.cpp                 |  9 +++---
 layout/forms/nsListControlFrame.cpp           |  2 +-
 layout/generic/nsFrame.cpp                    |  4 +--
 layout/mathml/nsMathMLChar.cpp                |  4 +--
 layout/painting/nsCSSRendering.cpp            |  9 +++---
 layout/style/nsCSSPropList.h                  |  2 +-
 layout/style/nsComputedDOMStyle.cpp           |  2 +-
 layout/style/nsRuleNode.cpp                   | 18 +++++-------
 layout/style/nsStyleStruct.cpp                | 28 +++++++++++++++++--
 layout/style/nsStyleStruct.h                  |  9 ++++--
 .../test/test_transitions_per_property.html   |  2 +-
 layout/tables/nsTableCellFrame.cpp            | 12 ++++----
 layout/tables/nsTableFrame.cpp                |  4 +--
 widget/nsNativeTheme.cpp                      |  4 +--
 17 files changed, 74 insertions(+), 49 deletions(-)

diff --git a/accessible/base/TextAttrs.cpp b/accessible/base/TextAttrs.cpp
index 0f9e4f6feac5..cb66d1380b9c 100644
--- a/accessible/base/TextAttrs.cpp
+++ b/accessible/base/TextAttrs.cpp
@@ -374,10 +374,9 @@ bool
 TextAttrsMgr::BGColorTextAttr::
   GetColor(nsIFrame* aFrame, nscolor* aColor)
 {
-  const nsStyleBackground* styleBackground = aFrame->StyleBackground();
-
-  if (NS_GET_A(styleBackground->mBackgroundColor) > 0) {
-    *aColor = styleBackground->mBackgroundColor;
+  nscolor backgroundColor = aFrame->StyleBackground()->BackgroundColor(aFrame);
+  if (NS_GET_A(backgroundColor) > 0) {
+    *aColor = backgroundColor;
     return true;
   }
 
diff --git a/accessible/html/HTMLTableAccessible.cpp b/accessible/html/HTMLTableAccessible.cpp
index b0cdc0932dbb..c87e7bee2120 100644
--- a/accessible/html/HTMLTableAccessible.cpp
+++ b/accessible/html/HTMLTableAccessible.cpp
@@ -1075,7 +1075,7 @@ HTMLTableAccessible::IsProbablyLayoutTable()
     if (child->Role() == roles::ROW) {
       prevRowColor = rowColor;
       nsIFrame* rowFrame = child->GetFrame();
-      rowColor = rowFrame->StyleBackground()->mBackgroundColor;
+      rowColor = rowFrame->StyleBackground()->BackgroundColor(rowFrame);
 
       if (childIdx > 0 && prevRowColor != rowColor)
         RETURN_LAYOUT_ANSWER(false, "2 styles of row background color, non-bordered");
diff --git a/accessible/windows/ia2/ia2AccessibleComponent.cpp b/accessible/windows/ia2/ia2AccessibleComponent.cpp
index f32c09d1e413..7ae62f381cd8 100644
--- a/accessible/windows/ia2/ia2AccessibleComponent.cpp
+++ b/accessible/windows/ia2/ia2AccessibleComponent.cpp
@@ -117,8 +117,9 @@ ia2AccessibleComponent::get_background(IA2Color* aBackground)
     return CO_E_OBJNOTCONNECTED;
 
   nsIFrame* frame = acc->GetFrame();
-  if (frame)
-    *aBackground = frame->StyleBackground()->mBackgroundColor;
+  if (frame) {
+    *aBackground = frame->StyleBackground()->BackgroundColor(frame);
+  }
 
   return S_OK;
 
diff --git a/layout/base/nsLayoutUtils.cpp b/layout/base/nsLayoutUtils.cpp
index 32af4b76288f..911a28e0dfc3 100644
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -6851,7 +6851,7 @@ nsLayoutUtils::GetFrameTransparency(nsIFrame* aBackgroundFrame,
     return eTransparencyTransparent;
   }
   const nsStyleBackground* bg = bgSC->StyleBackground();
-  if (NS_GET_A(bg->mBackgroundColor) < 255 ||
+  if (NS_GET_A(bg->BackgroundColor(bgSC)) < 255 ||
       // bottom layer's clip is used for the color
       bg->BottomLayer().mClip != StyleGeometryBox::Border)
     return eTransparencyTransparent;
@@ -8798,8 +8798,9 @@ nsLayoutUtils::ComputeScrollMetadata(nsIFrame* aForFrame,
     } else {
       nsStyleContext* backgroundStyle;
       if (nsCSSRendering::FindBackground(aScrollFrame, &backgroundStyle)) {
-        metadata.SetBackgroundColor(Color::FromABGR(
-          backgroundStyle->StyleBackground()->mBackgroundColor));
+        nscolor backgroundColor = backgroundStyle->
+          StyleBackground()->BackgroundColor(backgroundStyle);
+        metadata.SetBackgroundColor(Color::FromABGR(backgroundColor));
       }
     }
   }
@@ -9332,4 +9333,4 @@ nsLayoutUtils::ComputeGeometryBox(nsIFrame* aFrame,
              : ComputeHTMLReferenceRect(aFrame, aGeometryBox);
 
   return r;
-}
\ No newline at end of file
+}
diff --git a/layout/forms/nsListControlFrame.cpp b/layout/forms/nsListControlFrame.cpp
index 328c9ff77dd7..b50f97ea0a64 100644
--- a/layout/forms/nsListControlFrame.cpp
+++ b/layout/forms/nsListControlFrame.cpp
@@ -1453,7 +1453,7 @@ nsListControlFrame::AboutToDropDown()
   mLastDropdownBackstopColor = NS_RGBA(0,0,0,0);
   while (NS_GET_A(mLastDropdownBackstopColor) < 255 && context) {
     mLastDropdownBackstopColor =
-      NS_ComposeColors(context->StyleBackground()->mBackgroundColor,
+      NS_ComposeColors(context->StyleBackground()->BackgroundColor(context),
                        mLastDropdownBackstopColor);
     context = context->GetParent();
   }
diff --git a/layout/generic/nsFrame.cpp b/layout/generic/nsFrame.cpp
index 78ac40a6108b..8eb07ed8ebbc 100644
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -1894,7 +1894,7 @@ nsFrame::DisplayBackgroundUnconditional(nsDisplayListBuilder* aBuilder,
   // receive a propagated background should just set aForceBackground to
   // true.
   if (aBuilder->IsForEventDelivery() || aForceBackground ||
-      !StyleBackground()->IsTransparent() || StyleDisplay()->mAppearance) {
+      !StyleBackground()->IsTransparent(this) || StyleDisplay()->mAppearance) {
     return nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
         aBuilder, this, GetRectRelativeToSelf(), aLists.BorderBackground());
   }
@@ -5436,7 +5436,7 @@ nsRect
 nsFrame::ComputeSimpleTightBounds(DrawTarget* aDrawTarget) const
 {
   if (StyleOutline()->mOutlineStyle != NS_STYLE_BORDER_STYLE_NONE ||
-      StyleBorder()->HasBorder() || !StyleBackground()->IsTransparent() ||
+      StyleBorder()->HasBorder() || !StyleBackground()->IsTransparent(this) ||
       StyleDisplay()->mAppearance) {
     // Not necessarily tight, due to clipping, negative
     // outline-offset, and lots of other issues, but that's OK
diff --git a/layout/mathml/nsMathMLChar.cpp b/layout/mathml/nsMathMLChar.cpp
index e73dba0627b6..32e6b4311cad 100644
--- a/layout/mathml/nsMathMLChar.cpp
+++ b/layout/mathml/nsMathMLChar.cpp
@@ -1986,9 +1986,9 @@ nsMathMLChar::Display(nsDisplayListBuilder*   aBuilder,
       nsDisplayMathMLSelectionRect(aBuilder, aForFrame, *aSelectedRect));
   }
   else if (mRect.width && mRect.height) {
-    const nsStyleBackground* backg = styleContext->StyleBackground();
     if (styleContext != parentContext &&
-        NS_GET_A(backg->mBackgroundColor) > 0) {
+        NS_GET_A(styleContext->StyleBackground()->
+                 BackgroundColor(styleContext)) > 0) {
       nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
         aBuilder, aForFrame, mRect, aLists.BorderBackground(),
         /* aAllowWillPaintBorderOptimization */ true, styleContext);
diff --git a/layout/painting/nsCSSRendering.cpp b/layout/painting/nsCSSRendering.cpp
index a81d8ba02581..9b9a5d37c7bf 100644
--- a/layout/painting/nsCSSRendering.cpp
+++ b/layout/painting/nsCSSRendering.cpp
@@ -1192,8 +1192,9 @@ nsCSSRendering::FindNonTransparentBackgroundFrame(nsIFrame* aFrame,
   while (frame) {
     // No need to call GetVisitedDependentColor because it always uses
     // this alpha component anyway.
-    if (NS_GET_A(frame->StyleBackground()->mBackgroundColor) > 0)
+    if (NS_GET_A(frame->StyleBackground()->BackgroundColor(frame)) > 0) {
       break;
+    }
 
     if (frame->IsThemed())
       break;
@@ -1227,7 +1228,7 @@ nsCSSRendering::FindBackgroundStyleFrame(nsIFrame* aForFrame)
   const nsStyleBackground* result = aForFrame->StyleBackground();
 
   // Check if we need to do propagation from BODY rather than HTML.
-  if (!result->IsTransparent()) {
+  if (!result->IsTransparent(aForFrame)) {
     return aForFrame;
   }
 
@@ -1333,7 +1334,7 @@ FindElementBackground(nsIFrame* aForFrame, nsIFrame* aRootElementFrame,
     return true;
 
   const nsStyleBackground* htmlBG = aRootElementFrame->StyleBackground();
-  return !htmlBG->IsTransparent();
+  return !htmlBG->IsTransparent(aRootElementFrame);
 }
 
 bool
@@ -2249,7 +2250,7 @@ nsCSSRendering::DetermineBackgroundColor(nsPresContext* aPresContext,
     // transparent, but we are expected to use white instead of whatever
     // color was specified.
     bgColor = NS_RGB(255, 255, 255);
-    if (aDrawBackgroundImage || !bg->IsTransparent()) {
+    if (aDrawBackgroundImage || !bg->IsTransparent(aStyleContext)) {
       aDrawBackgroundColor = true;
     } else {
       bgColor = NS_RGBA(0,0,0,0);
diff --git a/layout/style/nsCSSPropList.h b/layout/style/nsCSSPropList.h
index e9a490c848ea..b0fc2d7e741d 100644
--- a/layout/style/nsCSSPropList.h
+++ b/layout/style/nsCSSPropList.h
@@ -538,7 +538,7 @@ CSS_PROP_BACKGROUND(
     VARIANT_HC,
     nullptr,
     offsetof(nsStyleBackground, mBackgroundColor),
-    eStyleAnimType_Color)
+    eStyleAnimType_ComplexColor)
 CSS_PROP_BACKGROUND(
     background-image,
     background_image,
diff --git a/layout/style/nsComputedDOMStyle.cpp b/layout/style/nsComputedDOMStyle.cpp
index 8301d0831406..68ae144a590e 100644
--- a/layout/style/nsComputedDOMStyle.cpp
+++ b/layout/style/nsComputedDOMStyle.cpp
@@ -1870,7 +1870,7 @@ already_AddRefed
 nsComputedDOMStyle::DoGetBackgroundColor()
 {
   RefPtr val = new nsROCSSPrimitiveValue;
-  SetToRGBAColor(val, StyleBackground()->mBackgroundColor);
+  SetValueFromComplexColor(val, StyleBackground()->mBackgroundColor);
   return val.forget();
 }
 
diff --git a/layout/style/nsRuleNode.cpp b/layout/style/nsRuleNode.cpp
index 29added60f39..27f96b74930e 100644
--- a/layout/style/nsRuleNode.cpp
+++ b/layout/style/nsRuleNode.cpp
@@ -7417,17 +7417,13 @@ nsRuleNode::ComputeBackgroundData(void* aStartStruct,
 {
   COMPUTE_START_RESET(Background, bg, parentBG)
 
-  // background-color: color, string, inherit
-  const nsCSSValue* backColorValue = aRuleData->ValueForBackgroundColor();
-  if (eCSSUnit_Initial == backColorValue->GetUnit() ||
-      eCSSUnit_Unset == backColorValue->GetUnit()) {
-    bg->mBackgroundColor = NS_RGBA(0, 0, 0, 0);
-  } else if (!SetColor(*backColorValue, parentBG->mBackgroundColor,
-                       mPresContext, aContext, bg->mBackgroundColor,
-                       conditions)) {
-    NS_ASSERTION(eCSSUnit_Null == backColorValue->GetUnit(),
-                 "unexpected color unit");
-  }
+  // background-color: color, inherit
+  SetComplexColor(*aRuleData->ValueForBackgroundColor(),
+                                 parentBG->mBackgroundColor,
+                                 StyleComplexColor::FromColor(
+                                     NS_RGBA(0, 0, 0, 0)),
+                                 mPresContext,
+                                 bg->mBackgroundColor, conditions);
 
   uint32_t maxItemCount = 1;
   bool rebuild = false;
diff --git a/layout/style/nsStyleStruct.cpp b/layout/style/nsStyleStruct.cpp
index 736a6dd0f46e..efa311449edf 100644
--- a/layout/style/nsStyleStruct.cpp
+++ b/layout/style/nsStyleStruct.cpp
@@ -2881,7 +2881,7 @@ nsStyleImageLayers::Layer::CalcDifference(const nsStyleImageLayers::Layer& aNewL
 
 nsStyleBackground::nsStyleBackground(StyleStructContext aContext)
   : mImage(nsStyleImageLayers::LayerType::Background)
-  , mBackgroundColor(NS_RGBA(0, 0, 0, 0))
+  , mBackgroundColor(StyleComplexColor::FromColor(NS_RGBA(0, 0, 0, 0)))
 {
   MOZ_COUNT_CTOR(nsStyleBackground);
 }
@@ -2943,12 +2943,34 @@ nsStyleBackground::HasFixedBackground(nsIFrame* aFrame) const
   return false;
 }
 
+nscolor
+nsStyleBackground::BackgroundColor(const nsIFrame* aFrame) const
+{
+  return BackgroundColor(aFrame->StyleContext());
+}
+
+nscolor
+nsStyleBackground::BackgroundColor(nsStyleContext* aContext) const
+{
+  // In majority of cases, background-color should just be a numeric color.
+  // In that case, we can skip resolving StyleColor().
+  return mBackgroundColor.IsNumericColor()
+    ? mBackgroundColor.mColor
+    : aContext->StyleColor()->CalcComplexColor(mBackgroundColor);
+}
+
 bool
-nsStyleBackground::IsTransparent() const
+nsStyleBackground::IsTransparent(const nsIFrame* aFrame) const
+{
+  return IsTransparent(aFrame->StyleContext());
+}
+
+bool
+nsStyleBackground::IsTransparent(nsStyleContext* aContext) const
 {
   return BottomLayer().mImage.IsEmpty() &&
          mImage.mImageCount == 1 &&
-         NS_GET_A(mBackgroundColor) == 0;
+         NS_GET_A(BackgroundColor(aContext)) == 0;
 }
 
 void
diff --git a/layout/style/nsStyleStruct.h b/layout/style/nsStyleStruct.h
index 7af150538c0c..14acea25f316 100644
--- a/layout/style/nsStyleStruct.h
+++ b/layout/style/nsStyleStruct.h
@@ -942,8 +942,13 @@ struct MOZ_NEEDS_MEMMOVABLE_MEMBERS nsStyleBackground {
     return nsChangeHint(0);
   }
 
+  // Return the background color as nscolor.
+  nscolor BackgroundColor(const nsIFrame* aFrame) const;
+  nscolor BackgroundColor(nsStyleContext* aContext) const;
+
   // True if this background is completely transparent.
-  bool IsTransparent() const;
+  bool IsTransparent(const nsIFrame* aFrame) const;
+  bool IsTransparent(nsStyleContext* aContext) const;
 
   // We have to take slower codepaths for fixed background attachment,
   // but we don't want to do that when there's no image.
@@ -958,7 +963,7 @@ struct MOZ_NEEDS_MEMMOVABLE_MEMBERS nsStyleBackground {
   const nsStyleImageLayers::Layer& BottomLayer() const { return mImage.BottomLayer(); }
 
   nsStyleImageLayers mImage;
-  nscolor mBackgroundColor;       // [reset]
+  mozilla::StyleComplexColor mBackgroundColor;       // [reset]
 };
 
 #define NS_SPACING_MARGIN   0
diff --git a/layout/style/test/test_transitions_per_property.html b/layout/style/test/test_transitions_per_property.html
index b854c60a9c65..a72358b8be78 100644
--- a/layout/style/test/test_transitions_per_property.html
+++ b/layout/style/test/test_transitions_per_property.html
@@ -83,7 +83,7 @@ var supported_properties = {
     "-moz-outline-radius-topleft": [ test_radius_transition ],
     "-moz-outline-radius-topright": [ test_radius_transition ],
     "background-color": [ test_color_transition,
-                          test_currentcolor_transition ],
+                          test_true_currentcolor_transition ],
     "background-position": [ test_background_position_transition,
                              // FIXME: We don't currently test clamping,
                              // since background-position uses calc() as
diff --git a/layout/tables/nsTableCellFrame.cpp b/layout/tables/nsTableCellFrame.cpp
index ee95a30ce1f6..fe9a4a699ab5 100644
--- a/layout/tables/nsTableCellFrame.cpp
+++ b/layout/tables/nsTableCellFrame.cpp
@@ -320,11 +320,10 @@ nsTableCellFrame::DecorateForSelection(DrawTarget* aDrawTarget, nsPoint aPt)
           LookAndFeel::GetColor(LookAndFeel::eColorID_TextSelectBackground);
       }
       nscoord threePx = nsPresContext::CSSPixelsToAppUnits(3);
-      if ((mRect.width > threePx) && (mRect.height > threePx))
-      {
-        //compare bordercolor to ((nsStyleColor *)myColor)->mBackgroundColor)
-        bordercolor = EnsureDifferentColors(bordercolor,
-                                            StyleBackground()->mBackgroundColor);
+      if ((mRect.width > threePx) && (mRect.height > threePx)) {
+        //compare bordercolor to background-color
+        bordercolor = EnsureDifferentColors(
+          bordercolor, StyleBackground()->BackgroundColor(this));
 
         int32_t appUnitsPerDevPixel = PresContext()->AppUnitsPerDevPixel();
         Point devPixelOffset = NSPointToPoint(aPt, appUnitsPerDevPixel);
@@ -501,7 +500,8 @@ nsTableCellFrame::BuildDisplayList(nsDisplayListBuilder*   aBuilder,
     
       // display background if we need to.
       if (aBuilder->IsForEventDelivery() ||
-          !StyleBackground()->IsTransparent() || StyleDisplay()->mAppearance) {
+          !StyleBackground()->IsTransparent(this) ||
+          StyleDisplay()->mAppearance) {
         if (!tableFrame->IsBorderCollapse() ||
             aBuilder->IsAtRootOfPseudoStackingContext() ||
             aBuilder->IsForEventDelivery()) {
diff --git a/layout/tables/nsTableFrame.cpp b/layout/tables/nsTableFrame.cpp
index b223e84ea17c..296c9a7ae634 100644
--- a/layout/tables/nsTableFrame.cpp
+++ b/layout/tables/nsTableFrame.cpp
@@ -1285,7 +1285,7 @@ static inline bool FrameHasBorderOrBackground(nsTableFrame* tableFrame, nsIFrame
   if (f->StyleBorder()->HasBorder()) {
     return true;
   }
-  if (!f->StyleBackground()->IsTransparent() ||
+  if (!f->StyleBackground()->IsTransparent(f) ||
       f->StyleDisplay()->mAppearance) {
     
     nsTableCellFrame *cellFrame = do_QueryFrame(f);
@@ -6480,7 +6480,7 @@ BCPaintBorderIterator::BCPaintBorderIterator(nsTableFrame* aTable)
 
   nsIFrame* bgFrame =
     nsCSSRendering::FindNonTransparentBackgroundFrame(aTable);
-  mTableBgColor = bgFrame->StyleBackground()->mBackgroundColor;
+  mTableBgColor = bgFrame->StyleBackground()->BackgroundColor(bgFrame);
 }
 
 bool
diff --git a/widget/nsNativeTheme.cpp b/widget/nsNativeTheme.cpp
index a5bd85fafa7b..66e91d34a4f9 100644
--- a/widget/nsNativeTheme.cpp
+++ b/widget/nsNativeTheme.cpp
@@ -759,12 +759,12 @@ nsNativeTheme::IsDarkBackground(nsIFrame* aFrame)
   }
   nsStyleContext* bgSC = nullptr;
   if (!nsCSSRendering::FindBackground(frame, &bgSC) ||
-      bgSC->StyleBackground()->IsTransparent()) {
+      bgSC->StyleBackground()->IsTransparent(bgSC)) {
     nsIFrame* backgroundFrame = nsCSSRendering::FindNonTransparentBackgroundFrame(frame, true);
     nsCSSRendering::FindBackground(backgroundFrame, &bgSC);
   }
   if (bgSC) {
-    nscolor bgColor = bgSC->StyleBackground()->mBackgroundColor;
+    nscolor bgColor = bgSC->StyleBackground()->BackgroundColor(bgSC);
     // Consider the background color dark if the sum of the r, g and b values is
     // less than 384 in a semi-transparent document.  This heuristic matches what
     // WebKit does, and we can improve it later if needed.

From df4d42fabbf5c6d3819797a951919e8dff14e20d Mon Sep 17 00:00:00 2001
From: Andreas Pehrson 
Date: Thu, 29 Dec 2016 19:05:39 +0100
Subject: [PATCH 170/229] Bug 1326386 - Restore test_gUM_active_autoplay.html.
 r=jesup

MozReview-Commit-ID: HKNgBRENrcY

--HG--
extra : rebase_source : ea1803f832b586e0bf10e3a9fbec96a0f0410bf2
---
 dom/media/tests/mochitest/mochitest.ini | 1 +
 1 file changed, 1 insertion(+)

diff --git a/dom/media/tests/mochitest/mochitest.ini b/dom/media/tests/mochitest/mochitest.ini
index 6ac08f95fddd..cc001b167923 100644
--- a/dom/media/tests/mochitest/mochitest.ini
+++ b/dom/media/tests/mochitest/mochitest.ini
@@ -40,6 +40,7 @@ skip-if = android_version == '18' # android(Bug 1189784, timeouts on 4.3 emulato
 [test_enumerateDevices.html]
 [test_ondevicechange.html]
 skip-if = os == 'android'
+[test_getUserMedia_active_autoplay.html]
 [test_getUserMedia_audioCapture.html]
 skip-if = android_version == '18' # android(Bug 1189784, timeouts on 4.3 emulator)
 [test_getUserMedia_addTrackRemoveTrack.html]

From df5d3987d6ba3416b0e31e2cb38acbe143cc48ce Mon Sep 17 00:00:00 2001
From: Michael Froman 
Date: Fri, 30 Dec 2016 13:29:51 -0600
Subject: [PATCH 171/229] Bug 1325991 - sections with bundle-only should have
 port set to 0. r=drno,jesup

MozReview-Commit-ID: 6O7X1MWZhZI

--HG--
extra : rebase_source : 4787f4b354900882f1bbd4f47757ff77dfa74324
---
 .../signaling/gtest/jsep_session_unittest.cpp | 37 ++++++++++++-------
 .../signaling/src/jsep/JsepSessionImpl.cpp    |  2 +
 media/webrtc/signaling/src/sdp/SdpHelper.cpp  |  9 ++++-
 3 files changed, 33 insertions(+), 15 deletions(-)

diff --git a/media/webrtc/signaling/gtest/jsep_session_unittest.cpp b/media/webrtc/signaling/gtest/jsep_session_unittest.cpp
index f2f7aad7c49f..cb5060edb23b 100644
--- a/media/webrtc/signaling/gtest/jsep_session_unittest.cpp
+++ b/media/webrtc/signaling/gtest/jsep_session_unittest.cpp
@@ -824,21 +824,26 @@ protected:
                                     size_t transportLevel,
                                     const std::string& context) const
       {
+        Address expectedAddress = "0.0.0.0";
+        Port expectedPort = 9U;
+
         if (expectDefault) {
           // Copy so we can be terse and use []
           auto defaultCandidates = mDefaultCandidates;
-          ASSERT_EQ(defaultCandidates[transportLevel][RTP].first,
-                    msection.GetConnection().GetAddress())
-            << context << " (level " << msection.GetLevel() << ")";
-          ASSERT_EQ(defaultCandidates[transportLevel][RTP].second,
-                    msection.GetPort())
-            << context << " (level " << msection.GetLevel() << ")";
-        } else {
-          ASSERT_EQ("0.0.0.0", msection.GetConnection().GetAddress())
-            << context << " (level " << msection.GetLevel() << ")";
-          ASSERT_EQ(9U, msection.GetPort())
-            << context << " (level " << msection.GetLevel() << ")";
+          expectedAddress = defaultCandidates[transportLevel][RTP].first;
+          expectedPort = defaultCandidates[transportLevel][RTP].second;
         }
+
+        // if bundle-only attribute is present, expect port 0
+        const SdpAttributeList& attrs = msection.GetAttributeList();
+        if (attrs.HasAttribute(SdpAttribute::kBundleOnlyAttribute)) {
+          expectedPort = 0U;
+        }
+
+        ASSERT_EQ(expectedAddress, msection.GetConnection().GetAddress())
+          << context << " (level " << msection.GetLevel() << ")";
+        ASSERT_EQ(expectedPort, msection.GetPort())
+          << context << " (level " << msection.GetLevel() << ")";
       }
 
       void CheckDefaultRtcpCandidate(bool expectDefault,
@@ -1074,11 +1079,15 @@ private:
         ASSERT_EQ(SdpMediaSection::kUdpTlsRtpSavpf, msection.GetProtocol());
       }
 
-      if (msection.GetPort() == 0) {
+      const SdpAttributeList& attrs = msection.GetAttributeList();
+      bool bundle_only = attrs.HasAttribute(SdpAttribute::kBundleOnlyAttribute);
+
+      // port 0 only means disabled when the bundle-only attribute is missing
+      if (!bundle_only && msection.GetPort() == 0) {
         ValidateDisabledMSection(&msection);
         continue;
       }
-      const SdpAttributeList& attrs = msection.GetAttributeList();
+
       ASSERT_EQ(source.mIceUfrag, attrs.GetIceUfrag());
       ASSERT_EQ(source.mIcePwd, attrs.GetIcePwd());
       const SdpFingerprintAttributeList& fps = attrs.GetFingerprint();
@@ -4152,10 +4161,12 @@ TEST_P(JsepSessionTest, TestMaxBundle)
   ASSERT_FALSE(
       parsedOffer->GetMediaSection(0).GetAttributeList().HasAttribute(
         SdpAttribute::kBundleOnlyAttribute));
+  ASSERT_NE(0U, parsedOffer->GetMediaSection(0).GetPort());
   for (size_t i = 1; i < parsedOffer->GetMediaSectionCount(); ++i) {
     ASSERT_TRUE(
         parsedOffer->GetMediaSection(i).GetAttributeList().HasAttribute(
           SdpAttribute::kBundleOnlyAttribute));
+    ASSERT_EQ(0U, parsedOffer->GetMediaSection(i).GetPort());
   }
 
 
diff --git a/media/webrtc/signaling/src/jsep/JsepSessionImpl.cpp b/media/webrtc/signaling/src/jsep/JsepSessionImpl.cpp
index 5375110b60ed..0a6565edabee 100644
--- a/media/webrtc/signaling/src/jsep/JsepSessionImpl.cpp
+++ b/media/webrtc/signaling/src/jsep/JsepSessionImpl.cpp
@@ -666,6 +666,8 @@ JsepSessionImpl::SetupBundle(Sdp* sdp) const
       if (useBundleOnly) {
         attrs.SetAttribute(
             new SdpFlagAttribute(SdpAttribute::kBundleOnlyAttribute));
+        // Set port to 0 for sections with bundle-only attribute. (mjf)
+        sdp->GetMediaSection(i).SetPort(0);
       }
 
       mids.push_back(attrs.GetMid());
diff --git a/media/webrtc/signaling/src/sdp/SdpHelper.cpp b/media/webrtc/signaling/src/sdp/SdpHelper.cpp
index e476b29e526b..a06e3a769307 100644
--- a/media/webrtc/signaling/src/sdp/SdpHelper.cpp
+++ b/media/webrtc/signaling/src/sdp/SdpHelper.cpp
@@ -424,14 +424,19 @@ SdpHelper::SetDefaultAddresses(const std::string& defaultCandidateAddr,
                                SdpMediaSection* msection)
 {
   msection->GetConnection().SetAddress(defaultCandidateAddr);
-  msection->SetPort(defaultCandidatePort);
+  SdpAttributeList& attrList = msection->GetAttributeList();
+
+  // only set the port if there is no bundle-only attribute
+  if (!attrList.HasAttribute(SdpAttribute::kBundleOnlyAttribute)) {
+    msection->SetPort(defaultCandidatePort);
+  }
 
   if (!defaultRtcpCandidateAddr.empty()) {
     sdp::AddrType ipVersion = sdp::kIPv4;
     if (defaultRtcpCandidateAddr.find(':') != std::string::npos) {
       ipVersion = sdp::kIPv6;
     }
-    msection->GetAttributeList().SetAttribute(new SdpRtcpAttribute(
+    attrList.SetAttribute(new SdpRtcpAttribute(
           defaultRtcpCandidatePort,
           sdp::kInternet,
           ipVersion,

From ccf62e01619445e83f707cfa9f36ea4dbf57294b Mon Sep 17 00:00:00 2001
From: cku 
Date: Fri, 30 Dec 2016 02:07:04 +0800
Subject: [PATCH 172/229] Bug 1324174 - Simplify context management logic in
 nsSVGIntegrationUtils::PaintMask. r=mstange

MozReview-Commit-ID: BwPSFlfqN8e

--HG--
extra : rebase_source : b16bad5f5baee1a469237b72ea6a23c341ebdb25
---
 layout/svg/nsSVGIntegrationUtils.cpp | 34 +++++++++++-----------------
 1 file changed, 13 insertions(+), 21 deletions(-)

diff --git a/layout/svg/nsSVGIntegrationUtils.cpp b/layout/svg/nsSVGIntegrationUtils.cpp
index 514c45d37a4e..215cc38ac2fc 100644
--- a/layout/svg/nsSVGIntegrationUtils.cpp
+++ b/layout/svg/nsSVGIntegrationUtils.cpp
@@ -750,9 +750,9 @@ nsSVGIntegrationUtils::PaintMask(const PaintFramesParams& aParams)
     return DrawResult::SUCCESS;
   }
 
-  if (maskUsage.opacity == 0.0f) {
-    return DrawResult::SUCCESS;
-  }
+  // XXX Bug 1323912.
+  MOZ_ASSERT(maskUsage.opacity == 1.0,
+             "nsSVGIntegrationUtils::PaintMask can not handle opacity now.");
 
   gfxContext& ctx = aParams.ctx;
   nsIFrame* firstFrame =
@@ -761,10 +761,7 @@ nsSVGIntegrationUtils::PaintMask(const PaintFramesParams& aParams)
     nsSVGEffects::GetEffectProperties(firstFrame);
 
   DrawResult result = DrawResult::SUCCESS;
-  nsPoint offsetToBoundingBox;
-  nsPoint offsetToUserSpace;
-  gfxContextMatrixAutoSaveRestore matSR;
-    RefPtr maskTarget = ctx.GetDrawTarget();
+  RefPtr maskTarget = ctx.GetDrawTarget();
 
   if (maskUsage.shouldGenerateMaskLayer &&
       maskUsage.shouldGenerateClipMaskLayer) {
@@ -778,19 +775,25 @@ nsSVGIntegrationUtils::PaintMask(const PaintFramesParams& aParams)
                                                      SurfaceFormat::A8);
   }
 
+  gfxContextMatrixAutoSaveRestore matSR;
+  nsPoint offsetToBoundingBox;
+  nsPoint offsetToUserSpace;
+
+  // Paint clip-path-basic-shape onto ctx
+  gfxContextAutoSaveRestore basicShapeSR;
   if (maskUsage.shouldApplyBasicShape) {
     matSR.SetContext(&ctx);
 
     SetupContextMatrix(firstFrame, aParams, offsetToBoundingBox,
                        offsetToUserSpace);
 
+    basicShapeSR.SetContext(&ctx);
     nsCSSClipPathInstance::ApplyBasicShapeClip(ctx, frame);
     if (!maskUsage.shouldGenerateMaskLayer) {
       // Only have basic-shape clip-path effect. Fill clipped region by
       // opaque white.
-      ctx.SetColor(Color(0.0, 0.0, 0.0, 1.0));
+      ctx.SetColor(Color(1.0, 1.0, 1.0, 1.0));
       ctx.Fill();
-      ctx.PopClip();
 
       return result;
     }
@@ -804,26 +807,15 @@ nsSVGIntegrationUtils::PaintMask(const PaintFramesParams& aParams)
     SetupContextMatrix(frame, aParams, offsetToBoundingBox,
                        offsetToUserSpace);
     nsTArray maskFrames = effectProperties.GetMaskFrames();
-    // XXX Bug 1323912.
-    MOZ_ASSERT(maskUsage.opacity == 1.0,
-               "nsSVGIntegrationUtils::PaintMask can not handle opacity now.");
+
     result = PaintMaskSurface(aParams, maskTarget, 1.0,
                               firstFrame->StyleContext(), maskFrames,
                               ctx.CurrentMatrix(), offsetToUserSpace);
     if (result != DrawResult::SUCCESS) {
-      if (maskUsage.shouldApplyBasicShape) {
-        ctx.PopClip();
-      }
-
       return result;
     }
   }
 
-  if (maskUsage.shouldApplyBasicShape) {
-    ctx.PopClip();
-    return result;
-  }
-
   // Paint clip-path onto ctx.
   if (maskUsage.shouldGenerateClipMaskLayer || maskUsage.shouldApplyClipPath) {
     matSR.Restore();

From 7d79da08f4abf28515d12539f6db64007341384f Mon Sep 17 00:00:00 2001
From: Chih-Yi Leu 
Date: Thu, 29 Dec 2016 15:00:00 -0500
Subject: [PATCH 173/229] Bug 1324592 - Use nsITimer to trigger DirectInput
 polling instead of DelayedDispatch. r=qdot

---
 dom/gamepad/windows/WindowsGamepad.cpp | 60 +++++++++++++++-----------
 1 file changed, 34 insertions(+), 26 deletions(-)

diff --git a/dom/gamepad/windows/WindowsGamepad.cpp b/dom/gamepad/windows/WindowsGamepad.cpp
index 5f60fd0b79d8..9f2c30654024 100644
--- a/dom/gamepad/windows/WindowsGamepad.cpp
+++ b/dom/gamepad/windows/WindowsGamepad.cpp
@@ -329,11 +329,31 @@ private:
   HMODULE mModule;
 };
 
+HWND sHWnd = nullptr;
+
+static void
+DirectInputMessageLoopOnceCallback(nsITimer *aTimer, void* aClosure)
+{
+  MOZ_ASSERT(NS_GetCurrentThread() == gMonitorThread);
+  MSG msg;
+  while (PeekMessageW(&msg, sHWnd, 0, 0, PM_REMOVE) > 0) {
+    TranslateMessage(&msg);
+    DispatchMessage(&msg);
+  }
+  aTimer->Cancel();
+  if (!sIsShutdown) {
+    aTimer->InitWithFuncCallback(DirectInputMessageLoopOnceCallback,
+                                 nullptr, kWindowsGamepadPollInterval,
+                                 nsITimer::TYPE_ONE_SHOT);
+  }
+}
+
 class WindowsGamepadService
 {
  public:
   WindowsGamepadService()
   {
+    mDirectInputTimer = do_CreateInstance("@mozilla.org/timer;1");
     mXInputTimer = do_CreateInstance("@mozilla.org/timer;1");
     mDeviceChangeTimer = do_CreateInstance("@mozilla.org/timer;1");
   }
@@ -343,6 +363,15 @@ class WindowsGamepadService
   }
 
   void DevicesChanged(bool aIsStablizing);
+
+  void StartMessageLoop()
+  {
+    MOZ_ASSERT(mDirectInputTimer);
+    mDirectInputTimer->InitWithFuncCallback(DirectInputMessageLoopOnceCallback,
+                                            nullptr, kWindowsGamepadPollInterval,
+                                            nsITimer::TYPE_ONE_SHOT);
+  }
+
   void Startup();
   void Shutdown();
   // Parse gamepad input from a WM_INPUT message.
@@ -373,6 +402,7 @@ class WindowsGamepadService
   HIDLoader mHID;
   XInputLoader mXInput;
 
+  nsCOMPtr mDirectInputTimer;
   nsCOMPtr mXInputTimer;
   nsCOMPtr mDeviceChangeTimer;
 };
@@ -892,6 +922,9 @@ void
 WindowsGamepadService::Cleanup()
 {
   mIsXInputMonitoring = false;
+  if (mDirectInputTimer) {
+    mDirectInputTimer->Cancel();
+  }
   if (mXInputTimer) {
     mXInputTimer->Cancel();
   }
@@ -914,8 +947,6 @@ WindowsGamepadService::DevicesChanged(bool aIsStablizing)
   }
 }
 
-HWND sHWnd = nullptr;
-
 bool
 RegisterRawInput(HWND hwnd, bool enable)
 {
@@ -964,29 +995,6 @@ GamepadWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
   return DefWindowProc(hwnd, msg, wParam, lParam);
 }
 
-class WindowGamepadMessageLoopOnceRunnable final : public Runnable
-{
-public:
-  WindowGamepadMessageLoopOnceRunnable() {}
-  NS_IMETHOD Run() override
-  {
-    MOZ_ASSERT(NS_GetCurrentThread() == gMonitorThread);
-    MSG msg;
-    while (PeekMessageW(&msg, sHWnd, 0, 0, PM_REMOVE) > 0) {
-      TranslateMessage(&msg);
-      DispatchMessage(&msg);
-    }
-    if (!sIsShutdown) {
-      nsCOMPtr runnable = new WindowGamepadMessageLoopOnceRunnable();
-      NS_DelayedDispatchToCurrentThread(runnable.forget(),
-                                        kWindowsGamepadPollInterval);
-    }
-    return NS_OK;
-  }
-private:
-  ~WindowGamepadMessageLoopOnceRunnable() {}
-};
-
 class StartWindowsGamepadServiceRunnable final : public Runnable
 {
 public:
@@ -1017,7 +1025,7 @@ public:
     }
 
     // Explicitly start the message loop
-    NS_DispatchToCurrentThread(new WindowGamepadMessageLoopOnceRunnable());
+    gService->StartMessageLoop();
 
     return NS_OK;
   }

From 4e5007c1c2b34e9052fd035f0d74952a2e96daf0 Mon Sep 17 00:00:00 2001
From: Andreas Pehrson 
Date: Fri, 30 Dec 2016 10:56:49 +0100
Subject: [PATCH 174/229] Bug 1314886 - Call mozCaptureStream() after
 "loadedmetadata" in test_streams_element_capture_reset. r=jwwang

MozReview-Commit-ID: 1i5VIfCWWRy

--HG--
extra : rebase_source : 00e78dc0214557bd53b773e918a56de8a56e9682
---
 .../test_streams_element_capture_reset.html   | 24 ++++++++++++-------
 1 file changed, 16 insertions(+), 8 deletions(-)

diff --git a/dom/media/test/test_streams_element_capture_reset.html b/dom/media/test/test_streams_element_capture_reset.html
index 1290e4618b0f..888c3bec9d2d 100644
--- a/dom/media/test/test_streams_element_capture_reset.html
+++ b/dom/media/test/test_streams_element_capture_reset.html
@@ -17,8 +17,6 @@ SimpleTest.waitForExplicitFinish();
 var v = document.getElementById('v');
 var vout = document.getElementById('vout');
 var vout_untilended = document.getElementById('vout_untilended');
-vout.srcObject = v.mozCaptureStream();
-vout_untilended.srcObject = v.mozCaptureStreamUntilEnded();
 
 function dumpEvent(event) {
   var v = event.target;
@@ -101,17 +99,27 @@ function startTest(test) {
   v.addEventListener("ended", ended, false);
   vout_untilended.addEventListener("ended", ended, false);
 
-  v.src = test.name;
-  v.name = test.name;
-  v.play();
-
   function checkNoEnded() {
     ok(false, "ended event received unexpectedly");
   };
 
   vout.addEventListener("ended", checkNoEnded, false);
-  vout.play();
-  vout_untilended.play();
+
+  v.src = test.name;
+  v.name = test.name;
+  v.preload = "metadata";
+
+  function loadedmetadata() {
+    vout.srcObject = v.mozCaptureStream();
+    vout.play();
+
+    vout_untilended.srcObject = v.mozCaptureStreamUntilEnded();
+    vout_untilended.play();
+
+    v.play();
+  };
+
+  v.addEventListener("loadedmetadata", loadedmetadata, {once: true});
 }
 
 var testVideo = getPlayableVideo(gSmallTests);

From a8ed5ef06daa604801685a37f14cd78480d84a6d Mon Sep 17 00:00:00 2001
From: Sebastian Hengst 
Date: Fri, 30 Dec 2016 11:21:24 +0100
Subject: [PATCH 175/229] Bug 1326058 - icon and color should be in center of
 focus ring in container preferences dialog. r=jkt

---
 browser/components/preferences/containers.js     |  3 ++-
 browser/themes/shared/preferences/containers.css | 14 +++++++++-----
 2 files changed, 11 insertions(+), 6 deletions(-)

diff --git a/browser/components/preferences/containers.js b/browser/components/preferences/containers.js
index 6ca5853f7f82..d60ad4893c8a 100644
--- a/browser/components/preferences/containers.js
+++ b/browser/components/preferences/containers.js
@@ -89,7 +89,7 @@ let gContainersManager = {
   createIconButtons(defaultIcon) {
     let radiogroup = document.createElement("radiogroup");
     radiogroup.setAttribute("id", "icon");
-    radiogroup.className = "icon-buttons";
+    radiogroup.className = "icon-buttons radio-buttons";
 
     for (let icon of this.icons) {
       let iconSwatch = document.createElement("radio");
@@ -118,6 +118,7 @@ let gContainersManager = {
   createColorSwatches(defaultColor) {
     let radiogroup = document.createElement("radiogroup");
     radiogroup.setAttribute("id", "color");
+    radiogroup.className = "radio-buttons";
 
     for (let color of this.colors) {
       let colorSwatch = document.createElement("radio");
diff --git a/browser/themes/shared/preferences/containers.css b/browser/themes/shared/preferences/containers.css
index 3fb965331631..b7a372a4b4e7 100644
--- a/browser/themes/shared/preferences/containers.css
+++ b/browser/themes/shared/preferences/containers.css
@@ -10,12 +10,12 @@
   --preference-active-color: #858585;
 }
 
-radiogroup {
+.radio-buttons {
   display: flex;
   margin-inline-start: 0.35rem;
 }
 
-radio {
+.radio-buttons > radio {
   flex: auto;
   display: flex;
   align-items: center;
@@ -35,19 +35,23 @@ radio {
   fill: #4d4d4d;
 }
 
+.radio-buttons > radio {
+  padding-inline-start: 2px;
+}
+
 radio > [data-identity-icon] {
   inline-size: 22px;
   block-size: 22px;
 }
 
-radio[selected=true] {
+.radio-buttons > radio[selected=true] {
   outline-color: var(--preference-unselected-color);
 }
 
-radio[focused=true] {
+.radio-buttons > radio[focused=true] {
   outline-color: var(--preference-selected-color);
 }
 
-radio:hover:active {
+.radio-buttons > radio:hover:active {
   outline-color: var(--preference-active-color);
 }

From d73e7186815956b7a01c1e52311b560d62e291fa Mon Sep 17 00:00:00 2001
From: Sebastian Hengst 
Date: Fri, 30 Dec 2016 11:21:24 +0100
Subject: [PATCH 176/229] Bug 1326087 - Make accesskeys in container properties
 dialog work. r=jkt

---
 browser/components/preferences/containers.xul | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/browser/components/preferences/containers.xul b/browser/components/preferences/containers.xul
index 62a775fe409d..fc8d2cccf245 100644
--- a/browser/components/preferences/containers.xul
+++ b/browser/components/preferences/containers.xul
@@ -30,17 +30,15 @@
   
 
   
   

From 4b758f2434062779e9e69fafa206176aef27236c Mon Sep 17 00:00:00 2001
From: Sebastian Hengst 
Date: Fri, 30 Dec 2016 11:21:24 +0100
Subject: [PATCH 177/229] Bug 1326098 - Use placeholder text for container
 name, remove unused strings. r=jkt

---
 browser/components/preferences/containers.xul              | 2 +-
 browser/components/preferences/in-content/containers.xul   | 2 +-
 .../en-US/chrome/browser/preferences/containers.dtd        | 2 +-
 .../en-US/chrome/browser/preferences/containers.properties | 7 -------
 4 files changed, 3 insertions(+), 10 deletions(-)

diff --git a/browser/components/preferences/containers.xul b/browser/components/preferences/containers.xul
index fc8d2cccf245..1b2672e4c4bf 100644
--- a/browser/components/preferences/containers.xul
+++ b/browser/components/preferences/containers.xul
@@ -32,7 +32,7 @@