├── README.md
├── example-complex.htm
├── example-complex.js
├── example-simple.htm
├── example-simple.js
├── graph
├── DirectedGraphLayout.js
├── SvgRenderer.js
├── gpl.txt
├── pathFinder.js
├── resources
│ ├── dgraph.css
│ ├── example-complex.gif
│ └── example.css
└── svgCssUtil.js
└── package.json
/README.md:
--------------------------------------------------------------------------------
1 | dGraph
2 | ======
3 |
4 | Create layered directed graphs in SVG with a few lines of JS in a beautiful and compact layout. The library is based on
5 | a modified [Sugiyama algorithm](http://en.wikipedia.org/wiki/Kozo_Sugiyama "Kozo Sugiyama"). The data feed into the graph
6 | library needs to be a node list with its corresponding adjacency list. Each node object in the list is expected to have
7 | at least the two properties 'label' and 'layer'. See the two provided example pages
8 | [example-simple.htm](example-simple.htm) and [example-complex.htm](example-complex.htm) for more information.
9 |
10 | 
11 |
12 | ## History
13 | Originally developed for the Data Analysis Software NAFIDAS of the [Swiss National Forest Inventory](http://www.lfi.ch/index-en.php)
14 | to visualize dependencies of database variables.
15 |
16 | ## Features
17 | * Client side rendering of the graph in SVG.
18 | * Mesh size of the grid can be set.
19 | * Grid lines can be set to visible or hidden.
20 | * Graph can be compacted to save space on the screen (default).
21 | * Simple data format consisting of a node list and an adjacency list.
22 | * Graph can be inverted, e.g. order of layers in graph is reversed.
23 | * Highlight connected parent and/or child nodes
24 |
25 | ## Dependencies
26 | * none, uses only native JS
27 |
28 | ## Installation
29 | See the two example pages [example-simple.htm](example-simple.htm) and [example-complex.htm](example-complex.htm)
30 |
31 | ## Licence
32 | GNU GENERAL PUBLIC LICENSE v3
--------------------------------------------------------------------------------
/example-complex.htm:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Example of a complex Layered DirectedGraph
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/example-complex.js:
--------------------------------------------------------------------------------
1 | import {DirectedGraphLayout} from "./graph/DirectedGraphLayout.js";
2 | import {SvgRenderer} from "./graph/SvgRenderer.js";
3 |
4 | let graph, svg,
5 | graphData = {
6 | numLayer: 10, maxPerLayer: 3, nodeList: [
7 | {label: 'Turdus', layer: 0},
8 | {label: 'Parus', layer: 0},
9 | {label: 'Falco', layer: 0},
10 | {label: 'Rubecula', layer: 0},
11 | {label: 'Corvus', layer: 0},
12 | {label: 'Sturnus', layer: 0},
13 | {label: 'Mycteria', layer: 0},
14 | {label: 'Ciconia', layer: 0},
15 | {label: 'Cygnus', layer: 0},
16 | {label: 'Cathartes', layer: 0},
17 | {label: 'Anas', layer: 0},
18 | {label: 'Atticora', layer: 0},
19 | {label: 'Hirundo', layer: 0},
20 | {label: 'Jabiru', layer: 0},
21 | {label: 'Ara', layer: 0},
22 | {label: 'Fringilla', layer: 0},
23 | {label: 'ZUGANG', layer: 0},
24 | {label: 'Tigrisoma', layer: 1},
25 | {label: 'UMFANG', layer: 1},
26 | {label: 'Harpia', layer: 9},
27 | {label: 'Rynchops', layer: 3},
28 | {label: 'Larus', layer: 4},
29 | {label: 'Troglodytes', layer: 1},
30 | {label: 'Anthracothorax', layer: 5},
31 | {label: 'Pandion', layer: 1},
32 | {label: 'Egretta', layer: 1},
33 | {label: 'Thryothorus', layer: 6},
34 | {label: 'Ciconia', layer: 1},
35 | {label: 'Athene', layer: 8},
36 | {label: 'Anhinga', layer: 7},
37 | {label: 'Philomachus', layer: 7},
38 | {label: 'Tetrao', layer: 1},
39 | {label: 'Podiceps', layer: 1},
40 | {label: 'Poecile', layer: 4},
41 | {label: 'Asio', layer: 1},
42 | {label: 'Strix', layer: 2},
43 | {label: 'Hippophae', layer: 1},
44 | {label: 'Silvia', layer: 2},
45 | {label: 'Columba', layer: 1},
46 | {label: 'Lanius', layer: 1},
47 | {label: 'Merganser', layer: 1},
48 | {label: 'Anser', layer: 1},
49 | {label: 'Eudocimus', layer: 1},
50 | {label: 'Catoptrophorus', layer: 1},
51 | {label: 'Pluvialis', layer: 1},
52 | {label: 'Aythya', layer: 1},
53 | {label: 'Cinclus', layer: 3}
54 | ], adjList: [
55 | [39],
56 | [41],
57 | [33, 45, 46],
58 | [36, 42],
59 | [36, 43],
60 | [36, 44],
61 | [38, 40],
62 | [38, 40],
63 | [17],
64 | [24],
65 | [34],
66 | [27],
67 | [25],
68 | [18],
69 | [22],
70 | [32],
71 | [31],
72 | [23],
73 | [35],
74 | [],
75 | [21, 28, 29],
76 | [28],
77 | [28],
78 | [26],
79 | [21, 29, 30],
80 | [28, 29, 30],
81 | [28, 29, 30],
82 | [20, 30],
83 | [19],
84 | [28],
85 | [28],
86 | [26],
87 | [23],
88 | [23],
89 | [35],
90 | [20],
91 | [37, 46],
92 | [46],
93 | [46],
94 | [46],
95 | [46],
96 | [46],
97 | [46],
98 | [46],
99 | [46],
100 | [46],
101 | [33]
102 | ]
103 | };
104 |
105 | graph = new DirectedGraphLayout({
106 | numLayer: graphData.numLayer
107 | });
108 | svg = new SvgRenderer({
109 | canvas: 'graphCanvas',
110 | gridSize: {
111 | meshWidth: 84,
112 | meshHeight: 66
113 | },
114 | // renderGrid: false
115 | });
116 |
117 | graph.render(graphData);
118 | svg.render(graph);
--------------------------------------------------------------------------------
/example-simple.htm:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Example of a simple Layered DirectedGraph
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/example-simple.js:
--------------------------------------------------------------------------------
1 | import {DirectedGraphLayout} from "./graph/DirectedGraphLayout.js";
2 | import {SvgRenderer} from "./graph/SvgRenderer.js";
3 |
4 | let graph, svg,
5 | graphData = {
6 | numLayer: 4,
7 | maxPerLayer: 2,
8 | nodeList: [
9 | {label: 'Rubecula', layer: 0},
10 | {label: 'Turdus', layer: 3},
11 | {label: 'Corvus', layer: 1},
12 | {label: 'Falco', layer: 1},
13 | {label: 'Cathartes', layer: 2},
14 | {label: 'Parus', layer: 0}
15 | ],
16 | adjList: [
17 | [2, 3, 4],
18 | [],
19 | [1],
20 | [],
21 | [],
22 | [2]
23 | ]
24 | };
25 |
26 | graph = new DirectedGraphLayout({
27 | numLayer: graphData.numLayer,
28 | compacted: false
29 | });
30 | svg = new SvgRenderer({
31 | canvas: 'graphCanvas',
32 | gridSize: {
33 | meshWidth: 100,
34 | meshHeight: 100
35 | }
36 | });
37 |
38 | graph.render(graphData);
39 | svg.render(graph);
--------------------------------------------------------------------------------
/graph/DirectedGraphLayout.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Generate a directed graph layout using a Sugiyama algorithm.
3 | * @copyright Simon Speich 2013
4 | *
5 | * @license
6 | * This file is part of the DirectedGraph library.
7 | *
8 | * The DirectedGraph library is free software: you can redistribute it and/or modify
9 | * it under the terms of the GNU General Public License as published by
10 | * the Free Software Foundation, either version 3 of the License, or
11 | * (at your option) any later version.
12 | *
13 | * The DirectedGraph library is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | * GNU General Public License for more details.
17 | *
18 | * You should have received a copy of the GNU General Public License
19 | * along with DirectedGraph Application. If not, see .
20 | *
21 | * written for Swiss Federal Institute for Forest, Snow and Landscape Research WSL
22 | *
23 | * @note The methods expandNodeList(), splitLongEdges() orderLayer(), and updateEdgeIndexes()
24 | * work only with integers. Compacting the graph with compact allows for x values smaller
25 | * than unit size one. Therefore the order of applying these methods is important.
26 | *
27 | * @class module:dgraph/DirectedGraphLayout
28 | */
29 | export class DirectedGraphLayout {
30 |
31 | /**
32 | * @typedef {Object} graphNode
33 | * @property {Number} x x-coordinate of unit length
34 | * @property {Number} y y-coordinate of unit length
35 | * @property {Number} lx x-coordinate of layout
36 | * @property {Number} ly y-coordinate of layout
37 | * @property {Array} trgNodes list of adjacent target nodes
38 | * @property {Array} srcNodes list of adjacent source nodes
39 | * @property {Number} wUpper weight of target nodes (upper nodes),
40 | * @property {Number} wLower weight of source nodes {lower nodes),
41 | * @property {Boolean} virt is node virtual
42 | * @property {String} label label to display at node
43 | * @property {Boolean} isRaw is node from raw data or derived data
44 | * @property {Boolean} selected is node selected (base node of graph)
45 | */
46 | constructor(args) {
47 |
48 | /* NOTES:
49 | * Remember that in js arrays are passed by reference and so are objects.
50 | * There is a tradeoff between separation of logic and performance:
51 | * More separation means looping through the same loops again which reduces performance but plays nice with memory
52 | */
53 |
54 | /**
55 | * number of layers in graph
56 | * @member {Number}
57 | */
58 | this.numLayer = 0;
59 |
60 | /**
61 | * maximum number of nodes on all layers
62 | * @member Number}
63 | */
64 | this.maxNodesAllLayers = 0;
65 |
66 | /**
67 | * fast lookup to assign new x coordinates for virtual nodes
68 | * @member {Array}
69 | */
70 | this.numPerLayers = null;
71 |
72 | /**
73 | * holds graph nodes. NOTE: first dim is y, second is x!
74 | * @member {Array}
75 | */
76 | this.nodes = null;
77 |
78 | /**
79 | * Increment between virtual nodes when setting layout position. 1/incVirt has to be an integer.
80 | * @member {Number}
81 | * @default
82 | */
83 | this.incVirt = 0.2;
84 |
85 | /**
86 | * Increment between nodes when setting layout position.
87 | * @member {Number}
88 | * @default
89 | */
90 | this.inc = 1;
91 |
92 | /**
93 | * number of passes when compacting graph
94 | * @member {Number}
95 | * @default
96 | */
97 | this.numRepeat = 20;
98 |
99 | /**
100 | * compact graph
101 | * @member {Boolean}
102 | * @default
103 | */
104 | this.compacted = true;
105 | this.nodes = [];
106 | this.numPerLayers = [];
107 | Object.assign(this, args);
108 | }
109 |
110 | /**
111 | * Maps the list of nodes to a two dim array the size of the grid.
112 | * Nodes are stored as xy vectors of the grid. The grid is
113 | * maxNodesAllLayers x numLayer and dynamically extended with virtual nodes
114 | * when splitting long edges.
115 | * TODO: remove unused property isRaw
116 | * @param {Array} nodeList list with nodes
117 | */
118 | initNodeList(nodeList) {
119 | let i, len, layer, col, node;
120 |
121 | len = nodeList.length;
122 | for (i = 0; i < len; i++) {
123 | layer = nodeList[i].layer;
124 | if (this.nodes[layer] === undefined) {
125 | this.nodes[layer] = [];
126 | }
127 | col = this.nodes[layer].length;
128 | node = this.createNode({
129 | x: col,
130 | y: layer,
131 | virt: false,
132 | label: nodeList[i].label,
133 | isRaw: nodeList[i].isRaw,
134 | id: nodeList[i].id,
135 | selected: nodeList[i].selected
136 | });
137 | this.nodes[layer][col] = node; // internal node list for fast lookup in grid
138 | nodeList[i].node = node; // needed to be able to update trgNodes further below (addEdges())
139 | this.numPerLayers[layer] = col + 1;
140 | // get maximum grid width
141 | this.maxNodesAllLayers = this.numPerLayers[layer] > this.maxNodesAllLayers ? this.numPerLayers[layer]: this.maxNodesAllLayers;
142 | }
143 | len = this.nodes.length;
144 | for (i = 0; i < len; i++) {
145 | if (this.nodes[i] === undefined) {
146 | this.nodes[i] = [];
147 | }
148 | }
149 | len = this.numPerLayers.length;
150 | for (i = 0; i < len; i++) {
151 | if (this.numPerLayers[i] === undefined) {
152 | this.numPerLayers[i] = 0;
153 | }
154 | }
155 | }
156 |
157 | /**
158 | * Adds a node's edges.
159 | * Adds a node's neighbours as a list of array indexes of source and target nodes.
160 | * @param {Array} nodeList list with nodes
161 | * @param {Array} adjList list list of adjacent node indexes
162 | */
163 | addEdges(nodeList, adjList) {
164 | let i, j, len, lenJ, target, source,
165 | trgNodes, tx, ty, sx, sy;
166 |
167 | len = adjList.length;
168 | for (i = 0; i < len; i++) {
169 | if (adjList[i].length > 0) {
170 | trgNodes = adjList[i];
171 | lenJ = trgNodes.length;
172 | for (j = 0; j < lenJ; j++) {
173 | target = nodeList[trgNodes[j]].node;
174 | tx = target.x;
175 | ty = target.y;
176 | source = nodeList[i].node; // get target's source nodes
177 | sx = source.x;
178 | sy = source.y;
179 | this.nodes[sy][sx].trgNodes.push([tx, ty]);
180 | // also add this node to the source list of the edge
181 | this.nodes[ty][tx].srcNodes.push([sx, sy]);
182 | }
183 | }
184 | }
185 | }
186 |
187 | /**
188 | * Sets the weight of all node'.
189 | * A node's weight is either based on up-neighbours
190 | * or down-neighbours median.
191 | */
192 | setNodeWeights() {
193 | let i, len, w, l, node;
194 |
195 | len = this.nodes.length;
196 | for (i = 0; i < len; i++) {
197 | l = this.nodes[i].length;
198 | for (w = 0; w < l; w++) {
199 | node = this.nodes[i][w];
200 | if (node.srcNodes.length > 0) {
201 | node.wUpper = this.getMedian(node, 'upper');
202 | }
203 | if (node.trgNodes.length > 0) {
204 | node.wLower = this.getMedian(node, 'lower');
205 | }
206 | }
207 | }
208 | }
209 |
210 | /**
211 | * Adds virtual (dummy) nodes and edges to the node list.
212 | */
213 | expandNodeList() {
214 | let i, j, numRow, numCol, node;
215 |
216 | numRow = this.nodes.length;
217 | for (i = 0; i < numRow; i++) {
218 | numCol = this.nodes[i].length;
219 | for (j = 0; j < numCol; j++) {
220 | node = this.nodes[i][j];
221 | if (!node.virt && node.trgNodes.length > 0) {
222 | this.splitLongEdges(node);
223 | }
224 | }
225 | }
226 | this.setNodeWeights();
227 | }
228 |
229 | /**
230 | * Inserts virtual nodes and edges to create a proper graph.
231 | * Edges spanning more than one layer will be split into multiple edges of unit length.
232 | * This is done by shortening, e.g decrementing long edges continuously until it has unit length.
233 | * @param {graphNode} srcNode source node
234 | */
235 | splitLongEdges(srcNode) {
236 | let f, lenF, w, l,
237 | lastVirtNode, trgNode, trgNodes, span, origTrgNode, node, newNode;
238 |
239 | trgNodes = srcNode.trgNodes;
240 | l = trgNodes.length;
241 | for (w = 0; w < l; w++) {
242 | lastVirtNode = null;
243 | trgNode = {
244 | x: trgNodes[w][0],
245 | y: trgNodes[w][1]
246 | };
247 |
248 | span = trgNode.y - srcNode.y;
249 | // skip short edges of unit length
250 | if (span === 1) {
251 | continue;
252 | }
253 | span--; // We do not need to crate a new node for the original targetNode,
254 | while (span > 0) {
255 | /**** APPEND virtual nodes and edges ***/
256 | newNode = this.createVirtualNode(srcNode, trgNode, span);
257 | if (!lastVirtNode) {
258 | lastVirtNode = newNode;
259 | }
260 | if (this.nodes[newNode.y] === undefined) {
261 | this.nodes[newNode.y] = [newNode];
262 | }
263 | else {
264 | this.nodes[newNode.y].push(newNode);
265 | }
266 | // update maximum number of nodes per layer to know width of canvas
267 | this.numPerLayers[newNode.y]++;
268 | if (this.numPerLayers[newNode.y] > this.maxNodesAllLayers) {
269 | this.maxNodesAllLayers++;
270 | }
271 | span--;
272 | }
273 | // update original targetNode's srcNode to point to first inserted new node
274 | origTrgNode = trgNodes[w];
275 | origTrgNode = this.nodes[origTrgNode[1]][origTrgNode[0]];
276 | lenF = origTrgNode.srcNodes.length;
277 | for (f = 0; f < lenF; f++) { // find right srcNode to update
278 | node = origTrgNode.srcNodes[f];
279 | if (node[0] === srcNode.x && node[1] === srcNode.y) {
280 | origTrgNode.srcNodes[f][0] = lastVirtNode.x;
281 | origTrgNode.srcNodes[f][1] = lastVirtNode.y;
282 | break;
283 | }
284 | }
285 | // update srcNode's original targetNode to point to last inserted new node
286 | // note: do this after updating original target's srcNode, otherwise it is overwritten by newNode
287 | srcNode.trgNodes[w] = [newNode.x, newNode.y];
288 | }
289 | }
290 |
291 | /**
292 | * Creates and returns a graphNode.
293 | * @param {Object} params node parameter
294 | * @property {Number} x x-coordinate of unit length
295 | * @property {Number} y y-coordinate of unit length
296 | * @property {Number} lx x-coordinate of layout
297 | * @property {Number} ly y-coordinate of layout
298 | * @property {Array} trgNodes list of adjacent target nodes
299 | * @property {Array} srcNodes list of adjacent source nodes
300 | * @property {Number} wUpper weight of target nodes (upper nodes),
301 | * @property {Number} wLower weight of source nodes {lower nodes),
302 | * @property {Boolean} virt is node virtual
303 | * @property {String} label label to display at node
304 | * @property {Boolean} isRaw is node from raw data or derived data
305 | * @property {Boolean} selected is node selected (base node of graph)
306 | * @returns {graphNode}
307 | */
308 | createNode(params) {
309 | let graphNode = {
310 | x: 'x' in params ? params.x: 0,
311 | y: 'y' in params ? params.y: 0,
312 | lx: 'lx' in params ? params.lx: ('x' in params ? params.x: 0),
313 | ly: 'ly' in params ? params.ly: ('y' in params ? params.y: 0),
314 | trgNodes: 'trgNodes' in params ? [params.trgNodes]: [],
315 | srcNodes: 'srcNodes' in params ? [params.srcNodes]: [],
316 | wUpper: 'wUpper' in params ? params.wUpper: null,
317 | wLower: 'wLower' in params ? params.wLower: null,
318 | virt: 'virt' in params ? params.virt: false,
319 | label: 'label' in params ? params.label: false,
320 | isRaw: 'isRaw' in params ? params.isRaw: false,
321 | selected: 'selected' in params ? params.selected: false
322 | };
323 |
324 | if ('id' in params) {
325 | graphNode.id = params.id;
326 | }
327 |
328 | return graphNode;
329 | }
330 |
331 | /**
332 | * Creates a new virtual node.
333 | * New virtual nodes are appended to the layer, e.g x equals number of nodes on this layer
334 | * @param {graphNode} srcNode source node
335 | * @param {graphNode} trgNode target node
336 | * @param {Number} span length of span in unit length
337 | * @returns {graphNode}
338 | */
339 | createVirtualNode(srcNode, trgNode, span) {
340 | // we have 4 cases: target is a VirtualNode
341 | // target is originalTarget
342 | // source is virtual
343 | // source is originalSource
344 | let target, source, curLayer, x;
345 |
346 | curLayer = srcNode.y + span;
347 | if (curLayer === trgNode.y - 1) { // second new node has original target node as target
348 | target = [trgNode.x, trgNode.y];
349 | }
350 | else {
351 | target = [this.numPerLayers[curLayer + 1] - 1, curLayer + 1];
352 | }
353 | if (span === 1) { // second to last has original source as source
354 | source = [srcNode.x, srcNode.y];
355 | }
356 | else {
357 | source = [this.numPerLayers[curLayer - 1], curLayer - 1];
358 | }
359 | x = this.numPerLayers[curLayer];
360 |
361 | return this.createNode({
362 | x: x,
363 | y: curLayer,
364 | trgNodes: target,
365 | srcNodes: source,
366 | virt: true,
367 | label: null,
368 | isRaw: false
369 | });
370 | }
371 |
372 | /**
373 | * Counts the number of edge crossings of a layer's nodes.
374 | * Compares the x-values of a node's edges with all the x-edges
375 | * of the following nodes on that layer.
376 | * @param {Array} layer layer's nodes
377 | * @param {Number} direction
378 | * @return {Number} number of crossings
379 | */
380 | countCrossings(layer, direction) {
381 | let propName = direction === 'up' ? 'trgNodes': 'srcNodes',
382 | nodes = this.nodes[layer],
383 | i, lenI, numCross = 0,
384 | w, lenW, edges, edge1, edge2, node1, node2,
385 | p, lenP, z;
386 |
387 | lenI = nodes.length;
388 | // loop nodes
389 | for (i = 0; i < lenI; i++) {
390 | node1 = nodes[i];
391 | edges = node1[propName];
392 | lenW = edges.length;
393 | // loop node's targets
394 | for (w = 0; w < lenW; w++) {
395 | edge1 = edges[w];
396 | edge1 = this.nodes[edge1[1]][edge1[0]];
397 | // compare
398 | z = i + 1;
399 | for (z; z < lenI; z++) {
400 | node2 = nodes[z];
401 | lenP = node2[propName].length;
402 | for (p = 0; p < lenP; p++) {
403 | edge2 = node2[propName][p];
404 | edge2 = this.nodes[edge2[1]][edge2[0]];
405 | if (edge1.x > edge2.x) {
406 | numCross++;
407 | }
408 | }
409 | }
410 | }
411 | }
412 |
413 | return numCross;
414 | }
415 |
416 | /**
417 | * Minimize number of crossings between layers.
418 | * Important: We only manipulate the x and y properties,
419 | * when finding right ordering of nodes, the lookup properties
420 | * srcNodes and trgNodes are kept unchanged. Otherwise we
421 | * would have to do a lot of updating these lists.
422 | * numSweep: Up and down counts as one sweep
423 | * @param {Number} [numRepeat] number of sweeps
424 | */
425 | minimizeCrossings(numRepeat) {
426 | numRepeat = numRepeat || this.numRepeat;
427 | /*
428 | // TODO: take into account two or more nodes on layer having same median
429 | // TODO: also use countCrossings instead of numRepeat
430 | var sweepDown = true;
431 | var sweepUp = true;
432 | var z= 0;
433 | while (sweepDown == true || sweepUp == true) {
434 | var i = 1; // first layer does not have any upperWeights
435 | var len = this.nodes.length;
436 | for (; i < len; i++) {
437 | sweepDown = this.orderLayer(i, 'down');
438 | }
439 | i = len - 2; // last layer does not have any lowerWeights
440 | for (; i > -1; i--) {
441 | sweepUp = this.orderLayer(i, 'up');
442 | }
443 | z++;
444 |
445 | }
446 | console.debug(z);
447 | */
448 | let z, i, len;
449 | for (z = 0; z < numRepeat; z++) {
450 | i = 1; // first layer does not have any upperWeights
451 | len = this.nodes.length;
452 | for (i; i < len; i++) {
453 | this.orderLayer(i, 'down');
454 | }
455 | i = len - 2; // last layer does not have any lowerWeights
456 | for (i; i > -1; i--) {
457 | this.orderLayer(i, 'up');
458 | }
459 | }
460 | }
461 |
462 | /**
463 | * Orders nodes per layer based on median weight of incident nodes.
464 | * Ordering is only done as long as the reducing in #crossings is > than threshold
465 | * @param {Number} layer
466 | * @param {String} direction sweep direction up/down
467 | * @return {Boolean}
468 | */
469 | orderLayer(layer, direction) {
470 | let nodeOrderRestore = this.nodes[layer].slice(0),
471 | numCross1 = this.countCrossings(layer, direction),
472 | nodeOrder = this.nodes[layer], // node ordering has to be done on this.nodes for countCrossings to work
473 | numCross2, i, len, oldX;
474 |
475 | nodeOrder.sort(direction === 'up' ? this.compareByLowerWeight: this.compareByUpperWeight);
476 |
477 | numCross2 = this.countCrossings(layer, direction);
478 | if (numCross2 < numCross1) {
479 | // reassign new position (rank)
480 | len = nodeOrder.length;
481 | for (i = 0; i < len; i++) {
482 | if (i !== nodeOrder[i].x) { // set new pos only if node position has changed
483 | oldX = nodeOrder[i].x;
484 | nodeOrder[i].x = i;
485 | nodeOrder[i].lx = i;
486 | // update edges and weights of rearranged nodes
487 | this.updateEdges(nodeOrder[i], oldX);
488 | }
489 | }
490 |
491 | return true;
492 | }
493 |
494 | // update order in nodelist
495 | this.nodes[layer] = nodeOrderRestore.slice(0);
496 |
497 | return false;
498 | }
499 |
500 | /**
501 | * Updates a node's edges to point to the node's new position.
502 | * Since only x positions are changed we only have to update x pos.
503 | * @param {Object} node
504 | * @param {Number} oldIndex of node
505 | */
506 | updateEdges(node, oldIndex) {
507 | let i, x, y, lenV, v,
508 | nodes, len, trgNode, trgNodes, srcNode, srcNodes;
509 |
510 | // update node's source nodes
511 | nodes = node.srcNodes;
512 | len = nodes.length;
513 | for (i = 0; i < len; i++) {
514 | x = nodes[i][0];
515 | y = nodes[i][1];
516 | // find srcNode's target nodes to update
517 | trgNode = this.nodes[y][x];
518 | trgNodes = trgNode.trgNodes;
519 | lenV = trgNodes.length;
520 | for (v = 0; v < lenV; v++) {
521 | if (trgNodes[v][0] === oldIndex) {
522 | trgNodes[v][0] = node.x;
523 | trgNode.wLower = this.getMedian(trgNode, 'lower');
524 | break;
525 | }
526 | }
527 | }
528 | // update node's target nodes
529 | nodes = node.trgNodes;
530 | len = nodes.length;
531 | for (i = 0; i < len; i++) {
532 | x = nodes[i][0];
533 | y = nodes[i][1];
534 | // find trgNode's source nodes to update
535 | srcNode = this.nodes[y][x];
536 | srcNodes = srcNode.srcNodes;
537 | lenV = srcNodes.length;
538 | for (v = 0; v < lenV; v++) {
539 | if (srcNodes[v][0] === oldIndex) {
540 | srcNodes[v][0] = node.x;
541 | srcNode.wUpper = this.getMedian(srcNode, 'upper');
542 | break;
543 | }
544 | }
545 | }
546 | }
547 |
548 | /**
549 | * Calculates the median of the node's edges.
550 | * The median is calculated from the x values relative to the
551 | * x value of the node. This can either be the nodes on the previous (up)
552 | * or next (down) layer.
553 | * @param {Object} node
554 | * @param {String} type median of lower or upper layer
555 | * @return {number} median
556 | */
557 | getMedian(node, type) {
558 | let weights = [], i, len, middle, nodes;
559 |
560 | nodes = (type === 'upper' ? node.srcNodes: node.trgNodes);
561 | len = nodes.length;
562 | for (i = 0; i < len; i++) {
563 | // do not sort srcNodes or trgNodes directly
564 | weights[i] = this.nodes[nodes[i][1]][nodes[i][0]].lx;
565 | }
566 | weights.sort(function ascend(a, b) {
567 | return a - b;
568 | });
569 | middle = Math.floor(weights.length / 2);
570 | if ((weights.length % 2) !== 0) {
571 | return weights[middle];
572 | }
573 | return (weights[middle - 1] + weights[middle]) / 2;
574 | }
575 |
576 | /**
577 | * Align nodes on layer according to barrycenter and priority.
578 | */
579 | setLayoutPosition() {
580 | let i, len, w, lenW = 4;
581 |
582 | for (w = 0; w < lenW; w++) {
583 | len = this.nodes.length;
584 | for (i = 0; i < len; i++) {
585 | // this.setDegree(i, 'down');
586 | this.align(i, 'down');
587 | }
588 | this.setNodeWeights();
589 |
590 | i = len - 1;
591 | for (i; i > -1; i--) {
592 | // this.setDegree(i, 'up');
593 | this.align(i, 'up');
594 | }
595 | // TODO: Improve performance by only updating lower(upper) (e.g layer +- 1) when on a layer
596 | this.setNodeWeights();
597 | }
598 | }
599 |
600 | /**
601 | * Defines an order based on degree and edge type.
602 | * Virtual nodes get highest degree. Degree is
603 | * based on number of edges.
604 | * @param {Number} layer layer the node is on
605 | * @param {String} direction up or down
606 | */
607 | setDegree(layer, direction) {
608 | let i, len, z, degree,
609 | maxDegree = 0,
610 | nodes = this.nodes[layer];
611 |
612 | // find highest degree
613 | maxDegree = 0;
614 | len = nodes.length;
615 | for (i = 0; i < len; i++) {
616 | if (direction === 'up') {
617 | degree = nodes[i].trgNodes ? nodes[i].trgNodes.length: 0;
618 | }
619 | else {
620 | degree = nodes[i].srcNodes ? nodes[i].srcNodes.length: 0;
621 | }
622 | degree *= 2;
623 | if (maxDegree < degree) {
624 | maxDegree = degree;
625 | }
626 | if (!nodes[i].virt) {
627 | nodes[i].degree = degree;
628 | }
629 | }
630 | // give virtual nodes higher degree than max degree
631 | maxDegree++;
632 | for (z = 0; z < len; z++) {
633 | if (nodes[z].virt) {
634 | nodes[z].degree = maxDegree;
635 | }
636 | }
637 | }
638 |
639 | /**
640 | * Compares the upper weight of two graph nodes.
641 | * @param {graphNode} a
642 | * @param {graphNode} b
643 | */
644 | compareByUpperWeight(a, b) {
645 | if (a.wUpper === null || b.wUpper === null) {
646 | return 0;
647 | }
648 | return (a.wUpper - b.wUpper);
649 | }
650 |
651 | /**
652 | * Compares the lower weight of two graph nodes.
653 | * @param {graphNode} a
654 | * @param {graphNode} b
655 | */
656 | compareByLowerWeight(a, b) {
657 | if (a.wLower === null || b.wLower === null) {
658 | return 0;
659 | }
660 | return (a.wLower - b.wLower);
661 | }
662 |
663 | /**
664 | * Returns some statistics about the graph.
665 | * @return {Object}
666 | */
667 | getGraphStat() {
668 | // since graph might have changed in the meantime we
669 | // have to recalculate this every time
670 | let stat = {
671 | nodesTotal: 0,
672 | nodesDerived: 0,
673 | nodesRaw: 0,
674 | edges: 0
675 | },
676 | node,
677 | z, lenZ, i, len, j, lenJ;
678 |
679 | len = this.nodes.length;
680 | for (i = 0; i < len; i++) {
681 | lenZ = this.nodes[i].length;
682 | for (z = 0; z < lenZ; z++) {
683 | node = this.nodes[i][z];
684 | if (node.isRaw) {
685 | stat.nodesRaw++;
686 | }
687 | if (!node.virt) {
688 | lenJ = node.trgNodes.length;
689 | for (j = 0; j < lenJ; j++) {
690 | stat.edges++;
691 | }
692 | stat.nodesTotal++;
693 | }
694 | }
695 | }
696 | stat.nodesDerived = stat.nodesTotal - stat.nodesRaw;
697 |
698 | return stat;
699 | }
700 |
701 | /**
702 | * Align nodes according to the up/down barycenter.
703 | * They are moved as closely to the barycenter as possible
704 | * using the priority list.
705 | * @param {Number} layer list of nodes to move
706 | * @param {String} direction string
707 | *
708 | */
709 | align(layer, direction) {
710 | // move node according to it's upper/lower median
711 | let numDec = this.getDecimalPlaces(this.incVirt, '.'),
712 | len = this.nodes[layer].length,
713 | i = len - 1,
714 | node, newX, lx;
715 |
716 | for (i; i > -1; i--) {
717 | node = this.nodes[layer][i];
718 | newX = direction === 'up' ? node.wLower: node.wUpper;
719 | if (node.virt) {
720 | newX = this.round(newX, numDec);
721 | }
722 | else {
723 | newX = Math.round(newX / this.inc) * this.inc; // align to inc grid
724 | }
725 | if (node.lx < newX) { // nodes can only be moved to the right, because after compacting we are already as far left as possible
726 | if (i === len - 1) { // right most node can always move right
727 | node.lx = newX;
728 | continue;
729 | }
730 | // shift left as long as pos is unoccupied
731 | // note: when using inc you also have to check for incVirt in between
732 | lx = this.round(node.lx + this.incVirt, numDec);
733 | while (lx <= newX) {
734 | if (lx === this.nodes[layer][i + 1].lx) { // pos already occupied
735 | break;
736 | }
737 | else if (node.virt || lx % this.inc === 0) {
738 | node.lx = lx;
739 | }
740 | lx = this.round(lx + this.incVirt, numDec);
741 | }
742 | }
743 | }
744 | }
745 |
746 | /**
747 | * Compact graph
748 | * Compacts graph by moving nodes as far to left as possible.
749 | * Graph is assumed to be integers only, changed graph can
750 | * have fractions.
751 | */
752 | compact() {
753 | let numDec = this.getDecimalPlaces(this.incVirt, '.'),
754 | g, lenG, node, inc, lx,
755 | i, len = this.nodes.length;
756 |
757 | for (i = 0; i < len; i++) {
758 | g = 1; // first node is always lx == 0
759 | lenG = this.nodes[i].length;
760 | for (g; g < lenG; g++) {
761 | node = this.nodes[i][g];
762 | inc = node.virt ? this.incVirt: this.inc;
763 | lx = node.lx - inc;
764 | if (lx === this.nodes[i][g - 1].lx) { // quickly check pos if already occupied
765 | continue;
766 | }
767 | // shift left as long as unoccupied
768 | while (lx > 0) {
769 | if (lx === this.nodes[i][g - 1].lx) { // pos already occupied
770 | break;
771 | }
772 | else if (node.virt || lx % this.inc === 0) {
773 | node.lx = lx;
774 | }
775 | lx = this.round(lx - this.incVirt, numDec);
776 | }
777 | }
778 | }
779 | this.setNodeWeights();
780 | }
781 |
782 | /**
783 | * Returns the width of the graph.
784 | * @return {Number}
785 | */
786 | getGraphWidth() {
787 | let i, len, z, lenZ, width = 0;
788 |
789 | len = this.nodes.length;
790 | for (i = 0; i < len; i++) {
791 | lenZ = this.nodes[i].length;
792 | for (z = 0; z < lenZ; z++) {
793 | if (this.nodes[i][z].lx > width) {
794 | width = this.nodes[i][z].lx;
795 | }
796 | }
797 | }
798 |
799 | return width + 1;
800 | }
801 |
802 | /**
803 | * Returns the rounded number.
804 | * @param {Number} num number
805 | * @param {Number} decimalPlaces number of decimal places
806 | */
807 | round(num, decimalPlaces) {
808 |
809 | return Math.round(parseFloat(num) * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
810 | }
811 |
812 | /**
813 | * Returns the number of decimal places.
814 | * @param {Number} x number
815 | * @param {String} decSeparator decimal separator
816 | * @return {Number}
817 | */
818 | getDecimalPlaces(x, decSeparator) {
819 | let str = x.toString();
820 |
821 | if (str.indexOf(decSeparator) > -1) {
822 | return str.length - str.indexOf(decSeparator) - 1;
823 | }
824 |
825 | return 0;
826 | }
827 |
828 | /**
829 | * Convenience function to render graph.
830 | * Generates the nodes list and edges.
831 | * @param {Object} graphData
832 | * @param {Object} graphData.nodeList
833 | * @param {Object} graphData.adjList
834 | */
835 | render(graphData) {
836 | this.initNodeList(graphData.nodeList);
837 | this.addEdges(graphData.nodeList, graphData.adjList);
838 | this.expandNodeList();
839 | this.minimizeCrossings();
840 | if (this.compacted) {
841 | this.compact();
842 | }
843 | this.setLayoutPosition();
844 | }
845 | }
--------------------------------------------------------------------------------
/graph/SvgRenderer.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Module to generate a directed graph layout using a Sugiyama algorithm.
3 | * @module dgraph/SvgRenderer
4 | */
5 | import {svgCssUtil} from "./svgCssUtil.js";
6 |
7 | let d = document;
8 |
9 | /**
10 | * Returns an class to create the SVG of the directed graph.
11 | * @class module:dgraph/SvgRenderer
12 | * @param {Object} args parameters
13 | * @param {String} args.canvas name of HTMLElement to be used as canvas
14 | * @param {Object} args.gridSize grid dimensions
15 | * @param {Number} args.gridSize.meshWidth width of grid mesh
16 | * @param {Number} args.gridSize.meshHeight height of grid mesh
17 | * @param {Boolean} [args.renderGrid] render the grid
18 | * @param {Boolean} [args.invert] render the graph inverted
19 | */
20 | export class SvgRenderer {
21 |
22 | constructor(args) {
23 |
24 | this.canvas = null;
25 |
26 | /**
27 | * reference to svg element
28 | * @member {null|SVGElement}
29 | * @default null
30 | */
31 | this.svg = null;
32 |
33 | /**
34 | * svg namespace
35 | * @member {String}
36 | * @default
37 | */
38 | this.svgNs = 'http://www.w3.org/2000/svg';
39 |
40 | this.invert = false;
41 |
42 | /**
43 | * label prefix of the grid x-lines
44 | * @member {string}
45 | * @default
46 | */
47 | this.gridLabel = 'layer';
48 |
49 | /**
50 | * render the grid.
51 | * @member {Boolean}
52 | * @default
53 | */
54 | this.renderGrid = true;
55 |
56 | Object.assign(this, args);
57 |
58 | this.canvas = d.getElementById(args.canvas);
59 | }
60 |
61 | /**
62 | * Creates the SVG canvas.
63 | * @param {Number} width width of svg canvas
64 | * @param {Number} height height of svg canvas
65 | */
66 | initSVG(width, height) {
67 | this.svg = d.createElementNS(this.svgNs, 'svg');
68 | this.svg.setAttribute('version', '1.1');
69 | this.svg.setAttribute('width', width);
70 | this.svg.setAttribute('height', height);
71 | this.svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
72 | this.defs = d.createElementNS(this.svgNs, 'defs'); // holds markers, such as arrow heads
73 | this.svg.appendChild(this.defs);
74 | this.svgRoot = d.createElementNS(this.svgNs, 'g'); // holds all nodes and edges for simple transformation
75 | this.svg.appendChild(this.svgRoot);
76 | this.canvas.appendChild(this.svg);
77 | }
78 |
79 | /**
80 | * Creates a svg graph node.
81 | * @param {graphNode} node
82 | * @return {SVGElement} svg group element
83 | */
84 | createNode(node) {
85 | var text, dist, tspan, circle,
86 | group = d.createElementNS(this.svgNs, 'g');
87 |
88 | svgCssUtil.add(group, 'node');
89 | group.setAttribute('cx', node.lx);
90 | group.setAttribute('cy', node.ly);
91 |
92 | // create circle
93 | circle = d.createElementNS(this.svgNs, 'circle');
94 | circle.setAttribute('r', '5');
95 | group.appendChild(circle);
96 |
97 | // create node label
98 | text = d.createElementNS(this.svgNs, 'text');
99 | text.setAttribute('text-anchor', 'middle');
100 | text.setAttribute('x', '0px');
101 | dist = this.invert ? -1 : 1;
102 | tspan = d.createElementNS(this.svgNs, 'tspan');
103 | tspan.setAttribute('x', '0px');
104 | tspan.setAttribute('y', 1.5 * dist + 'em');
105 | tspan.appendChild(d.createTextNode(node.label));
106 | text.appendChild(tspan);
107 | group.appendChild(text);
108 |
109 | return group;
110 | }
111 |
112 | /**
113 | * Draws the node on the canvas.
114 | * @param {graphNode} node
115 | * @param {Array} nodes graph node list
116 | * @return {graphNode} node
117 | */
118 | drawNode(node, nodes) {
119 | var x, y, shift = 1;
120 |
121 | x = (shift + Number(node.getAttribute('cx'))) * this.gridSize.meshWidth;
122 | if (this.invert) {
123 | y = (Number(node.getAttribute('cy')) * -1 + nodes.length) * this.gridSize.meshHeight;
124 | }
125 | else {
126 | y = (shift + Number(node.getAttribute('cy'))) * this.gridSize.meshHeight;
127 | }
128 | node.setAttribute('transform', 'translate(' + x + ',' + y + ')');
129 | this.svgRoot.appendChild(node);
130 | return node;
131 | }
132 |
133 | /**
134 | * Draws the grid on the canvas.
135 | * Note: After using compact we can not simply calculate
136 | * the width from the number of nodes per layer.
137 | * The height is calculated from the number of layers.
138 | * @param {Number} width width of the grid
139 | * @param {Number} height height of the grid
140 | */
141 | drawGrid(width, height) {
142 | var i, text, level,
143 | numVertical = width / this.gridSize.meshWidth + 1,
144 | numHorizontal = height / this.gridSize.meshHeight;
145 |
146 | for (i = 1; i < numHorizontal; i++) {
147 | this.drawLine(0, i, width, i);
148 | if (i > 0) {
149 | text = d.createElementNS(this.svgNs, 'text');
150 | level = this.invert ? (i + 1) * -1 + numHorizontal : i - 1;
151 | text.setAttribute('text-anchor', 'left');
152 | text.appendChild(d.createTextNode(this.gridLabel + ' ' + level));
153 | text.setAttribute('x', 0);
154 | text.setAttribute('y', i * this.gridSize.meshHeight + 3);
155 | this.svgRoot.appendChild(text);
156 | }
157 | }
158 |
159 | for (i = 1; i < numVertical + 1; i++) {
160 | this.drawLine(i, 0, i, height);
161 | }
162 | }
163 |
164 | /**
165 | * Draws a line on the canvas.
166 | * @param {Number} x1 x-coord of line start
167 | * @param {Number} y1 y-coord of line start
168 | * @param {Number} x2 x-coord of line end
169 | * @param {Number} y2 y-coord of line end
170 | * @return {Object} SVGLine
171 | */
172 | drawLine(x1, y1, x2, y2) {
173 | var width = this.gridSize.meshWidth,
174 | height = this.gridSize.meshHeight,
175 | line = d.createElementNS(this.svgNs, 'line');
176 |
177 | line.setAttribute('x1', x1 * width);
178 | line.setAttribute('y1', y1 * height);
179 | line.setAttribute('x2', x2 * width);
180 | line.setAttribute('y2', y2 * height);
181 | this.svgRoot.appendChild(line);
182 | return line;
183 | }
184 |
185 | /**
186 | * Creates a reusable arrow head.
187 | * The arrow head is appended to the SVG defs element as a marker element
188 | * and can be reused.
189 | * @param {String} id id of marker
190 | * @return {Object} SVGMarker
191 | */
192 | createArrowHead(id) {
193 | var p, nodeRadius,
194 | marker = document.createElementNS(this.svgNs, 'marker');
195 |
196 | marker.setAttribute('id', id);
197 | marker.setAttribute('markerWidth', 11);
198 | marker.setAttribute('markerHeight', 11);
199 | marker.setAttribute('orient', 'auto');
200 | // start arrow head where circle ends
201 | // TODO: find better method to get x
202 | p = document.createElementNS(this.svgNs, 'polyline');
203 | p.setAttribute('points', '0,0 10,5 0,10 1,5');
204 | nodeRadius = 10; // TODO: find generic solution
205 | marker.setAttribute('refX', nodeRadius + Number(marker.getAttribute('markerWidth')));
206 | marker.setAttribute('refY', marker.getAttribute('markerHeight') / 2);
207 | marker.appendChild(p);
208 | this.defs.appendChild(marker);
209 | return marker;
210 | }
211 |
212 | /**
213 | * Draws the edge on the canvas.
214 | * The edge is drawn from node1 to node2 with arrow head.
215 | * @param {graphNode} node1 start node
216 | * @param {graphNode} node2 end node
217 | * @param {Object} arrow SVGMarker
218 | * @param {Array} nodes graph node list
219 | * @return {Object} edge
220 | */
221 | drawEdge(node1, node2, arrow, nodes) {
222 | var x1, x2, y1, y2,
223 | shift = 1,
224 | width = this.gridSize.meshWidth,
225 | height = this.gridSize.meshHeight,
226 | edge = document.createElementNS(this.svgNs, 'polyline');
227 |
228 | x1 = (shift + node1.lx) * width;
229 | x2 = (shift + node2.lx) * width;
230 | if (this.invert) {
231 | y1 = (node1.ly * -1 + nodes.length) * height;
232 | y2 = (node2.ly * -1 + nodes.length) * height;
233 | }
234 | else {
235 | y1 = (shift + node1.ly) * height;
236 | y2 = (shift + node2.ly) * height;
237 | }
238 | svgCssUtil.add(edge, 'edge');
239 | edge.setAttribute('points', x1 + ',' + y1 + ' ' + x2 + ',' + y2);
240 | if (!node2.virt) {
241 | edge.setAttribute('marker-end', 'url(#' + arrow.id + ')');
242 | }
243 | this.svgRoot.appendChild(edge);
244 | return edge;
245 | }
246 |
247 | /**
248 | * Places the nodes on the canvas.
249 | * @param {Array} nodes graph nodes list
250 | */
251 | placeNodes(nodes) {
252 | var i, numRow = nodes.length,
253 | j, numCol, node, svgNode;
254 |
255 | for (i = 0; i < numRow; i++) {
256 | numCol = nodes[i].length;
257 | for (j = 0; j < numCol; j++) {
258 | node = nodes[i][j];
259 | if (!node.virt) {
260 | svgNode = this.createNode(nodes[i][j]);
261 | nodes[i][j].svgNode = this.drawNode(svgNode, nodes); // save back for later reference
262 | }
263 | }
264 | }
265 | }
266 |
267 | /**
268 | * Places the edges on the canvas.
269 | * @param {Array} nodes graph node list
270 | */
271 | placeEdges(nodes) {
272 | var i, j, l, z, x, y, adjNode, numCol, node,
273 | numRow = nodes.length,
274 | arrow = this.createArrowHead('arrow');
275 |
276 | for (i = 0; i < numRow; i++) {
277 | numCol = nodes[i].length;
278 | for (j = 0; j < numCol; j++) {
279 | node = nodes[i][j];
280 | if (node.trgNodes) {
281 | l = node.trgNodes.length;
282 | node.svgEdges = [];
283 | for (z = 0; z < l; z++) {
284 | x = node.trgNodes[z][0];
285 | y = node.trgNodes[z][1];
286 | adjNode = nodes[y][x];
287 | node.svgEdges[z] = this.drawEdge(node, adjNode, arrow, nodes);
288 | }
289 | }
290 | }
291 | }
292 | }
293 |
294 | /**
295 | * Clear the canvas.
296 | */
297 | clearCanvas() {
298 | if (this.canvas) {
299 | this.canvas.innerHTML = '';
300 | }
301 | }
302 |
303 | /**
304 | * Render graph as SVG.
305 | * @param {Object} graph
306 | */
307 | render(graph) {
308 | var width = (graph.getGraphWidth() + 1) * this.gridSize.meshWidth,
309 | height = this.gridSize.meshHeight * (graph.numLayer + 1);
310 |
311 | this.initSVG(width, height);
312 | if (this.renderGrid) {
313 | this.drawGrid(width, height);
314 | }
315 | this.placeEdges(graph.nodes);
316 | this.placeNodes(graph.nodes);
317 | }
318 | }
--------------------------------------------------------------------------------
/graph/gpl.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/graph/pathFinder.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Module contains utility to search graph nodes.
3 | *
4 | * You can use and change this freely as long as you keep this note.
5 | * @copyright: Simon Speich, 2013
6 | *
7 | * Note: Can't use dojo/dom-class since SVGElements are not supported
8 | * @see https://bugs.dojotoolkit.org/ticket/16309
9 | * @module dgraph/pathFinder
10 | */
11 | import {svgCssUtil} from './svgCssUtil.js';
12 |
13 | export let pathFinder = {
14 |
15 | /**
16 | * Find connected target nodes using a breadth first search (BFS) search.
17 | * @param {graphNode} node graph node
18 | * @param {Array} nodelist list of graph nodes
19 | * @param {Function} fnc callback
20 | */
21 | searchByTargets: function(node, nodelist, fnc) {
22 | let openNodes = [],
23 | newNode, neighbors, i, len, nextNode;
24 |
25 | openNodes.push(node);
26 | while (openNodes.length > 0) {
27 | newNode = openNodes.shift();
28 | neighbors = newNode.trgNodes;
29 | len = neighbors.length;
30 | // Add each neighbor to the beginning of openNodes
31 | for (i = 0; i < len; i++) {
32 | nextNode = nodelist[neighbors[i][1]][neighbors[i][0]];
33 | fnc.apply(this, [nextNode]);
34 | openNodes.unshift(nextNode);
35 | }
36 | }
37 | },
38 |
39 | /**
40 | * Find connected source nodes using a breadth first search (BFS) search.
41 | * @param {graphNode} node graph node
42 | * @param {Array} nodelist list of graph nodes
43 | * @param {Function} fnc callback
44 | */
45 | searchBySources: function(node, nodelist, fnc) {
46 | let openNodes = [],
47 | newNode, neighbors, i, len, nextNode;
48 |
49 | openNodes.push(node);
50 | while (openNodes.length > 0) {
51 | newNode = openNodes.shift();
52 | neighbors = newNode.srcNodes;
53 | len = neighbors.length;
54 | // Add each neighbor to the beginning of openNodes
55 | for (i = 0; i < len; i++) {
56 | nextNode = nodelist[neighbors[i][1]][neighbors[i][0]];
57 | fnc.apply(this, [newNode, nextNode]);
58 | openNodes.unshift(nextNode);
59 | }
60 | }
61 | },
62 |
63 | /**
64 | * Highlight all connected edges.
65 | * @param {graphNode} node graph node
66 | * @param {Array} nodelist list of graph nodes
67 | */
68 | highlightPath: function(node, nodelist) {
69 | let highlightSources, highlightTargets, el;
70 |
71 | highlightSources = function(node, srcNode) {
72 | var target, edge, el, z, lenZ, cl;
73 |
74 | lenZ = srcNode.svgEdges.length;
75 | for (z = 0; z < lenZ; z++) {
76 | target = srcNode.trgNodes[z];
77 | if (target[0] === node.x && target[1] === node.y) { // order of trgNode and svgEdges is same
78 | edge = srcNode.svgEdges[z];
79 | svgCssUtil.toggle(edge, 'srcEdgeHighlighted');
80 | if (srcNode.svgNode) {
81 | el = srcNode.svgNode;
82 | svgCssUtil.toggle(el, 'srcNodeHighlighted');
83 | }
84 | }
85 | }
86 | };
87 | highlightTargets = function(node) {
88 | let edge, el, z, lenZ;
89 |
90 | lenZ = node.trgNodes.length;
91 | for (z = 0; z < lenZ; z++) {
92 | edge = node.svgEdges[z];
93 | svgCssUtil.toggle(edge, 'targetEdgeHighlighted');
94 | el = nodelist[node.trgNodes[z][1]][node.trgNodes[z][0]];
95 | if (el.virt === false) {
96 | el = el.svgNode;
97 | svgCssUtil.toggle(el, 'trgNodeHighlighted');
98 | }
99 | }
100 | };
101 |
102 | el = node.svgNode; //.getElementsByTagName('circle')[0];
103 | svgCssUtil.toggle(el, 'nodeHighlighted');
104 | el = el.getElementsByTagName('circle')[0];
105 | el.setAttribute('r', el.getAttribute('r') === '5' ? 8: 5);
106 | highlightTargets(node);
107 | this.searchByTargets(node, nodelist, highlightTargets);
108 | this.searchBySources(node, nodelist, highlightSources);
109 | }
110 | };
111 |
--------------------------------------------------------------------------------
/graph/resources/dgraph.css:
--------------------------------------------------------------------------------
1 | .node circle {
2 | stroke: #999999;
3 | stroke-width: 1px;
4 | fill: #99cccc;
5 | cursor: inherit;
6 | }
7 |
8 | .nodeHighlighted circle {
9 | fill: #ffcc00;
10 | }
11 |
12 | .nodeHighlighted text {
13 | font-weight: bold;
14 | }
15 |
16 | .srcNodeHighlighted circle {
17 | fill: #6666cc;
18 | }
19 |
20 | .targetNodeHighlighted circle {
21 | fill: #cc6666;
22 | }
23 |
24 | line {
25 | stroke: #eaeaea;
26 | stroke-width: 1px;
27 | }
28 |
29 | .edge {
30 | stroke-width: 0.6px;
31 | stroke: #999999;
32 | }
33 |
34 | .srcEdgeHighlighted {
35 | stroke: #0000aa;
36 | }
37 |
38 | .targetEdgeHighlighted {
39 | stroke: #aa0000;
40 | }
41 |
--------------------------------------------------------------------------------
/graph/resources/example-complex.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/speich/dGraph/c87a62a26c84f67b150357bd470d9b5e0688a432/graph/resources/example-complex.gif
--------------------------------------------------------------------------------
/graph/resources/example.css:
--------------------------------------------------------------------------------
1 | #graphCanvas {
2 | font-family: Verdana, Arial, Helvetica, sans-serif;
3 | font-size: 11px;
4 | }
--------------------------------------------------------------------------------
/graph/svgCssUtil.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Module containing CSS helper functions to work with svg.
3 | *
4 | * Note: dojo/dom-class does not work with svg elements, because in SVG,
5 | * className is defined as type SVGAnimatedString -> use getAttribute instead of className
6 | * @see https://bugs.dojotoolkit.org/ticket/16309
7 | * @module dgraph/svgCssUtil
8 | */
9 | export let svgCssUtil = {
10 |
11 | /**
12 | * Add a class name to the class attribute.
13 | * @param {HTMLElement|SVGElement} element
14 | * @param {String} className
15 | * @param {Boolean} [overwrite] adds by default
16 | */
17 | add: function(element, className, overwrite) {
18 | let cls = element.getAttribute('class');
19 |
20 | if (!overwrite) {
21 | className = (cls ? cls + ' ': '') + className;
22 | }
23 | element.setAttribute('class', className);
24 | },
25 |
26 | /**
27 | * Returns the class attribute
28 | * @param {HTMLElement|SVGElement} element
29 | * @return {string}
30 | */
31 | getClass: function(element) {
32 |
33 | return element.getAttribute('class');
34 | },
35 |
36 | /**
37 | * Remove a class name from class attribute
38 | * @param {HTMLElement|SVGElement} element
39 | * @param className
40 | */
41 | remove: function(element, className) {
42 | let arrClasses = element.hasAttribute('class') ? this.getClass(element).split(' '): [],
43 | newClasses = [],
44 | i, len;
45 |
46 | len = arrClasses.length;
47 | for (i = 0; i < len; i++) {
48 | if (className !== arrClasses[i]) {
49 | newClasses.push(arrClasses[i]);
50 | }
51 | }
52 | this.add(element, newClasses.join(' '), true);
53 | },
54 |
55 | /**
56 | * Checks element for given class.
57 | * ClassName can be an array to check for multiple classes.
58 | * @param {HTMLElement|SVGElement} element
59 | * @param {Array|String} className
60 | */
61 | has: function(element, className) {
62 | let elClasses = element.hasAttribute('class') ? this.getClass(element).split(' '): [],
63 | arrClasses = className,
64 | chkInd = 0,
65 | i, len, z, lenZ;
66 |
67 | if (typeof className === 'string') {
68 | arrClasses = className.split(' ');
69 | }
70 |
71 | len = arrClasses.length;
72 | for (i = 0; i < len; i++) {
73 | lenZ = elClasses.length;
74 | for (z = 0; z < lenZ; z++) {
75 | if (arrClasses[i] === elClasses[z]) {
76 | chkInd++;
77 | break;
78 | }
79 | }
80 | }
81 |
82 | return chkInd === arrClasses.length;
83 | },
84 |
85 | /**
86 | * Adds a class to node if not present, or removes if present.
87 | * @param {HTMLElement|SVGElement} element
88 | * @param className
89 | */
90 | toggle: function(element, className) {
91 | let fnc = this.has(element, className) ? 'remove': 'add';
92 |
93 | this[fnc](element, className);
94 | }
95 | };
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "dgraph",
3 | "version": "1.0.0",
4 | "license": "GPL-3.0-or-later",
5 | "author": "Simon Speich, WSL"
6 | }
--------------------------------------------------------------------------------