topoForce.js
38.2 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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
ONOS GUI -- Topology Event Module.
Defines event handling for events received from the server.
*/
(function () {
'use strict';
// injected refs
var $log, fs, sus, is, ts, flash, tis, icfg, uplink;
// configuration
var labelConfig = {
imgPad: 16,
padLR: 4,
padTB: 3,
marginLR: 3,
marginTB: 2,
port: {
gap: 3,
width: 18,
height: 14
}
};
var deviceIconConfig = {
xoff: -20,
yoff: -18
};
var linkConfig = {
light: {
baseColor: '#666',
inColor: '#66f',
outColor: '#f00',
},
dark: {
baseColor: '#aaa',
inColor: '#66f',
outColor: '#f66'
},
inWidth: 12,
outWidth: 10
};
// internal state
var settings, // merged default settings and options
force, // force layout object
drag, // drag behavior handler
network = {
nodes: [],
links: [],
lookup: {},
revLinkToKey: {}
},
lu = network.lookup, // shorthand
deviceLabelIndex = 0, // for device label cycling
hostLabelIndex = 0, // for host label cycling
showHosts = true, // whether hosts are displayed
showOffline = true, // whether offline devices are displayed
oblique = false, // whether we are in the oblique view
width, height;
// SVG elements;
var linkG, linkLabelG, nodeG;
// D3 selections;
var link, linkLabel, node;
// default settings for force layout
var defaultSettings = {
gravity: 0.4,
friction: 0.7,
charge: {
// note: key is node.class
device: -8000,
host: -5000,
_def_: -12000
},
linkDistance: {
// note: key is link.type
direct: 100,
optical: 120,
hostLink: 3,
_def_: 50
},
linkStrength: {
// note: key is link.type
// range: {0.0 ... 1.0}
//direct: 1.0,
//optical: 1.0,
//hostLink: 1.0,
_def_: 1.0
}
};
// ==========================
// === EVENT HANDLERS
function addDevice(data) {
var id = data.id,
d;
uplink.showNoDevs(false);
// although this is an add device event, if we already have the
// device, treat it as an update instead..
if (lu[id]) {
updateDevice(data);
return;
}
d = createDeviceNode(data);
network.nodes.push(d);
lu[id] = d;
$log.debug("Created new device.. ", d.id, d.x, d.y);
updateNodes();
fStart();
}
function updateDevice(data) {
var id = data.id,
d = lu[id],
wasOnline;
if (d) {
wasOnline = d.online;
angular.extend(d, data);
if (positionNode(d, true)) {
sendUpdateMeta(d, true);
}
updateNodes();
if (wasOnline !== d.online) {
findAttachedLinks(d.id).forEach(restyleLinkElement);
updateOfflineVisibility(d);
}
} else {
// TODO: decide whether we want to capture logic errors
//logicError('updateDevice lookup fail. ID = "' + id + '"');
}
}
function removeDevice(data) {
var id = data.id,
d = lu[id];
if (d) {
removeDeviceElement(d);
} else {
// TODO: decide whether we want to capture logic errors
//logicError('removeDevice lookup fail. ID = "' + id + '"');
}
}
function addHost(data) {
var id = data.id,
d, lnk;
// although this is an add host event, if we already have the
// host, treat it as an update instead..
if (lu[id]) {
updateHost(data);
return;
}
d = createHostNode(data);
network.nodes.push(d);
lu[id] = d;
$log.debug("Created new host.. ", d.id, d.x, d.y);
updateNodes();
lnk = createHostLink(data);
if (lnk) {
$log.debug("Created new host-link.. ", lnk.key);
d.linkData = lnk; // cache ref on its host
network.links.push(lnk);
lu[d.ingress] = lnk;
lu[d.egress] = lnk;
updateLinks();
}
fStart();
}
function updateHost(data) {
var id = data.id,
d = lu[id];
if (d) {
angular.extend(d, data);
if (positionNode(d, true)) {
sendUpdateMeta(d, true);
}
updateNodes();
} else {
// TODO: decide whether we want to capture logic errors
//logicError('updateHost lookup fail. ID = "' + id + '"');
}
}
function removeHost(data) {
var id = data.id,
d = lu[id];
if (d) {
removeHostElement(d, true);
} else {
// may have already removed host, if attached to removed device
//console.warn('removeHost lookup fail. ID = "' + id + '"');
}
}
function addLink(data) {
var result = findLink(data, 'add'),
bad = result.badLogic,
d = result.ldata;
if (bad) {
//logicError(bad + ': ' + link.id);
return;
}
if (d) {
// we already have a backing store link for src/dst nodes
addLinkUpdate(d, data);
return;
}
// no backing store link yet
d = createLink(data);
if (d) {
network.links.push(d);
lu[d.key] = d;
updateLinks();
fStart();
}
}
function updateLink(data) {
var result = findLink(data, 'update'),
bad = result.badLogic;
if (bad) {
//logicError(bad + ': ' + link.id);
return;
}
result.updateWith(link);
}
function removeLink(data) {
var result = findLink(data, 'remove'),
bad = result.badLogic;
if (bad) {
// may have already removed link, if attached to removed device
//console.warn(bad + ': ' + link.id);
return;
}
result.removeRawLink();
}
// ========================
function addLinkUpdate(ldata, link) {
// add link event, but we already have the reverse link installed
ldata.fromTarget = link;
network.revLinkToKey[link.id] = ldata.key;
restyleLinkElement(ldata);
}
function createLink(link) {
var lnk = linkEndPoints(link.src, link.dst);
if (!lnk) {
return null;
}
angular.extend(lnk, {
key: link.id,
class: 'link',
fromSource: link,
// functions to aggregate dual link state
type: function () {
var s = lnk.fromSource,
t = lnk.fromTarget;
return (s && s.type) || (t && t.type) || defaultLinkType;
},
online: function () {
var s = lnk.fromSource,
t = lnk.fromTarget,
both = lnk.source.online && lnk.target.online;
return both && ((s && s.online) || (t && t.online));
},
linkWidth: function () {
var s = lnk.fromSource,
t = lnk.fromTarget,
ws = (s && s.linkWidth) || 0,
wt = (t && t.linkWidth) || 0;
return Math.max(ws, wt);
}
});
return lnk;
}
function makeNodeKey(d, what) {
var port = what + 'Port';
return d[what] + '/' + d[port];
}
function makeLinkKey(d, flipped) {
var one = flipped ? makeNodeKey(d, 'dst') : makeNodeKey(d, 'src'),
two = flipped ? makeNodeKey(d, 'src') : makeNodeKey(d, 'dst');
return one + '-' + two;
}
var widthRatio = 1.4,
linkScale = d3.scale.linear()
.domain([1, 12])
.range([widthRatio, 12 * widthRatio])
.clamp(true),
allLinkTypes = 'direct indirect optical tunnel',
defaultLinkType = 'direct';
function restyleLinkElement(ldata) {
// this fn's job is to look at raw links and decide what svg classes
// need to be applied to the line element in the DOM
var th = ts.theme(),
el = ldata.el,
type = ldata.type(),
lw = ldata.linkWidth(),
online = ldata.online();
el.classed('link', true);
el.classed('inactive', !online);
el.classed(allLinkTypes, false);
if (type) {
el.classed(type, true);
}
el.transition()
.duration(1000)
.attr('stroke-width', linkScale(lw))
.attr('stroke', linkConfig[th].baseColor);
}
function findLinkById(id) {
// check to see if this is a reverse lookup, else default to given id
var key = network.revLinkToKey[id] || id;
return key && lu[key];
}
function findLink(linkData, op) {
var key = makeLinkKey(linkData),
keyrev = makeLinkKey(linkData, 1),
link = lu[key],
linkRev = lu[keyrev],
result = {},
ldata = link || linkRev,
rawLink;
if (op === 'add') {
if (link) {
// trying to add a link that we already know about
result.ldata = link;
result.badLogic = 'addLink: link already added';
} else if (linkRev) {
// we found the reverse of the link to be added
result.ldata = linkRev;
if (linkRev.fromTarget) {
result.badLogic = 'addLink: link already added';
}
}
} else if (op === 'update') {
if (!ldata) {
result.badLogic = 'updateLink: link not found';
} else {
rawLink = link ? ldata.fromSource : ldata.fromTarget;
result.updateWith = function (data) {
angular.extend(rawLink, data);
restyleLinkElement(ldata);
}
}
} else if (op === 'remove') {
if (!ldata) {
result.badLogic = 'removeLink: link not found';
} else {
rawLink = link ? ldata.fromSource : ldata.fromTarget;
if (!rawLink) {
result.badLogic = 'removeLink: link not found';
} else {
result.removeRawLink = function () {
if (link) {
// remove fromSource
ldata.fromSource = null;
if (ldata.fromTarget) {
// promote target into source position
ldata.fromSource = ldata.fromTarget;
ldata.fromTarget = null;
ldata.key = keyrev;
delete network.lookup[key];
network.lookup[keyrev] = ldata;
delete network.revLinkToKey[keyrev];
}
} else {
// remove fromTarget
ldata.fromTarget = null;
delete network.revLinkToKey[keyrev];
}
if (ldata.fromSource) {
restyleLinkElement(ldata);
} else {
removeLinkElement(ldata);
}
}
}
}
}
return result;
}
function findDevices(offlineOnly) {
var a = [];
network.nodes.forEach(function (d) {
if (d.class === 'device' && !(offlineOnly && d.online)) {
a.push(d);
}
});
return a;
}
function findAttachedHosts(devId) {
var hosts = [];
network.nodes.forEach(function (d) {
if (d.class === 'host' && d.cp.device === devId) {
hosts.push(d);
}
});
return hosts;
}
function findAttachedLinks(devId) {
var links = [];
network.links.forEach(function (d) {
if (d.source.id === devId || d.target.id === devId) {
links.push(d);
}
});
return links;
}
function removeLinkElement(d) {
var idx = fs.find(d.key, network.links, 'key'),
removed;
if (idx >=0) {
// remove from links array
removed = network.links.splice(idx, 1);
// remove from lookup cache
delete lu[removed[0].key];
updateLinks();
fResume();
}
}
function removeHostElement(d, upd) {
// first, remove associated hostLink...
removeLinkElement(d.linkData);
// remove hostLink bindings
delete lu[d.ingress];
delete lu[d.egress];
// remove from lookup cache
delete lu[d.id];
// remove from nodes array
var idx = fs.find(d.id, network.nodes);
network.nodes.splice(idx, 1);
// remove from SVG
// NOTE: upd is false if we were called from removeDeviceElement()
if (upd) {
updateNodes();
fResume();
}
}
function removeDeviceElement(d) {
var id = d.id;
// first, remove associated hosts and links..
findAttachedHosts(id).forEach(removeHostElement);
findAttachedLinks(id).forEach(removeLinkElement);
// remove from lookup cache
delete lu[id];
// remove from nodes array
var idx = fs.find(id, network.nodes);
network.nodes.splice(idx, 1);
if (!network.nodes.length) {
xlink.showNoDevs(true);
}
// remove from SVG
updateNodes();
fResume();
}
function updateHostVisibility() {
sus.makeVisible(nodeG.selectAll('.host'), showHosts);
sus.makeVisible(linkG.selectAll('.hostLink'), showHosts);
}
function updateOfflineVisibility(dev) {
function updDev(d, show) {
sus.makeVisible(d.el, show);
findAttachedLinks(d.id).forEach(function (link) {
b = show && ((link.type() !== 'hostLink') || showHosts);
sus.makeVisible(link.el, b);
});
findAttachedHosts(d.id).forEach(function (host) {
b = show && showHosts;
sus.makeVisible(host.el, b);
});
}
if (dev) {
// updating a specific device that just toggled off/on-line
updDev(dev, dev.online || showOffline);
} else {
// updating all offline devices
findDevices(true).forEach(function (d) {
updDev(d, showOffline);
});
}
}
function sendUpdateMeta(d, store) {
var metaUi = {},
ll;
if (store) {
ll = lngLatFromCoord([d.x, d.y]);
metaUi = {
x: d.x,
y: d.y,
lng: ll[0],
lat: ll[1]
};
}
d.metaUi = metaUi;
uplink.sendEvent('updateMeta', {
id: d.id,
'class': d.class,
memento: metaUi
});
}
// ==========================
// === Devices and hosts - helper functions
function coordFromLngLat(loc) {
var p = uplink.projection();
return p ? p([loc.lng, loc.lat]) : [0, 0];
}
function lngLatFromCoord(coord) {
var p = uplink.projection();
return p ? p.invert([coord.x, coord.y]) : [0, 0];
}
function positionNode(node, forUpdate) {
var meta = node.metaUi,
x = meta && meta.x,
y = meta && meta.y,
xy;
// If we have [x,y] already, use that...
if (x && y) {
node.fixed = true;
node.px = node.x = x;
node.py = node.y = y;
return;
}
var location = node.location,
coord;
if (location && location.type === 'latlng') {
coord = coordFromLngLat(location);
node.fixed = true;
node.px = node.x = coord[0];
node.py = node.y = coord[1];
return true;
}
// if this is a node update (not a node add).. skip randomizer
if (forUpdate) {
return;
}
// Note: Placing incoming unpinned nodes at exactly the same point
// (center of the view) causes them to explode outwards when
// the force layout kicks in. So, we spread them out a bit
// initially, to provide a more serene layout convergence.
// Additionally, if the node is a host, we place it near
// the device it is connected to.
function spread(s) {
return Math.floor((Math.random() * s) - s/2);
}
function randDim(dim) {
return dim / 2 + spread(dim * 0.7071);
}
function rand() {
return {
x: randDim(width),
y: randDim(height)
};
}
function near(node) {
var min = 12,
dx = spread(12),
dy = spread(12);
return {
x: node.x + min + dx,
y: node.y + min + dy
};
}
function getDevice(cp) {
var d = lu[cp.device];
return d || rand();
}
xy = (node.class === 'host') ? near(getDevice(node.cp)) : rand();
angular.extend(node, xy);
}
function createDeviceNode(device) {
// start with the object as is
var node = device,
type = device.type,
svgCls = type ? 'node device ' + type : 'node device';
// Augment as needed...
node.class = 'device';
node.svgClass = device.online ? svgCls + ' online' : svgCls;
positionNode(node);
return node;
}
function createHostNode(host) {
var node = host;
// Augment as needed...
node.class = 'host';
if (!node.type) {
node.type = 'endstation';
}
node.svgClass = 'node host ' + node.type;
positionNode(node);
return node;
}
function createHostLink(host) {
var src = host.id,
dst = host.cp.device,
id = host.ingress,
lnk = linkEndPoints(src, dst);
if (!lnk) {
return null;
}
// Synthesize link ...
angular.extend(lnk, {
key: id,
class: 'link',
type: function () { return 'hostLink'; },
online: function () {
// hostlink target is edge switch
return lnk.target.online;
},
linkWidth: function () { return 1; }
});
return lnk;
}
function linkEndPoints(srcId, dstId) {
var srcNode = lu[srcId],
dstNode = lu[dstId],
sMiss = !srcNode ? missMsg('src', srcId) : '',
dMiss = !dstNode ? missMsg('dst', dstId) : '';
if (sMiss || dMiss) {
$log.error('Node(s) not on map for link:\n' + sMiss + dMiss);
//logicError('Node(s) not on map for link:\n' + sMiss + dMiss);
return null;
}
return {
source: srcNode,
target: dstNode,
x1: srcNode.x,
y1: srcNode.y,
x2: dstNode.x,
y2: dstNode.y
};
}
function missMsg(what, id) {
return '\n[' + what + '] "' + id + '" missing ';
}
// ==========================
// === Devices and hosts - D3 rendering
function nodeMouseOver(m) {
// TODO
$log.debug("TODO nodeMouseOver()...", m);
}
function nodeMouseOut(m) {
// TODO
$log.debug("TODO nodeMouseOut()...", m);
}
// Returns the newly computed bounding box of the rectangle
function adjustRectToFitText(n) {
var text = n.select('text'),
box = text.node().getBBox(),
lab = labelConfig;
text.attr('text-anchor', 'middle')
.attr('y', '-0.8em')
.attr('x', lab.imgPad/2);
// translate the bbox so that it is centered on [x,y]
box.x = -box.width / 2;
box.y = -box.height / 2;
// add padding
box.x -= (lab.padLR + lab.imgPad/2);
box.width += lab.padLR * 2 + lab.imgPad;
box.y -= lab.padTB;
box.height += lab.padTB * 2;
return box;
}
function mkSvgClass(d) {
return d.fixed ? d.svgClass + ' fixed' : d.svgClass;
}
function hostLabel(d) {
var idx = (hostLabelIndex < d.labels.length) ? hostLabelIndex : 0;
return d.labels[idx];
}
function deviceLabel(d) {
var idx = (deviceLabelIndex < d.labels.length) ? deviceLabelIndex : 0;
return d.labels[idx];
}
function trimLabel(label) {
return (label && label.trim()) || '';
}
function emptyBox() {
return {
x: -2,
y: -2,
width: 4,
height: 4
};
}
function updateDeviceLabel(d) {
var label = trimLabel(deviceLabel(d)),
noLabel = !label,
node = d.el,
dim = icfg.device.dim,
devCfg = deviceIconConfig,
box, dx, dy;
node.select('text')
.text(label)
.style('opacity', 0)
.transition()
.style('opacity', 1);
if (noLabel) {
box = emptyBox();
dx = -dim/2;
dy = -dim/2;
} else {
box = adjustRectToFitText(node);
dx = box.x + devCfg.xoff;
dy = box.y + devCfg.yoff;
}
node.select('rect')
.transition()
.attr(box);
node.select('g.deviceIcon')
.transition()
.attr('transform', sus.translate(dx, dy));
}
function updateHostLabel(d) {
var label = trimLabel(hostLabel(d));
d.el.select('text').text(label);
}
function updateDeviceColors(d) {
if (d) {
setDeviceColor(d);
} else {
node.filter('.device').each(function (d) {
setDeviceColor(d);
});
}
}
function vis(b) {
return b ? 'visible' : 'hidden';
}
function toggleHosts() {
showHosts = !showHosts;
updateHostVisibility();
flash.flash('Hosts ' + vis(showHosts));
}
function toggleOffline() {
showOffline = !showOffline;
updateOfflineVisibility();
flash.flash('Offline devices ' + vis(showOffline));
}
function cycleDeviceLabels() {
deviceLabelIndex = (deviceLabelIndex+1) % 3;
findDevices().forEach(function (d) {
updateDeviceLabel(d);
});
}
// ==========================================
var dCol = {
black: '#000',
paleblue: '#acf',
offwhite: '#ddd',
darkgrey: '#444',
midgrey: '#888',
lightgrey: '#bbb',
orange: '#f90'
};
// note: these are the device icon colors without affinity
var dColTheme = {
light: {
rfill: dCol.offwhite,
online: {
glyph: dCol.darkgrey,
rect: dCol.paleblue
},
offline: {
glyph: dCol.midgrey,
rect: dCol.lightgrey
}
},
dark: {
rfill: dCol.midgrey,
online: {
glyph: dCol.darkgrey,
rect: dCol.paleblue
},
offline: {
glyph: dCol.midgrey,
rect: dCol.darkgrey
}
}
};
function devBaseColor(d) {
var o = d.online ? 'online' : 'offline';
return dColTheme[ts.theme()][o];
}
function setDeviceColor(d) {
var o = d.online,
s = d.el.classed('selected'),
c = devBaseColor(d),
a = instColor(d.master, o),
icon = d.el.select('g.deviceIcon'),
g, r;
if (s) {
g = c.glyph;
r = dCol.orange;
} else if (tis.isVisible()) {
g = o ? a : c.glyph;
r = o ? c.rfill : a;
} else {
g = c.glyph;
r = c.rect;
}
icon.select('use').style('fill', g);
icon.select('rect').style('fill', r);
}
function instColor(id, online) {
return sus.cat7().getColor(id, !online, ts.theme());
}
// ==========================
function updateNodes() {
// select all the nodes in the layout:
node = nodeG.selectAll('.node')
.data(network.nodes, function (d) { return d.id; });
// operate on existing nodes:
node.filter('.device').each(deviceExisting);
node.filter('.host').each(hostExisting);
// operate on entering nodes:
var entering = node.enter()
.append('g')
.attr({
id: function (d) { return sus.safeId(d.id); },
class: mkSvgClass,
transform: function (d) { return sus.translate(d.x, d.y); },
opacity: 0
})
.call(drag)
.on('mouseover', nodeMouseOver)
.on('mouseout', nodeMouseOut)
.transition()
.attr('opacity', 1);
// augment entering nodes:
entering.filter('.device').each(deviceEnter);
entering.filter('.host').each(hostEnter);
// operate on both existing and new nodes:
updateDeviceColors();
// operate on exiting nodes:
// Note that the node is removed after 2 seconds.
// Sub element animations should be shorter than 2 seconds.
var exiting = node.exit()
.transition()
.duration(2000)
.style('opacity', 0)
.remove();
// exiting node specifics:
exiting.filter('.host').each(hostExit);
exiting.filter('.device').each(deviceExit);
// finally, resume the force layout
fResume();
}
// ==========================
// updateNodes - subfunctions
function deviceExisting(d) {
var node = d.el;
node.classed('online', d.online);
updateDeviceLabel(d);
positionNode(d, true);
}
function hostExisting(d) {
updateHostLabel(d);
positionNode(d, true);
}
function deviceEnter(d) {
var node = d3.select(this),
glyphId = d.type || 'unknown',
label = trimLabel(deviceLabel(d)),
devCfg = deviceIconConfig,
noLabel = !label,
box, dx, dy, icon;
d.el = node;
node.append('rect').attr({ rx: 5, ry: 5 });
node.append('text').text(label).attr('dy', '1.1em');
box = adjustRectToFitText(node);
node.select('rect').attr(box);
icon = is.addDeviceIcon(node, glyphId);
if (noLabel) {
dx = -icon.dim/2;
dy = -icon.dim/2;
} else {
box = adjustRectToFitText(node);
dx = box.x + devCfg.xoff;
dy = box.y + devCfg.yoff;
}
icon.attr('transform', sus.translate(dx, dy));
}
function hostEnter(d) {
var node = d3.select(this),
gid = d.type || 'unknown',
rad = icfg.host.radius,
r = d.type ? rad.withGlyph : rad.noGlyph,
textDy = r + 10;
d.el = node;
sus.makeVisible(node, showHosts);
is.addHostIcon(node, r, gid);
node.append('text')
.text(hostLabel)
.attr('dy', textDy)
.attr('text-anchor', 'middle');
}
function hostExit(d) {
var node = d.el;
node.select('use')
.style('opacity', 0.5)
.transition()
.duration(800)
.style('opacity', 0);
node.select('text')
.style('opacity', 0.5)
.transition()
.duration(800)
.style('opacity', 0);
node.select('circle')
.style('stroke-fill', '#555')
.style('fill', '#888')
.style('opacity', 0.5)
.transition()
.duration(1500)
.attr('r', 0);
}
function deviceExit(d) {
var node = d.el;
node.select('use')
.style('opacity', 0.5)
.transition()
.duration(800)
.style('opacity', 0);
node.selectAll('rect')
.style('stroke-fill', '#555')
.style('fill', '#888')
.style('opacity', 0.5);
}
// ==========================
function updateLinks() {
var th = ts.theme();
link = linkG.selectAll('.link')
.data(network.links, function (d) { return d.key; });
// operate on existing links:
//link.each(linkExisting);
// operate on entering links:
var entering = link.enter()
.append('line')
.attr({
x1: function (d) { return d.x1; },
y1: function (d) { return d.y1; },
x2: function (d) { return d.x2; },
y2: function (d) { return d.y2; },
stroke: linkConfig[th].inColor,
'stroke-width': linkConfig.inWidth
});
// augment links
entering.each(linkEntering);
// operate on both existing and new links:
//link.each(...)
// apply or remove labels
var labelData = getLabelData();
applyLinkLabels(labelData);
// operate on exiting links:
link.exit()
.attr('stroke-dasharray', '3 3')
.attr('stroke', linkConfig[th].outColor)
.style('opacity', 0.5)
.transition()
.duration(1500)
.attr({
'stroke-dasharray': '3 12',
'stroke-width': linkConfig.outWidth
})
.style('opacity', 0.0)
.remove();
// NOTE: invoke a single tick to force the labels to position
// onto their links.
tick();
// TODO: this causes undesirable behavior when in oblique view
// It causes the nodes to jump into "overhead" view positions, even
// though the oblique planes are still showing...
}
// ==========================
// updateLinks - subfunctions
function getLabelData() {
// create the backing data for showing labels..
var data = [];
link.each(function (d) {
if (d.label) {
data.push({
id: 'lab-' + d.key,
key: d.key,
label: d.label,
ldata: d
});
}
});
return data;
}
//function linkExisting(d) { }
function linkEntering(d) {
var link = d3.select(this);
d.el = link;
restyleLinkElement(d);
if (d.type() === 'hostLink') {
sus.makeVisible(link, showHosts);
}
}
//function linkExiting(d) { }
var linkLabelOffset = '0.3em';
function applyLinkLabels(data) {
var entering;
linkLabel = linkLabelG.selectAll('.linkLabel')
.data(data, function (d) { return d.id; });
// for elements already existing, we need to update the text
// and adjust the rectangle size to fit
linkLabel.each(function (d) {
var el = d3.select(this),
rect = el.select('rect'),
text = el.select('text');
text.text(d.label);
rect.attr(rectAroundText(el));
});
entering = linkLabel.enter().append('g')
.classed('linkLabel', true)
.attr('id', function (d) { return d.id; });
entering.each(function (d) {
var el = d3.select(this),
rect,
text,
parms = {
x1: d.ldata.x1,
y1: d.ldata.y1,
x2: d.ldata.x2,
y2: d.ldata.y2
};
d.el = el;
rect = el.append('rect');
text = el.append('text').text(d.label);
rect.attr(rectAroundText(el));
text.attr('dy', linkLabelOffset);
el.attr('transform', transformLabel(parms));
});
// Remove any labels that are no longer required.
linkLabel.exit().remove();
}
function rectAroundText(el) {
var text = el.select('text'),
box = text.node().getBBox();
// translate the bbox so that it is centered on [x,y]
box.x = -box.width / 2;
box.y = -box.height / 2;
// add padding
box.x -= 1;
box.width += 2;
return box;
}
function transformLabel(p) {
var dx = p.x2 - p.x1,
dy = p.y2 - p.y1,
xMid = dx/2 + p.x1,
yMid = dy/2 + p.y1;
return sus.translate(xMid, yMid);
}
// ==========================
// force layout tick function
function fResume() {
if (!oblique) {
force.resume();
}
}
function fStart() {
if (!oblique) {
force.start();
}
}
var tickStuff = {
nodeAttr: {
transform: function (d) { return sus.translate(d.x, d.y); }
},
linkAttr: {
x1: function (d) { return d.source.x; },
y1: function (d) { return d.source.y; },
x2: function (d) { return d.target.x; },
y2: function (d) { return d.target.y; }
},
linkLabelAttr: {
transform: function (d) {
var lnk = findLinkById(d.key);
if (lnk) {
return transformLabel({
x1: lnk.source.x,
y1: lnk.source.y,
x2: lnk.target.x,
y2: lnk.target.y
});
}
}
}
};
function tick() {
node.attr(tickStuff.nodeAttr);
link.attr(tickStuff.linkAttr);
linkLabel.attr(tickStuff.linkLabelAttr);
}
// ==========================
// === MOUSE GESTURE HANDLERS
// FIXME:
function selectCb() { }
function atDragEnd() {}
function dragEnabled() {}
function clickEnabled() {}
// ==========================
// Module definition
angular.module('ovTopo')
.factory('TopoForceService',
['$log', 'FnService', 'SvgUtilService', 'IconService', 'ThemeService',
'FlashService', 'TopoInstService',
function (_$log_, _fs_, _sus_, _is_, _ts_, _flash_, _tis_) {
$log = _$log_;
fs = _fs_;
sus = _sus_;
is = _is_;
ts = _ts_;
flash = _flash_;
tis = _tis_;
icfg = is.iconConfig();
// forceG is the SVG group to display the force layout in
// xlink is the cross-link api from the main topo source file
// w, h are the initial dimensions of the SVG
// opts are, well, optional :)
function initForce(forceG, _uplink_, w, h, opts) {
$log.debug('initForce().. WxH = ' + w + 'x' + h);
uplink = _uplink_;
width = w;
height = h;
settings = angular.extend({}, defaultSettings, opts);
linkG = forceG.append('g').attr('id', 'topo-links');
linkLabelG = forceG.append('g').attr('id', 'topo-linkLabels');
nodeG = forceG.append('g').attr('id', 'topo-nodes');
link = linkG.selectAll('.link');
linkLabel = linkLabelG.selectAll('.linkLabel');
node = nodeG.selectAll('.node');
force = d3.layout.force()
.size([w, h])
.nodes(network.nodes)
.links(network.links)
.gravity(settings.gravity)
.friction(settings.friction)
.charge(settings.charge._def_)
.linkDistance(settings.linkDistance._def_)
.linkStrength(settings.linkStrength._def_)
.on('tick', tick);
drag = sus.createDragBehavior(force,
selectCb, atDragEnd, dragEnabled, clickEnabled);
}
function resize(dim) {
width = dim.width;
height = dim.height;
force.size([width, height]);
// Review -- do we need to nudge the layout ?
}
return {
initForce: initForce,
resize: resize,
updateDeviceColors: updateDeviceColors,
toggleHosts: toggleHosts,
toggleOffline: toggleOffline,
cycleDeviceLabels: cycleDeviceLabels,
addDevice: addDevice,
updateDevice: updateDevice,
removeDevice: removeDevice,
addHost: addHost,
updateHost: updateHost,
removeHost: removeHost,
addLink: addLink,
updateLink: updateLink,
removeLink: removeLink
};
}]);
}());