forked from The-OpenROAD-Project/OpenROAD
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
984 lines (898 loc) · 37.5 KB
/
Copy pathmain.js
File metadata and controls
984 lines (898 loc) · 37.5 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026, The OpenROAD Authors
import { GoldenLayout, LayoutConfig } from 'https://esm.sh/golden-layout@2.6.0';
import { latLngToDbu } from './coordinates.js';
import { WebSocketManager } from './websocket-manager.js';
import { createWebSocketTileLayer } from './websocket-tile-layer.js';
import { TimingWidget } from './timing-widget.js';
import { ClockTreeWidget } from './clock-tree-widget.js';
import { ChartsWidget } from './charts-widget.js';
import { HierarchyBrowser } from './hierarchy-browser.js';
import { createInspectorPanel } from './inspector.js';
import { populateDisplayControls } from './display-controls.js';
import { createMenuBar } from './menu-bar.js';
import { RulerManager } from './ruler.js';
import { SchematicWidget } from './schematic-widget.js';
import { DrcWidget } from './drc-widget.js';
import { TclCompleter } from './tcl-completer.js';
import { setCookie } from './theme.js';
// ─── Status Indicator ───────────────────────────────────────────────────────
const statusDiv = document.getElementById('websocket-status');
let disconnectTimeout = null;
const DISCONNECT_DELAY_MS = 2000; // Show banner after 2 seconds of disconnection
function updateStatus() {
const isConnected = app.websocketManager && app.websocketManager.isConnected;
const pendingCount = app.websocketManager ? app.websocketManager.pending.size : 0;
if (!isConnected) {
// After an intentional shutdown the "Server stopped" banner is
// already showing — don't overwrite it with the generic message.
if (app.websocketManager?._shutdown) {
return;
}
// Only show banner after a delay to avoid flashing on page load
if (!disconnectTimeout) {
disconnectTimeout = setTimeout(() => {
if (!app.websocketManager?.isConnected) {
statusDiv.innerHTML = '<div class="disconnected-banner">⚠ OpenROAD disconnected — retrying…</div>';
statusDiv.style.display = 'block';
}
}, DISCONNECT_DELAY_MS);
}
} else {
// Connected - clear timeout and show pending indicator if needed
if (disconnectTimeout) {
clearTimeout(disconnectTimeout);
disconnectTimeout = null;
}
if (pendingCount === 0) {
statusDiv.style.display = 'none';
} else {
statusDiv.innerHTML = `<div class="pending-indicator">pending: ${pendingCount}</div>`;
statusDiv.style.display = 'block';
const color = pendingCount > 20 ? 'var(--error)' : 'var(--fg-bright)';
statusDiv.querySelector('.pending-indicator').style.color = color;
}
}
}
// ─── Component Factories ────────────────────────────────────────────────────
// Shared application state — replaces scattered module-level globals.
// Components receive this via closure now; when extracted to separate files
// they'll receive it as an explicit parameter.
const app = {
map: null,
fitBounds: null,
displayControlsEl: null,
allLayers: [],
designScale: null, // pixels-per-DBU for coordinate conversion
designMaxDXDY: null, // max(width, height) in DBU for Y-axis mapping
designOriginX: 0, // bounds.xMin() in DBU (tile grid origin)
designOriginY: 0, // bounds.yMin() in DBU (tile grid origin)
websocketManager: null, // set after construction below
goldenLayout: null, // set after GL init below
hasLiberty: false,
techData: null,
inspectorEl: null,
tclOutputEl: null,
highlightRect: null,
hoverHighlightLayer: null,
hoverHighlightPane: 'hover-highlight-pane',
modulesLayer: null,
pinsLayer: null,
hierarchyBrowser: null,
focusNets: new Set(),
routeGuideNets: new Set(),
visibleLayers: new Set(),
heatMapData: null,
activeHeatMap: '',
heatMapLayer: null,
heatMapLegendEl: null,
renderHeatMapControls: null,
rulerManager: null,
};
const visibility = {
stdcells: true,
macros: true,
// Pad sub-types
pad_input: true,
pad_output: true,
pad_inout: true,
pad_power: true,
pad_spacer: true,
pad_areaio: true,
pad_other: true,
// Physical sub-types
phys_fill: false,
phys_endcap: true,
phys_welltap: true,
phys_tie: true,
phys_antenna: true,
phys_cover: true,
phys_bump: true,
phys_other: true,
// Std cell sub-types
std_bufinv: true,
std_bufinv_timing: true,
std_clock_bufinv: true,
std_clock_gate: true,
std_level_shift: true,
std_sequential: true,
std_combinational: true,
// Net sub-types
net_signal: true,
net_power: true,
net_ground: true,
net_clock: true,
net_reset: true,
net_tieoff: true,
net_scan: true,
net_analog: true,
// Shapes
routing: true,
special_nets: true,
pins: true,
pin_markers: true,
blockages: true,
// Blockages
placement_blockages: true,
routing_obstructions: true,
// Rows (off by default, matching GUI)
rows: false,
// Tracks (off by default, matching GUI)
tracks_pref: false,
tracks_non_pref: false,
// Module view
module_view: false,
// Debug
debug: false,
};
const WebSocketTileLayer = createWebSocketTileLayer(visibility);
const BLANK_TILE
= 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
const HeatMapTileLayer = L.GridLayer.extend({
initialize: function(websocketManager, appState, options) {
this._websocketManager = websocketManager;
this._appState = appState;
L.GridLayer.prototype.initialize.call(this, options);
},
createTile: function(coords, done) {
const tile = document.createElement('img');
tile.alt = '';
tile.setAttribute('role', 'presentation');
tile._tileDone = false;
tile.onload = () => {
if (tile.src && tile.src.startsWith('blob:')) {
URL.revokeObjectURL(tile.src);
}
if (!tile._tileDone) {
tile._tileDone = true;
done(null, tile);
}
};
tile.onerror = () => {
if (!tile._tileDone) {
tile._tileDone = true;
done(new Error('heat map tile load error'), tile);
}
};
const active = this._appState.activeHeatMap;
if (!active) {
tile.src = BLANK_TILE;
return tile;
}
this._websocketManager.request({
type: 'heatmap_tile',
name: active,
z: coords.z,
x: coords.x,
y: coords.y,
}).then(blob => {
tile.src = URL.createObjectURL(blob);
}).catch(() => {
tile.src = BLANK_TILE;
});
return tile;
},
refreshTiles: function() {
if (!this._map) return;
for (const key in this._tiles) {
const tileInfo = this._tiles[key];
if (!tileInfo || !tileInfo.el) continue;
const tile = tileInfo.el;
const coords = tileInfo.coords;
const active = this._appState.activeHeatMap;
if (!active) {
tile.src = BLANK_TILE;
continue;
}
this._websocketManager.request({
type: 'heatmap_tile',
name: active,
z: coords.z,
x: coords.x,
y: coords.y,
}).then(blob => {
if (tile.src && tile.src.startsWith('blob:')) {
URL.revokeObjectURL(tile.src);
}
tile.src = URL.createObjectURL(blob);
}).catch(() => {
tile.src = BLANK_TILE;
});
}
},
});
function updateHeatMaps(data) {
app.heatMapData = data;
app.activeHeatMap = data.active || '';
if (app.heatMapLayer) {
if (app.activeHeatMap) {
if (!app.map.hasLayer(app.heatMapLayer)) {
app.heatMapLayer.addTo(app.map);
}
} else if (app.map.hasLayer(app.heatMapLayer)) {
app.map.removeLayer(app.heatMapLayer);
}
app.heatMapLayer.refreshTiles();
}
if (app.renderHeatMapControls) {
app.renderHeatMapControls(data);
}
}
app.updateHeatMaps = updateHeatMaps;
function redrawAllLayers() {
// Show/hide modules layer based on module_view visibility
if (app.modulesLayer) {
if (visibility.module_view && !app.map.hasLayer(app.modulesLayer)) {
app.modulesLayer.addTo(app.map);
} else if (!visibility.module_view && app.map.hasLayer(app.modulesLayer)) {
app.map.removeLayer(app.modulesLayer);
}
}
// Show/hide pin markers layer
if (app.pinsLayer) {
if (visibility.pin_markers && !app.map.hasLayer(app.pinsLayer)) {
app.pinsLayer.addTo(app.map);
} else if (!visibility.pin_markers && app.map.hasLayer(app.pinsLayer)) {
app.map.removeLayer(app.pinsLayer);
}
}
for (const layer of app.allLayers) {
layer.refreshTiles();
}
if (app.heatMapLayer) {
app.heatMapLayer.refreshTiles();
}
}
// Debounced wrapper: coalesces back-to-back server pushes (e.g.
// debug_refresh + debug_paused) into a single redrawAllLayers() call.
let _redrawRAF = null;
function scheduleRedrawAllLayers() {
if (_redrawRAF !== null) return;
_redrawRAF = requestAnimationFrame(() => {
_redrawRAF = null;
redrawAllLayers();
});
}
function createLayoutViewer(container) {
const mapDiv = document.createElement('div');
mapDiv.className = 'layout-viewer';
mapDiv.style.width = '100%';
mapDiv.style.height = '100%';
mapDiv.style.backgroundColor = 'var(--bg-map)';
container.element.appendChild(mapDiv);
const heatMapLegend = document.createElement('div');
heatMapLegend.className = 'heatmap-map-legend hidden';
mapDiv.appendChild(heatMapLegend);
app.heatMapLegendEl = heatMapLegend;
app.map = L.map(mapDiv, {
crs: L.CRS.Simple,
zoom: 1,
zoomSnap: 0,
fadeAnimation: false,
attributionControl: false,
});
const hoverPane = app.map.createPane(app.hoverHighlightPane);
hoverPane.style.zIndex = '650';
hoverPane.style.pointerEvents = 'none';
new ResizeObserver(() => {
app.map.invalidateSize({ animate: false });
}).observe(mapDiv);
// Coordinate readout overlay (bottom-left of the layout viewer).
const coordBar = document.createElement('div');
coordBar.id = 'coord-bar';
mapDiv.appendChild(coordBar);
app.map.on('mousemove', (e) => {
app.lastMouseLatLng = e.latlng;
if (!app.designScale) return;
const { dbuX, dbuY } = latLngToDbu(
e.latlng.lat, e.latlng.lng, app.designScale, app.designMaxDXDY,
app.designOriginX, app.designOriginY);
const dbuPerUm = app.techData?.dbu_per_micron || 1000;
const precision = Math.ceil(Math.log10(dbuPerUm));
const xUm = (dbuX / dbuPerUm).toFixed(precision);
const yUm = (dbuY / dbuPerUm).toFixed(precision);
coordBar.textContent = `X: ${xUm} Y: ${yUm}`;
});
app.map.on('mouseout', () => { app.lastMouseLatLng = null; });
app.rulerManager = new RulerManager(app, visibility, updateInspector, focusComponent);
}
function createDisplayControls(container) {
const el = document.createElement('div');
el.className = 'display-controls';
el.innerHTML = '<div class="loading">Loading layers...</div>';
container.element.appendChild(el);
app.displayControlsEl = el;
}
function tclAppend(text, className) {
if (!app.tclOutputEl) return;
const span = document.createElement('span');
if (className) span.className = className;
span.textContent = text;
app.tclOutputEl.appendChild(span);
app.tclOutputEl.scrollTop = app.tclOutputEl.scrollHeight;
}
// Browser UX for `exit`/`quit` typed in the Tcl console. The OpenROAD
// process keeps running in the terminal — only the web session ends.
// window.close() only succeeds when the tab was opened via JS (or via
// certain launcher integrations); when it fails we replace the page with
// a terminal overlay so the user knows the web_server stopped and they
// can close the tab manually.
function handleServerShutdown() {
// Suppress the normal "disconnected" banner — the disconnect is intentional.
if (app.websocketManager) {
app.websocketManager.onPush = () => {};
}
const overlay = document.createElement('div');
overlay.style.cssText =
'position:fixed;inset:0;z-index:99999;background:#1e1e1e;color:#ddd;' +
'display:flex;flex-direction:column;align-items:center;justify-content:center;' +
'font-family:system-ui,sans-serif;font-size:16px;padding:24px;text-align:center;';
overlay.innerHTML =
'<div style="font-size:22px;margin-bottom:12px;">Web session closed</div>' +
'<div style="opacity:0.7;">OpenROAD is still running in the terminal. You can close this tab.</div>';
document.body.appendChild(overlay);
setTimeout(() => { try { window.close(); } catch (e) { /* ignore */ } }, 400);
}
function createTclConsole(container) {
const el = document.createElement('div');
el.className = 'tcl-console';
el.innerHTML =
'<div class="tcl-output"></div>' +
'<div class="tcl-input-row">' +
' <span class="tcl-prompt">%</span>' +
' <input class="tcl-input" type="text" placeholder="Enter Tcl command..." spellcheck="false" autocomplete="off" autocapitalize="none" autocorrect="off"/>' +
'</div>';
container.element.appendChild(el);
app.tclOutputEl = el.querySelector('.tcl-output');
const input = el.querySelector('.tcl-input');
const completer = new TclCompleter(input, app.websocketManager);
input.addEventListener('keydown', (e) => {
// Let completer handle first (Tab, arrow keys, Enter-when-popup-visible)
if (completer.handleKeyDown(e)) return;
if (e.key === 'Enter') {
const cmd = input.value.trim();
if (!cmd) return;
tclAppend(`>>> ${cmd}\n`, 'tcl-cmd');
completer.addToHistory(cmd);
input.value = '';
app.websocketManager.request({ type: 'tcl_eval', cmd })
.then(data => {
if (data.output) {
tclAppend(data.output,
data.is_error ? 'tcl-error' : '');
}
if (data.result) {
tclAppend(data.result + '\n',
data.is_error ? 'tcl-error' : '');
}
if (data.action === 'shutdown') {
handleServerShutdown();
}
})
.catch(err => tclAppend(`Error: ${err}\n`, 'tcl-error'));
}
});
}
// ─── Inspector Panel ────────────────────────────────────────────────────────
const inspector = createInspectorPanel(app, redrawAllLayers);
const createInspector = inspector.createInspector;
const updateInspector = inspector.updateInspector;
const highlightBBox = inspector.highlightBBox;
app.updateInspector = updateInspector;
function createBrowser(container) {
new HierarchyBrowser(container, app, redrawAllLayers);
}
function createTimingWidget(container) {
app.timingWidget = new TimingWidget(app, redrawAllLayers);
container.element.appendChild(app.timingWidget.element);
}
function createDRCWidget(container) {
app.drcWidget = new DrcWidget(app, redrawAllLayers);
container.element.appendChild(app.drcWidget.element);
}
function createClockWidget(container) {
app.clockTreeWidget = new ClockTreeWidget(container, app, redrawAllLayers);
}
function createChartsWidget(container) {
app.chartsWidget = new ChartsWidget(app, redrawAllLayers);
container.element.appendChild(app.chartsWidget.element);
}
function createHelpWidget(container) {
const el = document.createElement('div');
el.className = 'help-panel';
el.innerHTML =
'<h3>Keyboard Shortcuts</h3>' +
'<table>' +
'<tr><td><kbd>f</kbd></td><td>Fit design to viewport</td></tr>' +
'<tr><td><kbd>scroll</kbd></td><td>Zoom in/out</td></tr>' +
'<tr><td><kbd>drag</kbd></td><td>Pan the view</td></tr>' +
'<tr><td><kbd>right-drag</kbd></td><td>Rubber-band zoom</td></tr>' +
'<tr><td><kbd>k</kbd></td><td>Toggle ruler mode</td></tr>' +
'<tr><td><kbd>Shift+K</kbd></td><td>Clear all rulers</td></tr>' +
'<tr><td><kbd>Escape</kbd></td><td>Cancel ruler (when building)</td></tr>' +
'</table>';
container.element.appendChild(el);
}
function createSelectHighlight(container) {
createStubPanel(container, 'Selection',
'Selection and highlight browser.');
}
function createSchematicWidget(container) {
new SchematicWidget(container, app);
}
function createStubPanel(container, title, description) {
const el = document.createElement('div');
el.className = 'stub-panel';
el.innerHTML =
`<div class="stub-title">${title}</div>` +
`<div class="stub-desc">${description}</div>`;
container.element.appendChild(el);
}
// ─── Layout Configuration ───────────────────────────────────────────────────
const defaultLayoutConfig = {
root: {
type: 'row',
content: [
{
type: 'component',
componentType: 'DisplayControls',
title: 'Display Controls',
width: 15,
},
{
type: 'column',
width: 55,
content: [
{
type: 'stack',
height: 70,
content: [
{
type: 'component',
componentType: 'LayoutViewer',
title: 'Layout',
isClosable: false,
},
{
type: 'component',
componentType: 'SchematicWidget',
title: 'Schematic',
},
],
},
{
type: 'component',
componentType: 'TclConsole',
title: 'Tcl Console',
height: 30,
},
],
},
{
type: 'stack',
width: 30,
content: [
{
type: 'component',
componentType: 'Inspector',
title: 'Inspector',
},
{
type: 'component',
componentType: 'Browser',
title: 'Hierarchy',
},
{
type: 'component',
componentType: 'TimingWidget',
title: 'Timing',
},
{
type: 'component',
componentType: 'DRCWidget',
title: 'DRC',
},
{
type: 'component',
componentType: 'ClockWidget',
title: 'Clock Tree',
},
{
type: 'component',
componentType: 'ChartsWidget',
title: 'Charts',
},
{
type: 'component',
componentType: 'HelpWidget',
title: 'Help',
},
],
},
],
},
};
// ─── Golden Layout Init ─────────────────────────────────────────────────────
app.goldenLayout = new GoldenLayout(document.getElementById('gl-container'));
app.goldenLayout.registerComponentFactoryFunction('LayoutViewer', createLayoutViewer);
app.goldenLayout.registerComponentFactoryFunction('DisplayControls', createDisplayControls);
app.goldenLayout.registerComponentFactoryFunction('TclConsole', createTclConsole);
app.goldenLayout.registerComponentFactoryFunction('Inspector', createInspector);
app.goldenLayout.registerComponentFactoryFunction('Browser', createBrowser);
app.goldenLayout.registerComponentFactoryFunction('TimingWidget', createTimingWidget);
app.goldenLayout.registerComponentFactoryFunction('DRCWidget', createDRCWidget);
app.goldenLayout.registerComponentFactoryFunction('ClockWidget', createClockWidget);
app.goldenLayout.registerComponentFactoryFunction('ChartsWidget', createChartsWidget);
app.goldenLayout.registerComponentFactoryFunction('SchematicWidget', createSchematicWidget);
app.goldenLayout.registerComponentFactoryFunction('HelpWidget', createHelpWidget);
app.goldenLayout.registerComponentFactoryFunction('SelectHighlight', createSelectHighlight);
// Layout version — bump this to force a layout reset when components change.
const LAYOUT_VERSION = 3;
// ─── WebSocket Init ─────────────────────────────────────────────────────────
// Must be created before loadLayout so that components (e.g. SchematicWidget)
// constructed during layout initialisation can access app.websocketManager.
const staticCache = window.__STATIC_CACHE__ || null;
if (staticCache) {
app.websocketManager = WebSocketManager.fromCache(staticCache, updateStatus);
} else {
const websocketUrl = `ws://${window.location.host || 'localhost:8080'}/ws`;
app.websocketManager = new WebSocketManager(websocketUrl, updateStatus);
}
// Check initial connection status
updateStatus();
// Restore saved layout or use default
const savedLayout = localStorage.getItem('gl-layout');
const savedVersion = parseInt(localStorage.getItem('gl-layout-version'), 10);
if (savedLayout && savedVersion === LAYOUT_VERSION) {
try {
const resolved = JSON.parse(savedLayout);
app.goldenLayout.loadLayout(LayoutConfig.fromResolved(resolved));
} catch (e) {
app.goldenLayout.loadLayout(defaultLayoutConfig);
}
} else {
app.goldenLayout.loadLayout(defaultLayoutConfig);
}
localStorage.setItem('gl-layout-version', LAYOUT_VERSION);
// Persist layout on changes (drag, resize, close, etc.)
app.goldenLayout.on('stateChanged', () => {
localStorage.setItem('gl-layout', JSON.stringify(app.goldenLayout.saveLayout()));
});
// Handle window resize
window.addEventListener('resize', () => {
const menuBarHeight = document.getElementById('menu-bar').offsetHeight;
app.goldenLayout.setSize(window.innerWidth, window.innerHeight - menuBarHeight);
});
// componentType → display title (must match defaultLayoutConfig).
const componentTitles = {
LayoutViewer: 'Layout',
DisplayControls: 'Display Controls',
TclConsole: 'Tcl Console',
Inspector: 'Inspector',
Browser: 'Hierarchy',
TimingWidget: 'Timing',
DRCWidget: 'DRC',
ClockWidget: 'Clock Tree',
ChartsWidget: 'Charts',
SchematicWidget: 'Schematic',
HelpWidget: 'Help',
SelectHighlight: 'Select Highlight',
};
// Focus a Golden Layout component tab, or re-create it if it was closed.
function focusComponent(componentType) {
function find(item) {
if (item.isComponent && item.componentType === componentType) return item;
if (item.contentItems) {
for (const child of item.contentItems) {
const found = find(child);
if (found) return found;
}
}
return null;
}
const item = find(app.goldenLayout.rootItem);
if (item) {
item.focus();
} else {
const title = componentTitles[componentType] || componentType;
app.goldenLayout.addComponent(componentType, undefined, title);
}
}
app.focusComponent = focusComponent;
app.toggleTheme = function() {
const next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
document.documentElement.dataset.theme = next;
setCookie('or_theme', next);
// Also write to localStorage for standalone file:// reports.
if (typeof localStorage !== 'undefined') {
localStorage.setItem('or_theme', next);
}
// Re-render canvas-based widgets that read theme colors.
if (app.chartsWidget) app.chartsWidget.render();
if (app.clockTreeWidget) app.clockTreeWidget.render();
};
// ─── Menu Bar ────────────────────────────────────────────────────────────────
createMenuBar(app);
// Debug-graphics pause affordance: appended lazily when the first
// debug_paused push arrives. Clicking "Continue" tells the server to
// release the placer thread.
function ensureDebugContinueButton() {
let btn = document.getElementById('debug-continue-btn');
if (btn) return btn;
btn = document.createElement('button');
btn.id = 'debug-continue-btn';
btn.className = 'debug-continue-btn';
btn.textContent = 'Continue';
btn.title = 'Advance the debugger (gpl, cts, ...)';
btn.addEventListener('click', () => {
// Fire-and-forget; server's broadcast tells us when the placer
// actually resumed.
app.websocketManager.request({ type: 'debug_continue' })
.catch(() => {});
});
document.body.appendChild(btn);
return btn;
}
// Handle server-push notifications (e.g. search indices ready)
app.websocketManager.onPush = (msg) => {
if (msg.type === 'refresh') {
document.getElementById('loading-overlay').style.display = 'none';
redrawAllLayers();
} else if (msg.type === 'debug_paused') {
ensureDebugContinueButton().style.display = 'block';
// Refetch tiles so the user sees the current paused state.
// Use the debounced version so that a debug_refresh arriving
// in the same event-loop turn is coalesced (avoids 2x tiles).
scheduleRedrawAllLayers();
// Fetch debug charts (e.g. GPL HPWL vs iteration).
if (app.chartsWidget) {
app.websocketManager.request({ type: 'debug_charts' })
.then(data => app.chartsWidget.setDebugCharts(data.charts || []))
.catch(() => {});
}
} else if (msg.type === 'debug_resumed') {
const btn = document.getElementById('debug-continue-btn');
if (btn) btn.style.display = 'none';
} else if (msg.type === 'debug_refresh') {
// Instance positions changed — clear the stale Leaflet highlight
// outline (the tile-based highlight updates automatically).
if (app.highlightRect) {
app.map.removeLayer(app.highlightRect);
app.highlightRect = null;
}
scheduleRedrawAllLayers();
} else if (msg.type === 'log') {
// Logger output from the main Tcl thread (e.g. global_placement).
// The text already contains \n between lines from the batch; strip
// any trailing newline to avoid a blank line at the end.
let text = msg.text;
if (text.endsWith('\n')) text = text.slice(0, -1);
if (text) tclAppend(text + '\n', '');
} else if (msg.type === 'shutdown') {
// Server is stopping intentionally (web_server -stop).
// Disable auto-reconnect and show a clear message.
app.websocketManager._shutdown = true;
statusDiv.innerHTML = '<div class="disconnected-banner">Server stopped</div>';
statusDiv.style.display = 'block';
}
};
app.websocketManager.readyPromise.then(async () => {
try {
const [techData, boundsData, heatMapData] = await Promise.all([
app.websocketManager.request({ type: 'tech' }),
app.websocketManager.request({ type: 'bounds' }),
app.websocketManager.request({ type: 'heatmaps' }),
]);
app.hasLiberty = techData.has_liberty;
app.techData = techData;
// --- Set Bounds ---
const designBounds = boundsData.bounds;
const minY = designBounds[0][0];
const minX = designBounds[0][1];
const maxY = designBounds[1][0];
const maxX = designBounds[1][1];
const designWidth = maxX - minX;
const designHeight = maxY - minY;
// No design loaded — skip map setup, let user open a DB via menu.
const hasDesign = designWidth > 0 && designHeight > 0;
if (hasDesign) {
const tileSize = 256;
const maxDXDY = Math.max(designWidth, designHeight);
const scale = tileSize / maxDXDY;
app.designScale = scale;
app.designMaxDXDY = maxDXDY;
app.designOriginX = minX;
app.designOriginY = minY;
app.fitBounds = [
[-maxDXDY * scale, 0],
[(designHeight - maxDXDY) * scale, designWidth * scale]
];
app.map.fitBounds(app.fitBounds);
if (staticCache) {
// Lock to the pre-rendered tile zoom level and fit.
const cacheZoom = staticCache.zoom;
app.map.setMinZoom(cacheZoom);
app.map.setMaxZoom(cacheZoom);
app.map.fitBounds(app.fitBounds);
app.map.scrollWheelZoom.disable();
app.map.touchZoom.disable();
app.map.boxZoom.disable();
app.map.doubleClickZoom.disable();
// Path highlight overlay image.
app.pathOverlay = L.imageOverlay('', app.fitBounds, {
opacity: 1, interactive: false, zIndex: 1000,
});
staticCache.setPathOverlay = (src) => {
if (src) {
app.pathOverlay.setUrl(src);
app.pathOverlay.addTo(app.map);
} else {
app.map.removeLayer(app.pathOverlay);
}
};
}
}
// Click-to-select: convert click position to DBU and query server
if (staticCache) {
// Hide loading overlay — shapes are always ready in static mode.
document.getElementById('loading-overlay').style.display = 'none';
}
if (!staticCache) app.map.on('click', (e) => {
if (!app.designScale) return;
if (app.rulerManager && app.rulerManager.isActive()) return;
const { dbuX: dbu_x, dbuY: dbu_y } = latLngToDbu(
e.latlng.lat, e.latlng.lng, app.designScale, app.designMaxDXDY,
app.designOriginX, app.designOriginY);
const vf = {};
for (const [k, v] of Object.entries(visibility)) {
vf[k] = v ? 1 : 0;
}
app.websocketManager.request({ type: 'select', dbu_x, dbu_y, zoom: app.map.getZoom(), visible_layers: [...app.visibleLayers], ...vf })
.then(data => {
console.log('Select response:', data, 'at dbu', dbu_x, dbu_y);
app.map.closePopup();
if (data.selected && data.selected.length > 0) {
const inst = data.selected[0];
if (inst.type === 'Inst') {
app.selectedInstanceName = inst.name;
if (app.schematicWidget) {
app.schematicWidget.refresh();
}
}
updateInspector(data);
focusComponent('Inspector');
// Highlight selected instance bbox
if (inst.bbox) {
highlightBBox(inst.bbox[0], inst.bbox[1],
inst.bbox[2], inst.bbox[3]);
}
} else {
updateInspector(null);
if (app.highlightRect) {
app.map.removeLayer(app.highlightRect);
app.highlightRect = null;
}
}
redrawAllLayers();
})
.catch(err => {
console.error('Select failed:', err);
});
});
// ─── Right-click rubber-band zoom ──────────────────────────────
if (!staticCache) {
const container = app.map.getContainer();
let rbStart = null; // {x, y} in client coords
let rbDiv = null; // overlay element
container.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
container.addEventListener('mousedown', (e) => {
if (e.button !== 2) return;
rbStart = { x: e.clientX, y: e.clientY };
app.map.dragging.disable();
});
window.addEventListener('mousemove', (e) => {
if (!rbStart) return;
const dx = e.clientX - rbStart.x;
const dy = e.clientY - rbStart.y;
if (!rbDiv && Math.abs(dx) >= 4 && Math.abs(dy) >= 4) {
rbDiv = document.createElement('div');
rbDiv.className = 'rubber-band';
document.body.appendChild(rbDiv);
}
if (rbDiv) {
const left = Math.min(rbStart.x, e.clientX);
const top = Math.min(rbStart.y, e.clientY);
rbDiv.style.left = left + 'px';
rbDiv.style.top = top + 'px';
rbDiv.style.width = Math.abs(dx) + 'px';
rbDiv.style.height = Math.abs(dy) + 'px';
}
});
window.addEventListener('mouseup', (e) => {
if (!rbStart) return;
const wasShowing = !!rbDiv;
if (rbDiv) {
rbDiv.remove();
rbDiv = null;
}
const start = rbStart;
rbStart = null;
app.map.dragging.enable();
if (!wasShowing) return;
// Convert the two screen corners to lat/lng and zoom
const rect = container.getBoundingClientRect();
const p1 = app.map.containerPointToLatLng([
start.x - rect.left, start.y - rect.top]);
const p2 = app.map.containerPointToLatLng([
e.clientX - rect.left, e.clientY - rect.top]);
app.map.fitBounds([
[Math.min(p1.lat, p2.lat), Math.min(p1.lng, p2.lng)],
[Math.max(p1.lat, p2.lat), Math.max(p1.lng, p2.lng)],
]);
});
}
populateDisplayControls(app, visibility, WebSocketTileLayer,
techData, redrawAllLayers, HeatMapTileLayer);
updateHeatMaps(heatMapData);
// Only show the loading overlay if a design is loaded but shapes
// aren't ready yet. On browser reload (without server restart),
// shapes are already built so we skip the overlay.
if (hasDesign && !boundsData.shapes_ready) {
document.getElementById('loading-overlay').style.display = 'flex';
}
} catch (err) {
console.error('Failed to load initial data from server:', err);
}
});
// ─── Keyboard Shortcuts ─────────────────────────────────────────────────────
document.addEventListener('keydown', (e) => {
// Ignore shortcuts when typing in an input field
const tag = e.target.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target.isContentEditable) return;
const key = e.key.toLowerCase();
if (key === 'escape' && app.rulerManager && app.rulerManager.isActive()) {
app.rulerManager.cancelRulerBuild();
} else if (key === 'k' && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
if (app.rulerManager) app.rulerManager.toggleRulerMode();
} else if (key === 'k' && e.shiftKey && !e.ctrlKey && !e.metaKey) {
if (app.rulerManager) app.rulerManager.clearAllRulers();
} else if (key === 'f' && !e.ctrlKey && !e.metaKey && app.fitBounds) {
app.map.fitBounds(app.fitBounds);
} else if (key === 'z' && !e.shiftKey && !e.ctrlKey && app.map) {
if (app.lastMouseLatLng) {
app.map.setZoomAround(app.lastMouseLatLng, app.map.getZoom() + 1);
} else {
app.map.zoomIn();
}
} else if (key === 'z' && e.shiftKey && !e.ctrlKey && app.map) {
if (app.lastMouseLatLng) {
app.map.setZoomAround(app.lastMouseLatLng, app.map.getZoom() - 1);
} else {
app.map.zoomOut();
}
} else if (key === 't' && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
app.toggleTheme();
}
}, true);