-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
304 lines (267 loc) · 7.18 KB
/
main.js
File metadata and controls
304 lines (267 loc) · 7.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// OpenPorts - macOS menu bar app (JXA stay-open applet)
// Shows all TCP listening ports grouped by process name
ObjC.import("Cocoa");
let statusItem = null;
let menuDelegate = null;
function getOpenPorts() {
const app = Application.currentApplication();
app.includeStandardAdditions = true;
let output;
try {
output = app.doShellScript(
"lsof +c 0 -i -P -n -sTCP:LISTEN 2>/dev/null | tail -n +2",
);
} catch (e) {
return {};
}
const groups = {};
const lines = output.split("\r").filter((l) => l.length > 0);
for (const line of lines) {
const parts = line.split(/\s+/);
if (parts.length < 9) continue;
const command = parts[0];
const pid = parts[1];
// TCP LISTEN lines end with "(LISTEN)", so address:port is second-to-last
const addrField = parts[parts.length - 2];
const portMatch = addrField.match(/:(\d+)$/);
if (!portMatch) continue;
const port = parseInt(portMatch[1], 10);
const cleanName = command.replace(/\\x20/g, " ");
if (!groups[cleanName]) {
groups[cleanName] = { pid: pid, ports: {} };
}
groups[cleanName].ports[port] = true;
}
const result = {};
const sortedNames = Object.keys(groups).sort((a, b) =>
a.toLowerCase().localeCompare(b.toLowerCase()),
);
for (const name of sortedNames) {
result[name] = {
pid: groups[name].pid,
ports: Object.keys(groups[name].ports)
.map(Number)
.sort((a, b) => a - b),
};
}
return result;
}
function killProcess(pid) {
const app = Application.currentApplication();
app.includeStandardAdditions = true;
try {
app.doShellScript(`kill ${pid}`);
} catch (e) {
// Process may already be gone
}
refreshMenu();
}
function copyToClipboard(text) {
const pb = $.NSPasteboard.generalPasteboard;
pb.clearContents;
pb.setStringForType($(text), $.NSPasteboardTypeString);
}
function buildMenu() {
const menu = $.NSMenu.alloc.init;
menu.autoenablesItems = false;
const groups = getOpenPorts();
const names = Object.keys(groups);
if (names.length === 0) {
const noItem = $.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$("No listening ports"),
null,
$(""),
);
noItem.enabled = false;
menu.addItem(noItem);
} else {
let totalPorts = 0;
for (const name of names) totalPorts += groups[name].ports.length;
const header = $.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$(`${totalPorts} open port${totalPorts !== 1 ? "s" : ""}`),
null,
$(""),
);
header.enabled = false;
menu.addItem(header);
menu.addItem($.NSMenuItem.separatorItem);
for (const name of names) {
const { pid, ports } = groups[name];
if (ports.length === 1) {
const title = `${ports[0]} · ${name}`;
const item =
$.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$(title),
"menuItemClicked:",
$(""),
);
item.target = menuDelegate;
item.representedObject = $(`${ports[0]}`);
item.enabled = true;
// Submenu with copy and kill actions
const actionMenu = $.NSMenu.alloc.init;
const copyItem =
$.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$(`Copy port ${ports[0]}`),
"menuItemClicked:",
$(""),
);
copyItem.target = menuDelegate;
copyItem.representedObject = $(`${ports[0]}`);
copyItem.enabled = true;
actionMenu.addItem(copyItem);
const killItem =
$.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$(`Kill process (PID ${pid})`),
"killClicked:",
$(""),
);
killItem.target = menuDelegate;
killItem.representedObject = $(`${pid}`);
killItem.enabled = true;
actionMenu.addItem(killItem);
item.submenu = actionMenu;
menu.addItem(item);
} else {
const title = `${name} (${ports.length} ports)`;
const item =
$.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$(title),
null,
$(""),
);
const submenu = $.NSMenu.alloc.init;
for (const port of ports) {
const subItem =
$.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$(`${port}`),
"menuItemClicked:",
$(""),
);
subItem.target = menuDelegate;
subItem.representedObject = $(`${port}`);
subItem.enabled = true;
submenu.addItem(subItem);
}
submenu.addItem($.NSMenuItem.separatorItem);
const killItem =
$.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$(`Kill process (PID ${pid})`),
"killClicked:",
$(""),
);
killItem.target = menuDelegate;
killItem.representedObject = $(`${pid}`);
killItem.enabled = true;
submenu.addItem(killItem);
item.submenu = submenu;
menu.addItem(item);
}
}
}
menu.addItem($.NSMenuItem.separatorItem);
const quitItem = $.NSMenuItem.alloc.initWithTitleActionKeyEquivalent(
$("Quit"),
"quitClicked:",
$("q"),
);
quitItem.target = menuDelegate;
quitItem.enabled = true;
menu.addItem(quitItem);
return menu;
}
function refreshMenu() {
statusItem.menu = buildMenu();
}
// Register delegate class
ObjC.registerSubclass({
name: "OpenPortsDelegate",
superclass: "NSObject",
methods: {
"menuItemClicked:": {
types: ["void", ["id"]],
implementation: function (sender) {
const port = sender.representedObject.js;
copyToClipboard(port);
},
},
"killClicked:": {
types: ["void", ["id"]],
implementation: function (sender) {
const pid = sender.representedObject.js;
killProcess(pid);
},
},
"quitClicked:": {
types: ["void", ["id"]],
implementation: function (_sender) {
$.NSApplication.sharedApplication.terminate(
$.NSApplication.sharedApplication,
);
},
},
"appDidLaunch:": {
types: ["void", ["id"]],
implementation: function (_notification) {
refreshMenu();
},
},
"appDidTerminate:": {
types: ["void", ["id"]],
implementation: function (_notification) {
refreshMenu();
},
},
},
});
// JXA stay-open applet handlers
function run() {
const app = $.NSApplication.sharedApplication;
app.setActivationPolicy($.NSApplicationActivationPolicyAccessory);
const statusBar = $.NSStatusBar.systemStatusBar;
statusItem = statusBar.statusItemWithLength($.NSVariableStatusItemLength);
const statusButton = statusItem.button;
statusButton.toolTip = $("Open Ports");
// Try SF Symbol icon, fallback to text
try {
const img = $.NSImage.imageWithSystemSymbolNameAccessibilityDescription(
"network",
"Open Ports",
);
if (img.js !== undefined) {
img.size = $.NSMakeSize(18, 18);
img.template = true;
statusButton.image = img;
} else {
statusButton.title = $("Ports");
}
} catch (e) {
statusButton.title = $("Ports");
}
menuDelegate = $.OpenPortsDelegate.alloc.init;
statusItem.menu = buildMenu();
// Watch for app launches/terminations to refresh instantly
const ws = $.NSWorkspace.sharedWorkspace.notificationCenter;
ws.addObserverSelectorNameObject(
menuDelegate,
"appDidLaunch:",
$.NSWorkspaceDidLaunchApplicationNotification,
null,
);
ws.addObserverSelectorNameObject(
menuDelegate,
"appDidTerminate:",
$.NSWorkspaceDidTerminateApplicationNotification,
null,
);
}
// idle handler — rebuild menu with fresh port data every 2s
function idle() {
statusItem.menu = buildMenu();
return 2;
}
// quit handler
function quit() {
const app = $.NSApplication.sharedApplication;
app.terminate(app);
}