Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/base/parts/ipc/common/ipc.mp.ts
4780 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { VSBuffer } from '../../../common/buffer.js';
7
import { Event } from '../../../common/event.js';
8
import { IDisposable } from '../../../common/lifecycle.js';
9
import { IMessagePassingProtocol, IPCClient } from './ipc.js';
10
11
/**
12
* Declare minimal `MessageEvent` and `MessagePort` interfaces here
13
* so that this utility can be used both from `browser` and
14
* `electron-main` namespace where message ports are available.
15
*/
16
17
export interface MessageEvent {
18
19
/**
20
* For our use we only consider `Uint8Array` a valid data transfer
21
* via message ports because our protocol implementation is buffer based.
22
*/
23
data: Uint8Array;
24
}
25
26
export interface MessagePort {
27
28
addEventListener(type: 'message', listener: (this: MessagePort, e: MessageEvent) => unknown): void;
29
removeEventListener(type: 'message', listener: (this: MessagePort, e: MessageEvent) => unknown): void;
30
31
postMessage(message: Uint8Array): void;
32
33
start(): void;
34
close(): void;
35
}
36
37
/**
38
* The MessagePort `Protocol` leverages MessagePort style IPC communication
39
* for the implementation of the `IMessagePassingProtocol`. That style of API
40
* is a simple `onmessage` / `postMessage` pattern.
41
*/
42
export class Protocol implements IMessagePassingProtocol {
43
44
readonly onMessage;
45
46
constructor(private port: MessagePort) {
47
this.onMessage = Event.fromDOMEventEmitter<VSBuffer>(this.port, 'message', (e: MessageEvent) => {
48
if (e.data) {
49
return VSBuffer.wrap(e.data);
50
}
51
return VSBuffer.alloc(0);
52
});
53
// we must call start() to ensure messages are flowing
54
port.start();
55
}
56
57
send(message: VSBuffer): void {
58
this.port.postMessage(message.buffer);
59
}
60
61
disconnect(): void {
62
this.port.close();
63
}
64
}
65
66
/**
67
* An implementation of a `IPCClient` on top of MessagePort style IPC communication.
68
*/
69
export class Client extends IPCClient implements IDisposable {
70
71
private protocol: Protocol;
72
73
constructor(port: MessagePort, clientId: string) {
74
const protocol = new Protocol(port);
75
super(protocol, clientId);
76
77
this.protocol = protocol;
78
}
79
80
override dispose(): void {
81
this.protocol.disconnect();
82
83
super.dispose();
84
}
85
}
86
87