1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/dom/MIDIInput.h"
8 #include "mozilla/dom/Document.h"
9 #include "mozilla/dom/MIDIPortChild.h"
10 #include "mozilla/dom/MIDIInputBinding.h"
11 #include "mozilla/dom/MIDIMessageEvent.h"
12 #include "mozilla/dom/MIDIMessageEventBinding.h"
16 namespace mozilla::dom
{
18 MIDIInput::MIDIInput(nsPIDOMWindowInner
* aWindow
)
19 : MIDIPort(aWindow
), mKeepAlive(false) {}
22 RefPtr
<MIDIInput
> MIDIInput::Create(nsPIDOMWindowInner
* aWindow
,
23 MIDIAccess
* aMIDIAccessParent
,
24 const MIDIPortInfo
& aPortInfo
,
25 const bool aSysexEnabled
) {
26 MOZ_ASSERT(static_cast<MIDIPortType
>(aPortInfo
.type()) ==
28 RefPtr
<MIDIInput
> port
= new MIDIInput(aWindow
);
29 if (!port
->Initialize(aPortInfo
, aSysexEnabled
, aMIDIAccessParent
)) {
35 JSObject
* MIDIInput::WrapObject(JSContext
* aCx
,
36 JS::Handle
<JSObject
*> aGivenProto
) {
37 return MIDIInput_Binding::Wrap(aCx
, this, aGivenProto
);
40 void MIDIInput::Receive(const nsTArray
<MIDIMessage
>& aMsgs
) {
42 return; // Ignore messages once we've been disconnected from the owner
45 nsCOMPtr
<Document
> doc
= GetOwner()->GetDoc();
47 NS_WARNING("No document available to send MIDIMessageEvent to!");
50 for (const auto& msg
: aMsgs
) {
51 RefPtr
<MIDIMessageEvent
> event(
52 MIDIMessageEvent::Constructor(this, msg
.timestamp(), msg
.data()));
53 DispatchTrustedEvent(event
);
57 void MIDIInput::StateChange() {
58 if (Port()->ConnectionState() == MIDIPortConnectionState::Open
||
59 (Port()->DeviceState() == MIDIPortDeviceState::Connected
&&
60 Port()->ConnectionState() == MIDIPortConnectionState::Pending
)) {
61 KeepAliveOnMidimessage();
63 DontKeepAliveOnMidimessage();
67 void MIDIInput::EventListenerAdded(nsAtom
* aType
) {
68 if (aType
== nsGkAtoms::onmidimessage
) {
69 // HACK: the Web MIDI spec states that we should open a port only when
70 // setting the midimessage event handler but Chrome does it even when
71 // adding event listeners hence this.
72 if (Port()->ConnectionState() != MIDIPortConnectionState::Open
) {
73 LOG("onmidimessage event listener added, sending implicit Open");
78 DOMEventTargetHelper::EventListenerAdded(aType
);
81 void MIDIInput::DisconnectFromOwner() {
82 DontKeepAliveOnMidimessage();
84 MIDIPort::DisconnectFromOwner();
87 void MIDIInput::KeepAliveOnMidimessage() {
90 KeepAliveIfHasListenersFor(nsGkAtoms::onmidimessage
);
94 void MIDIInput::DontKeepAliveOnMidimessage() {
96 IgnoreKeepAliveIfHasListenersFor(nsGkAtoms::onmidimessage
);
101 } // namespace mozilla::dom