diff --git a/xCAT-UI/js/jquery.flot.js b/xCAT-UI/js/jquery.flot.js index b1b298e99..b8bd4d730 100644 --- a/xCAT-UI/js/jquery.flot.js +++ b/xCAT-UI/js/jquery.flot.js @@ -1,20 +1,44 @@ -/* Javascript plotting library for jQuery, v. 0.5. +/* Javascript plotting library for jQuery, v. 0.6. * * Released under the MIT license by IOLA, December 2007. * */ +// first an inline dependency, jquery.colorhelpers.js, we inline it here +// for convenience + +/* Plugin for jQuery for working with colors. + * + * Version 1.0. + * + * Inspiration from jQuery color animation plugin by John Resig. + * + * Released under the MIT license by Ole Laursen, October 2009. + * + * Examples: + * + * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() + * var c = $.color.extract($("#mydiv"), 'background-color'); + * console.log(c.r, c.g, c.b, c.a); + * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" + * + * Note that .scale() and .add() work in-place instead of returning + * new objects. + */ +(function(){jQuery.color={};jQuery.color.make=function(E,D,B,C){var F={};F.r=E||0;F.g=D||0;F.b=B||0;F.a=C!=null?C:1;F.add=function(I,H){for(var G=0;G=1){return"rgb("+[F.r,F.g,F.b].join(",")+")"}else{return"rgba("+[F.r,F.g,F.b,F.a].join(",")+")"}};F.normalize=function(){function G(I,J,H){return JH?H:J)}F.r=G(0,parseInt(F.r),255);F.g=G(0,parseInt(F.g),255);F.b=G(0,parseInt(F.b),255);F.a=G(0,F.a,1);return F};F.clone=function(){return jQuery.color.make(F.r,F.b,F.g,F.a)};return F.normalize()};jQuery.color.extract=function(C,B){var D;do{D=C.css(B).toLowerCase();if(D!=""&&D!="transparent"){break}C=C.parent()}while(!jQuery.nodeName(C.get(0),"body"));if(D=="rgba(0, 0, 0, 0)"){D="transparent"}return jQuery.color.parse(D)};jQuery.color.parse=function(E){var D,B=jQuery.color.make;if(D=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(E)){return B(parseInt(D[1],10),parseInt(D[2],10),parseInt(D[3],10))}if(D=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(E)){return B(parseInt(D[1],10),parseInt(D[2],10),parseInt(D[3],10),parseFloat(D[4]))}if(D=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(E)){return B(parseFloat(D[1])*2.55,parseFloat(D[2])*2.55,parseFloat(D[3])*2.55)}if(D=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(E)){return B(parseFloat(D[1])*2.55,parseFloat(D[2])*2.55,parseFloat(D[3])*2.55,parseFloat(D[4]))}if(D=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(E)){return B(parseInt(D[1],16),parseInt(D[2],16),parseInt(D[3],16))}if(D=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(E)){return B(parseInt(D[1]+D[1],16),parseInt(D[2]+D[2],16),parseInt(D[3]+D[3],16))}var C=jQuery.trim(E).toLowerCase();if(C=="transparent"){return B(255,255,255,0)}else{D=A[C];return B(D[0],D[1],D[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(); + +// the actual Flot code (function($) { - function Plot(target_, data_, options_) { + function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] - // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label" } + // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var series = [], options = { - // the color theme used for graphs - colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], + // the color theme used for graphs + colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], legend: { show: true, noColumns: 1, // number of colums in legend table @@ -28,6 +52,8 @@ }, xaxis: { mode: null, // null or "time" + transform: null, // null or f: number -> number to transform axis + inverseTransform: null, // if transform is set, this should be the inverse function min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max @@ -41,7 +67,8 @@ tickSize: null, // number or [number, "unit"] minTickSize: null, // number or [number, "unit"] monthNames: null, // list of names of months - timeformat: null // format string to use + timeformat: null, // format string to use + twelveHourClock: false // 12 or 24 time in time mode }, yaxis: { autoscaleMargin: 0.02 @@ -51,34 +78,43 @@ }, y2axis: { autoscaleMargin: 0.02 - }, - points: { - show: false, - radius: 3, - lineWidth: 2, // in pixels - fill: true, - fillColor: "#ffffff" }, - lines: { - show: false, - lineWidth: 2, // in pixels - fill: false, - fillColor: null - }, - bars: { - show: false, - lineWidth: 2, // in pixels - barWidth: 1, // in units of the x axis - fill: true, - fillColor: null, - align: "left" // or "center" + series: { + points: { + show: false, + radius: 3, + lineWidth: 2, // in pixels + fill: true, + fillColor: "#ffffff" + }, + lines: { + // we don't put in show: false so we can see + // whether lines were actively disabled + lineWidth: 2, // in pixels + fill: false, + fillColor: null, + steps: false + }, + bars: { + show: false, + lineWidth: 2, // in pixels + barWidth: 1, // in units of the x axis + fill: true, + fillColor: null, + align: "left", // or "center" + horizontal: false // when horizontal, left is now top + }, + shadowSize: 3 }, grid: { + show: true, + aboveData: false, color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color - tickColor: "#dddddd", // color used for the ticks + tickColor: "rgba(0,0,0,0.15)", // color used for the ticks labelMargin: 5, // in pixels - borderWidth: 2, + borderWidth: 2, // in pixels + borderColor: null, // set if different from the grid color markings: null, // array of ranges or fn: axes -> array of ranges markingsColor: "#f4f4f4", markingsLineWidth: 2, @@ -88,72 +124,85 @@ autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, - selection: { - mode: null, // one of null, "x", "y" or "xy" - color: "#e8cfac" - }, - shadowSize: 4 + hooks: {} }, canvas = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, - target = target_, axes = { xaxis: {}, yaxis: {}, x2axis: {}, y2axis: {} }, plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, canvasWidth = 0, canvasHeight = 0, plotWidth = 0, plotHeight = 0, - // dedicated to storing data for buggy standard compliance cases - workarounds = {}; + hooks = { + processOptions: [], + processRawData: [], + processDatapoints: [], + draw: [], + bindEvents: [], + drawOverlay: [] + }, + plot = this; + + // public functions + plot.setData = setData; + plot.setupGrid = setupGrid; + plot.draw = draw; + plot.getPlaceholder = function() { return placeholder; }; + plot.getCanvas = function() { return canvas; }; + plot.getPlotOffset = function() { return plotOffset; }; + plot.width = function () { return plotWidth; }; + plot.height = function () { return plotHeight; }; + plot.offset = function () { + var o = eventHolder.offset(); + o.left += plotOffset.left; + o.top += plotOffset.top; + return o; + }; + plot.getData = function() { return series; }; + plot.getAxes = function() { return axes; }; + plot.getOptions = function() { return options; }; + plot.highlight = highlight; + plot.unhighlight = unhighlight; + plot.triggerRedrawOverlay = triggerRedrawOverlay; + plot.pointOffset = function(point) { + return { left: parseInt(axisSpecToRealAxis(point, "xaxis").p2c(+point.x) + plotOffset.left), + top: parseInt(axisSpecToRealAxis(point, "yaxis").p2c(+point.y) + plotOffset.top) }; + }; - this.setData = setData; - this.setupGrid = setupGrid; - this.draw = draw; - this.clearSelection = clearSelection; - this.setSelection = setSelection; - this.getCanvas = function() { return canvas; }; - this.getPlotOffset = function() { return plotOffset; }; - this.getData = function() { return series; }; - this.getAxes = function() { return axes; }; - this.highlight = highlight; - this.unhighlight = unhighlight; + + // public attributes + plot.hooks = hooks; // initialize + initPlugins(plot); parseOptions(options_); - setData(data_); constructCanvas(); + setData(data_); setupGrid(); draw(); + bindEvents(); - function setData(d) { - series = parseData(d); - - fillInSeriesOptions(); - processData(); + function executeHooks(hook, args) { + args = [plot].concat(args); + for (var i = 0; i < hook.length; ++i) + hook[i].apply(this, args); } - - function parseData(d) { - var res = []; - for (var i = 0; i < d.length; ++i) { - var s; - if (d[i].data) { - s = {}; - for (var v in d[i]) - s[v] = d[i][v]; - } - else { - s = { data: d[i] }; - } - res.push(s); + + function initPlugins() { + for (var i = 0; i < plugins.length; ++i) { + var p = plugins[i]; + p.init(plot); + if (p.options) + $.extend(true, options, p.options); } - - return res; } - function parseOptions(o) { - $.extend(true, options, o); - + function parseOptions(opts) { + $.extend(true, options, opts); + if (options.grid.borderColor == null) + options.grid.borderColor = options.grid.color; // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks; @@ -163,8 +212,58 @@ options.grid.markings = options.grid.coloredAreas; if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor; + if (options.lines) + $.extend(true, options.series.lines, options.lines); + if (options.points) + $.extend(true, options.series.points, options.points); + if (options.bars) + $.extend(true, options.series.bars, options.bars); + if (options.shadowSize) + options.series.shadowSize = options.shadowSize; + + for (var n in hooks) + if (options.hooks[n] && options.hooks[n].length) + hooks[n] = hooks[n].concat(options.hooks[n]); + + executeHooks(hooks.processOptions, [options]); } + function setData(d) { + series = parseData(d); + fillInSeriesOptions(); + processData(); + } + + function parseData(d) { + var res = []; + for (var i = 0; i < d.length; ++i) { + var s = $.extend(true, {}, options.series); + + if (d[i].data) { + s.data = d[i].data; // move the data instead of deep-copy + delete d[i].data; + + $.extend(true, s, d[i]); + + d[i].data = s.data; + } + else + s.data = d[i]; + res.push(s); + } + + return res; + } + + function axisSpecToRealAxis(obj, attr) { + var a = obj[attr]; + if (!a || a == 1) + return axes[attr]; + if (typeof a == "number") + return axes[attr.charAt(0) + a + attr.slice(1)]; + return a; // assume it's OK + } + function fillInSeriesOptions() { var i; @@ -179,7 +278,7 @@ if (typeof sc == "number") assignedColors.push(sc); else - usedColors.push(parseColor(series[i].color)); + usedColors.push($.color.parse(series[i].color)); } } @@ -195,14 +294,13 @@ while (colors.length < neededColors) { var c; if (options.colors.length == i) // check degenerate case - c = new Color(100, 100, 100); + c = $.color.make(100, 100, 100); else - c = parseColor(options.colors[i]); + c = $.color.parse(options.colors[i]); // vary color if needed var sign = variation % 2 == 1 ? -1 : 1; - var factor = 1 + sign * Math.ceil(variation / 2) * 0.2; - c.scale(factor, factor, factor); + c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2) // FIXME: if we're getting to close to something else, // we should probably skip this one @@ -219,7 +317,7 @@ var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; - + // assign colors if (s.color == null) { s.color = colors[colori].toString(); @@ -228,176 +326,437 @@ else if (typeof s.color == "number") s.color = colors[s.color].toString(); - // copy the rest - s.lines = $.extend(true, {}, options.lines, s.lines); - s.points = $.extend(true, {}, options.points, s.points); - s.bars = $.extend(true, {}, options.bars, s.bars); - if (s.shadowSize == null) - s.shadowSize = options.shadowSize; - if (s.xaxis && s.xaxis == 2) - s.xaxis = axes.x2axis; - else - s.xaxis = axes.xaxis; - if (s.yaxis && s.yaxis == 2) - s.yaxis = axes.y2axis; - else - s.yaxis = axes.yaxis; + // turn on lines automatically in case nothing is set + if (s.lines.show == null) { + var v, show = true; + for (v in s) + if (s[v] && s[v].show) { + show = false; + break; + } + if (show) + s.lines.show = true; + } + + // setup axes + s.xaxis = axisSpecToRealAxis(s, "xaxis"); + s.yaxis = axisSpecToRealAxis(s, "yaxis"); } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, - axis; + i, j, k, m, length, + s, points, ps, x, y, axis, val, f, p; for (axis in axes) { axes[axis].datamin = topSentry; axes[axis].datamax = bottomSentry; axes[axis].used = false; } - - for (var i = 0; i < series.length; ++i) { - var data = series[i].data, - axisx = series[i].xaxis, - axisy = series[i].yaxis, - mindelta = 0, maxdelta = 0; - - // make sure we got room for the bar - if (series[i].bars.show) { - mindelta = series[i].bars.align == "left" ? 0 : -series[i].bars.barWidth/2; - maxdelta = mindelta + series[i].bars.barWidth; - } - - axisx.used = axisy.used = true; - for (var j = 0; j < data.length; ++j) { - if (data[j] == null) - continue; - - var x = data[j][0], y = data[j][1]; - // convert to number - if (x != null && !isNaN(x = +x)) { - if (x + mindelta < axisx.datamin) - axisx.datamin = x + mindelta; - if (x + maxdelta > axisx.datamax) - axisx.datamax = x + maxdelta; - } + function updateAxis(axis, min, max) { + if (min < axis.datamin) + axis.datamin = min; + if (max > axis.datamax) + axis.datamax = max; + } + + for (i = 0; i < series.length; ++i) { + s = series[i]; + s.datapoints = { points: [] }; + + executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); + } + + // first pass: clean and copy data + for (i = 0; i < series.length; ++i) { + s = series[i]; + + var data = s.data, format = s.datapoints.format; + + if (!format) { + format = []; + // find out how to copy + format.push({ x: true, number: true, required: true }); + format.push({ y: true, number: true, required: true }); + + if (s.bars.show || (s.lines.show && s.lines.fill)) + format.push({ y: true, number: true, required: false, defaultValue: 0 }); - if (y != null && !isNaN(y = +y)) { - if (y < axisy.datamin) - axisy.datamin = y; - if (y > axisy.datamax) - axisy.datamax = y; - } - - if (x == null || y == null || isNaN(x) || isNaN(y)) - data[j] = null; // mark this point as invalid + s.datapoints.format = format; } + + if (s.datapoints.pointsize != null) + continue; // already filled in + + if (s.datapoints.pointsize == null) + s.datapoints.pointsize = format.length; + + ps = s.datapoints.pointsize; + points = s.datapoints.points; + + insertSteps = s.lines.show && s.lines.steps; + s.xaxis.used = s.yaxis.used = true; + + for (j = k = 0; j < data.length; ++j, k += ps) { + p = data[j]; + + var nullify = p == null; + if (!nullify) { + for (m = 0; m < ps; ++m) { + val = p[m]; + f = format[m]; + + if (f) { + if (f.number && val != null) { + val = +val; // convert to number + if (isNaN(val)) + val = null; + } + + if (val == null) { + if (f.required) + nullify = true; + + if (f.defaultValue != null) + val = f.defaultValue; + } + } + + points[k + m] = val; + } + } + + if (nullify) { + for (m = 0; m < ps; ++m) { + val = points[k + m]; + if (val != null) { + f = format[m]; + // extract min/max info + if (f.x) + updateAxis(s.xaxis, val, val); + if (f.y) + updateAxis(s.yaxis, val, val); + } + points[k + m] = null; + } + } + else { + // a little bit of line specific stuff that + // perhaps shouldn't be here, but lacking + // better means... + if (insertSteps && k > 0 + && points[k - ps] != null + && points[k - ps] != points[k] + && points[k - ps + 1] != points[k + 1]) { + // copy the point to make room for a middle point + for (m = 0; m < ps; ++m) + points[k + ps + m] = points[k + m]; + + // middle point has same y + points[k + 1] = points[k - ps + 1]; + + // we've added a point, better reflect that + k += ps; + } + } + } + } + + // give the hooks a chance to run + for (i = 0; i < series.length; ++i) { + s = series[i]; + + executeHooks(hooks.processDatapoints, [ s, s.datapoints]); + } + + // second pass: find datamax/datamin for auto-scaling + for (i = 0; i < series.length; ++i) { + s = series[i]; + points = s.datapoints.points, + ps = s.datapoints.pointsize; + + var xmin = topSentry, ymin = topSentry, + xmax = bottomSentry, ymax = bottomSentry; + + for (j = 0; j < points.length; j += ps) { + if (points[j] == null) + continue; + + for (m = 0; m < ps; ++m) { + val = points[j + m]; + f = format[m]; + if (!f) + continue; + + if (f.x) { + if (val < xmin) + xmin = val; + if (val > xmax) + xmax = val; + } + if (f.y) { + if (val < ymin) + ymin = val; + if (val > ymax) + ymax = val; + } + } + } + + if (s.bars.show) { + // make sure we got room for the bar on the dancing floor + var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2; + if (s.bars.horizontal) { + ymin += delta; + ymax += delta + s.bars.barWidth; + } + else { + xmin += delta; + xmax += delta + s.bars.barWidth; + } + } + + updateAxis(s.xaxis, xmin, xmax); + updateAxis(s.yaxis, ymin, ymax); } for (axis in axes) { if (axes[axis].datamin == topSentry) - axes[axis].datamin = 0; + axes[axis].datamin = null; if (axes[axis].datamax == bottomSentry) - axes[axis].datamax = 1; + axes[axis].datamax = null; } } function constructCanvas() { - canvasWidth = target.width(); - canvasHeight = target.height(); - target.html(""); // clear target - target.css("position", "relative"); // for positioning labels and overlay + function makeCanvas(width, height) { + var c = document.createElement('canvas'); + c.width = width; + c.height = height; + if ($.browser.msie) // excanvas hack + c = window.G_vmlCanvasManager.initElement(c); + return c; + } + + canvasWidth = placeholder.width(); + canvasHeight = placeholder.height(); + placeholder.html(""); // clear placeholder + if (placeholder.css("position") == 'static') + placeholder.css("position", "relative"); // for positioning labels and overlay if (canvasWidth <= 0 || canvasHeight <= 0) throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight; - // the canvas - canvas = $('').appendTo(target).get(0); if ($.browser.msie) // excanvas hack - canvas = window.G_vmlCanvasManager.initElement(canvas); + window.G_vmlCanvasManager.init_(document); // make sure everything is setup + + // the canvas + canvas = $(makeCanvas(canvasWidth, canvasHeight)).appendTo(placeholder).get(0); ctx = canvas.getContext("2d"); // overlay canvas for interactive features - overlay = $('').appendTo(target).get(0); - if ($.browser.msie) // excanvas hack - overlay = window.G_vmlCanvasManager.initElement(overlay); + overlay = $(makeCanvas(canvasWidth, canvasHeight)).css({ position: 'absolute', left: 0, top: 0 }).appendTo(placeholder).get(0); octx = overlay.getContext("2d"); + octx.stroke(); + } + function bindEvents() { // we include the canvas in the event holder too, because IE 7 // sometimes has trouble with the stacking order eventHolder = $([overlay, canvas]); // bind events - if (options.selection.mode != null || options.grid.hoverable) { - // FIXME: temp. work-around until jQuery bug 1871 is fixed - eventHolder.each(function () { - this.onmousemove = onMouseMove; - }); - - if (options.selection.mode != null) - eventHolder.mousedown(onMouseDown); - } + if (options.grid.hoverable) + eventHolder.mousemove(onMouseMove); if (options.grid.clickable) eventHolder.click(onClick); + + executeHooks(hooks.bindEvents, [eventHolder]); } function setupGrid() { - function setupAxis(axis, options) { - setRange(axis, options); - prepareTickGeneration(axis, options); - setTicks(axis, options); + function setTransformationHelpers(axis, o) { + function identity(x) { return x; } + + var s, m, t = o.transform || identity, + it = o.inverseTransform; + // add transformation helpers if (axis == axes.xaxis || axis == axes.x2axis) { + // precompute how much the axis is scaling a point + // in canvas space + s = axis.scale = plotWidth / (t(axis.max) - t(axis.min)); + m = t(axis.min); + // data point to canvas coordinate - axis.p2c = function (p) { return (p - axis.min) * axis.scale; }; - // canvas coordinate to data point - axis.c2p = function (c) { return axis.min + c / axis.scale; }; + if (t == identity) // slight optimization + axis.p2c = function (p) { return (p - m) * s; }; + else + axis.p2c = function (p) { return (t(p) - m) * s; }; + // canvas coordinate to data point + if (!it) + axis.c2p = function (c) { return m + c / s; }; + else + axis.c2p = function (c) { return it(m + c / s); }; } else { - axis.p2c = function (p) { return (axis.max - p) * axis.scale; }; - axis.c2p = function (p) { return axis.max - p / axis.scale; }; + s = axis.scale = plotHeight / (t(axis.max) - t(axis.min)); + m = t(axis.max); + + if (t == identity) + axis.p2c = function (p) { return (m - p) * s; }; + else + axis.p2c = function (p) { return (m - t(p)) * s; }; + if (!it) + axis.c2p = function (c) { return m - c / s; }; + else + axis.c2p = function (c) { return it(m - c / s); }; } } - for (var axis in axes) - setupAxis(axes[axis], options[axis]); + function measureLabels(axis, axisOptions) { + var i, labels = [], l; + + axis.labelWidth = axisOptions.labelWidth; + axis.labelHeight = axisOptions.labelHeight; - setSpacing(); - insertLabels(); + if (axis == axes.xaxis || axis == axes.x2axis) { + // to avoid measuring the widths of the labels, we + // construct fixed-size boxes and put the labels inside + // them, we don't need the exact figures and the + // fixed-size box content is easy to center + if (axis.labelWidth == null) + axis.labelWidth = canvasWidth / (axis.ticks.length > 0 ? axis.ticks.length : 1); + + // measure x label heights + if (axis.labelHeight == null) { + labels = []; + for (i = 0; i < axis.ticks.length; ++i) { + l = axis.ticks[i].label; + if (l) + labels.push('
' + l + '
'); + } + + if (labels.length > 0) { + var dummyDiv = $('
' + + labels.join("") + '
').appendTo(placeholder); + axis.labelHeight = dummyDiv.height(); + dummyDiv.remove(); + } + } + } + else if (axis.labelWidth == null || axis.labelHeight == null) { + // calculate y label dimensions + for (i = 0; i < axis.ticks.length; ++i) { + l = axis.ticks[i].label; + if (l) + labels.push('
' + l + '
'); + } + + if (labels.length > 0) { + var dummyDiv = $('
' + + labels.join("") + '
').appendTo(placeholder); + if (axis.labelWidth == null) + axis.labelWidth = dummyDiv.width(); + if (axis.labelHeight == null) + axis.labelHeight = dummyDiv.find("div").height(); + dummyDiv.remove(); + } + + } + + if (axis.labelWidth == null) + axis.labelWidth = 0; + if (axis.labelHeight == null) + axis.labelHeight = 0; + } + + function setGridSpacing() { + // get the most space needed around the grid for things + // that may stick out + var maxOutset = options.grid.borderWidth; + for (i = 0; i < series.length; ++i) + maxOutset = Math.max(maxOutset, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); + + plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset; + + var margin = options.grid.labelMargin + options.grid.borderWidth; + + if (axes.xaxis.labelHeight > 0) + plotOffset.bottom = Math.max(maxOutset, axes.xaxis.labelHeight + margin); + if (axes.yaxis.labelWidth > 0) + plotOffset.left = Math.max(maxOutset, axes.yaxis.labelWidth + margin); + if (axes.x2axis.labelHeight > 0) + plotOffset.top = Math.max(maxOutset, axes.x2axis.labelHeight + margin); + if (axes.y2axis.labelWidth > 0) + plotOffset.right = Math.max(maxOutset, axes.y2axis.labelWidth + margin); + + plotWidth = canvasWidth - plotOffset.left - plotOffset.right; + plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; + } + + var axis; + for (axis in axes) + setRange(axes[axis], options[axis]); + + if (options.grid.show) { + for (axis in axes) { + prepareTickGeneration(axes[axis], options[axis]); + setTicks(axes[axis], options[axis]); + measureLabels(axes[axis], options[axis]); + } + + setGridSpacing(); + } + else { + plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0; + plotWidth = canvasWidth; + plotHeight = canvasHeight; + } + + for (axis in axes) + setTransformationHelpers(axes[axis], options[axis]); + + if (options.grid.show) + insertLabels(); + insertLegend(); } function setRange(axis, axisOptions) { - var min = axisOptions.min != null ? axisOptions.min : axis.datamin; - var max = axisOptions.max != null ? axisOptions.max : axis.datamax; + var min = +(axisOptions.min != null ? axisOptions.min : axis.datamin), + max = +(axisOptions.max != null ? axisOptions.max : axis.datamax), + delta = max - min; - if (max - min == 0.0) { + if (delta == 0.0) { // degenerate case - var widen; - if (max == 0.0) - widen = 1.0; - else - widen = 0.01; + var widen = max == 0 ? 1 : 0.01; - min -= widen; - max += widen; + if (axisOptions.min == null) + min -= widen; + // alway widen max if we couldn't widen min to ensure we + // don't fall into min == max which doesn't work + if (axisOptions.max == null || axisOptions.min != null) + max += widen; } else { // consider autoscaling var margin = axisOptions.autoscaleMargin; if (margin != null) { if (axisOptions.min == null) { - min -= (max - min) * margin; + min -= delta * margin; // make sure we don't go below zero if all values // are positive - if (min < 0 && axis.datamin >= 0) + if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0; } if (axisOptions.max == null) { - max += (max - min) * margin; - if (max > 0 && axis.datamax <= 0) + max += delta * margin; + if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0; } } @@ -412,54 +771,18 @@ if (typeof axisOptions.ticks == "number" && axisOptions.ticks > 0) noTicks = axisOptions.ticks; else if (axis == axes.xaxis || axis == axes.x2axis) - noTicks = canvasWidth / 100; + // heuristic based on the model a*sqrt(x) fitted to + // some reasonable data points + noTicks = 0.3 * Math.sqrt(canvasWidth); else - noTicks = canvasHeight / 60; + noTicks = 0.3 * Math.sqrt(canvasHeight); - var delta = (axis.max - axis.min) / noTicks; - var size, generator, unit, formatter, i, magn, norm; + var delta = (axis.max - axis.min) / noTicks, + size, generator, unit, formatter, i, magn, norm; if (axisOptions.mode == "time") { // pretty handling of time - function formatDate(d, fmt, monthNames) { - var leftPad = function(n) { - n = "" + n; - return n.length == 1 ? "0" + n : n; - }; - - var r = []; - var escape = false; - if (monthNames == null) - monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - for (var i = 0; i < fmt.length; ++i) { - var c = fmt.charAt(i); - - if (escape) { - switch (c) { - case 'h': c = "" + d.getUTCHours(); break; - case 'H': c = leftPad(d.getUTCHours()); break; - case 'M': c = leftPad(d.getUTCMinutes()); break; - case 'S': c = leftPad(d.getUTCSeconds()); break; - case 'd': c = "" + d.getUTCDate(); break; - case 'm': c = "" + (d.getUTCMonth() + 1); break; - case 'y': c = "" + d.getUTCFullYear(); break; - case 'b': c = "" + monthNames[d.getUTCMonth()]; break; - } - r.push(c); - escape = false; - } - else { - if (c == "%") - escape = true; - else - r.push(c); - } - } - return r.join(""); - } - - // map of app. size of time units in milliseconds var timeUnitSize = { "second": 1000, @@ -591,18 +914,19 @@ // first check global format if (axisOptions.timeformat != null) - return formatDate(d, axisOptions.timeformat, axisOptions.monthNames); + return $.plot.formatDate(d, axisOptions.timeformat, axisOptions.monthNames); var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; + var suffix = (axisOptions.twelveHourClock) ? " %p" : ""; if (t < timeUnitSize.minute) - fmt = "%h:%M:%S"; + fmt = "%h:%M:%S" + suffix; else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) - fmt = "%h:%M"; + fmt = "%h:%M" + suffix; else - fmt = "%b %d %h:%M"; + fmt = "%b %d %h:%M" + suffix; } else if (t < timeUnitSize.month) fmt = "%b %d"; @@ -615,7 +939,7 @@ else fmt = "%y"; - return formatDate(d, fmt, axisOptions.monthNames); + return $.plot.formatDate(d, fmt, axisOptions.monthNames); }; } else { @@ -624,7 +948,7 @@ var dec = -Math.floor(Math.log(delta) / Math.LN10); if (maxDec != null && dec > maxDec) dec = maxDec; - + magn = Math.pow(10, -dec); norm = delta / magn; // norm is between 1.0 and 10.0 @@ -650,9 +974,9 @@ if (axisOptions.tickSize != null) size = axisOptions.tickSize; - + axis.tickDecimals = Math.max(0, (maxDec != null) ? maxDec : dec); - + generator = function (axis) { var ticks = []; @@ -679,10 +1003,6 @@ axis.tickFormatter = function (v, axis) { return "" + axisOptions.tickFormatter(v, axis); }; else axis.tickFormatter = formatter; - if (axisOptions.labelWidth != null) - axis.labelWidth = axisOptions.labelWidth; - if (axisOptions.labelHeight != null) - axis.labelHeight = axisOptions.labelHeight; } function setTicks(axis, axisOptions) { @@ -727,104 +1047,25 @@ if (axisOptions.min == null) axis.min = Math.min(axis.min, axis.ticks[0].v); if (axisOptions.max == null && axis.ticks.length > 1) - axis.max = Math.min(axis.max, axis.ticks[axis.ticks.length - 1].v); + axis.max = Math.max(axis.max, axis.ticks[axis.ticks.length - 1].v); } } - - function setSpacing() { - function measureXLabels(axis) { - // to avoid measuring the widths of the labels, we - // construct fixed-size boxes and put the labels inside - // them, we don't need the exact figures and the - // fixed-size box content is easy to center - if (axis.labelWidth == null) - axis.labelWidth = canvasWidth / 6; - - // measure x label heights - if (axis.labelHeight == null) { - labels = []; - for (i = 0; i < axis.ticks.length; ++i) { - l = axis.ticks[i].label; - if (l) - labels.push('
' + l + '
'); - } - - axis.labelHeight = 0; - if (labels.length > 0) { - var dummyDiv = $('
' - + labels.join("") + '
').appendTo(target); - axis.labelHeight = dummyDiv.height(); - dummyDiv.remove(); - } - } - } - - function measureYLabels(axis) { - if (axis.labelWidth == null || axis.labelHeight == null) { - var i, labels = [], l; - // calculate y label dimensions - for (i = 0; i < axis.ticks.length; ++i) { - l = axis.ticks[i].label; - if (l) - labels.push('
' + l + '
'); - } - - if (labels.length > 0) { - var dummyDiv = $('
' - + labels.join("") + '
').appendTo(target); - if (axis.labelWidth == null) - axis.labelWidth = dummyDiv.width(); - if (axis.labelHeight == null) - axis.labelHeight = dummyDiv.find("div").height(); - dummyDiv.remove(); - } - - if (axis.labelWidth == null) - axis.labelWidth = 0; - if (axis.labelHeight == null) - axis.labelHeight = 0; - } - } - - measureXLabels(axes.xaxis); - measureYLabels(axes.yaxis); - measureXLabels(axes.x2axis); - measureYLabels(axes.y2axis); - - // get the most space needed around the grid for things - // that may stick out - var maxOutset = options.grid.borderWidth / 2; - for (i = 0; i < series.length; ++i) - maxOutset = Math.max(maxOutset, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); - - plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset; - - if (axes.xaxis.labelHeight > 0) - plotOffset.bottom = Math.max(maxOutset, axes.xaxis.labelHeight + options.grid.labelMargin); - if (axes.yaxis.labelWidth > 0) - plotOffset.left = Math.max(maxOutset, axes.yaxis.labelWidth + options.grid.labelMargin); - - if (axes.x2axis.labelHeight > 0) - plotOffset.top = Math.max(maxOutset, axes.x2axis.labelHeight + options.grid.labelMargin); - - if (axes.y2axis.labelWidth > 0) - plotOffset.right = Math.max(maxOutset, axes.y2axis.labelWidth + options.grid.labelMargin); - - plotWidth = canvasWidth - plotOffset.left - plotOffset.right; - plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; - - // precompute how much the axis is scaling a point in canvas space - axes.xaxis.scale = plotWidth / (axes.xaxis.max - axes.xaxis.min); - axes.yaxis.scale = plotHeight / (axes.yaxis.max - axes.yaxis.min); - axes.x2axis.scale = plotWidth / (axes.x2axis.max - axes.x2axis.min); - axes.y2axis.scale = plotHeight / (axes.y2axis.max - axes.y2axis.min); - } - + function draw() { - drawGrid(); - for (var i = 0; i < series.length; i++) { + ctx.clearRect(0, 0, canvasWidth, canvasHeight); + + var grid = options.grid; + + if (grid.show && !grid.aboveData) + drawGrid(); + + for (var i = 0; i < series.length; ++i) drawSeries(series[i]); - } + + executeHooks(hooks.draw, [ctx]); + + if (grid.show && grid.aboveData) + drawGrid(); } function extractRange(ranges, coord) { @@ -860,18 +1101,17 @@ var i; ctx.save(); - ctx.clearRect(0, 0, canvasWidth, canvasHeight); ctx.translate(plotOffset.left, plotOffset.top); // draw background, if any if (options.grid.backgroundColor) { - ctx.fillStyle = options.grid.backgroundColor; + ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); ctx.fillRect(0, 0, plotWidth, plotHeight); } // draw markings - if (options.grid.markings) { - var markings = options.grid.markings; + var markings = options.grid.markings; + if (markings) { if ($.isFunction(markings)) // xmin etc. are backwards-compatible, to be removed in future markings = markings({ xmin: axes.xaxis.min, xmax: axes.xaxis.max, ymin: axes.yaxis.min, ymax: axes.yaxis.max, xaxis: axes.xaxis, yaxis: axes.yaxis, x2axis: axes.x2axis, y2axis: axes.y2axis }); @@ -912,19 +1152,21 @@ if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line + ctx.beginPath(); ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; - ctx.moveTo(Math.floor(xrange.from), Math.floor(yrange.from)); - ctx.lineTo(Math.floor(xrange.to), Math.floor(yrange.to)); + //ctx.moveTo(Math.floor(xrange.from), yrange.from); + //ctx.lineTo(Math.floor(xrange.to), yrange.to); + ctx.moveTo(xrange.from, yrange.from); + ctx.lineTo(xrange.to, yrange.to); ctx.stroke(); } else { // fill area ctx.fillStyle = m.color || options.grid.markingsColor; - ctx.fillRect(Math.floor(xrange.from), - Math.floor(yrange.to), - Math.floor(xrange.to - xrange.from), - Math.floor(yrange.from - yrange.to)); + ctx.fillRect(xrange.from, yrange.to, + xrange.to - xrange.from, + yrange.from - yrange.to); } } } @@ -933,11 +1175,13 @@ ctx.lineWidth = 1; ctx.strokeStyle = options.grid.tickColor; ctx.beginPath(); - var v, axis = axes.xaxis; + var v, axis = axes.xaxis, + bw = options.grid.borderWidth; for (i = 0; i < axis.ticks.length; ++i) { v = axis.ticks[i].v; - if (v <= axis.min || v >= axes.xaxis.max) - continue; // skip those lying on the axes + if (v < axis.min || v > axis.max || + (bw > 0 && (v == axis.min || v == axis.max))) + continue; // skip those lying on the axes if we got a border ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 0); ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, plotHeight); @@ -946,7 +1190,8 @@ axis = axes.yaxis; for (i = 0; i < axis.ticks.length; ++i) { v = axis.ticks[i].v; - if (v <= axis.min || v >= axis.max) + if (v < axis.min || v > axis.max || + (bw > 0 && (v == axis.min || v == axis.max))) continue; ctx.moveTo(0, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); @@ -956,7 +1201,8 @@ axis = axes.x2axis; for (i = 0; i < axis.ticks.length; ++i) { v = axis.ticks[i].v; - if (v <= axis.min || v >= axis.max) + if (v < axis.min || v > axis.max || + (bw > 0 && (v == axis.min || v == axis.max))) continue; ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, -5); @@ -966,7 +1212,8 @@ axis = axes.y2axis; for (i = 0; i < axis.ticks.length; ++i) { v = axis.ticks[i].v; - if (v <= axis.min || v >= axis.max) + if (v < axis.min || v > axis.max || + (bw > 0 && (v == axis.min || v == axis.max))) continue; ctx.moveTo(plotWidth-5, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); @@ -977,53 +1224,54 @@ if (options.grid.borderWidth) { // draw border - ctx.lineWidth = options.grid.borderWidth; - ctx.strokeStyle = options.grid.color; - ctx.lineJoin = "round"; - ctx.strokeRect(0, 0, plotWidth, plotHeight); + ctx.lineWidth = bw; + ctx.strokeStyle = options.grid.borderColor; + ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); } ctx.restore(); } - + function insertLabels() { - target.find(".tickLabels").remove(); + placeholder.find(".tickLabels").remove(); - var html = '
'; + var html = ['
']; function addLabels(axis, labelGenerator) { for (var i = 0; i < axis.ticks.length; ++i) { var tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; - html += labelGenerator(tick, axis); + html.push(labelGenerator(tick, axis)); } } + + var margin = options.grid.labelMargin + options.grid.borderWidth; addLabels(axes.xaxis, function (tick, axis) { - return '
' + tick.label + "
"; + return '
' + tick.label + "
"; }); addLabels(axes.yaxis, function (tick, axis) { - return '
' + tick.label + "
"; + return '
' + tick.label + "
"; }); addLabels(axes.x2axis, function (tick, axis) { - return '
' + tick.label + "
"; + return '
' + tick.label + "
"; }); addLabels(axes.y2axis, function (tick, axis) { - return '
' + tick.label + "
"; + return '
' + tick.label + "
"; }); - html += '
'; + html.push('
'); - target.append(html); + placeholder.append(html.join("")); } function drawSeries(series) { - if (series.lines.show || (!series.bars.show && !series.points.show)) + if (series.lines.show) drawSeriesLines(series); if (series.bars.show) drawSeriesBars(series); @@ -1032,19 +1280,18 @@ } function drawSeriesLines(series) { - function plotLine(data, offset, axisx, axisy) { - var prev, cur = null, drawx = null, drawy = null; + function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { + var points = datapoints.points, + ps = datapoints.pointsize, + prevx = null, prevy = null; ctx.beginPath(); - for (var i = 0; i < data.length; ++i) { - prev = cur; - cur = data[i]; - - if (prev == null || cur == null) - continue; + for (var i = ps; i < points.length; i += ps) { + var x1 = points[i - ps], y1 = points[i - ps + 1], + x2 = points[i], y2 = points[i + 1]; - var x1 = prev[0], y1 = prev[1], - x2 = cur[0], y2 = cur[1]; + if (x1 == null || x2 == null) + continue; // clip with ymin if (y1 <= y2 && y1 < axisy.min) { @@ -1103,41 +1350,58 @@ x2 = axisx.max; } - if (drawx != axisx.p2c(x1) || drawy != axisy.p2c(y1) + offset) - ctx.moveTo(axisx.p2c(x1), axisy.p2c(y1) + offset); + if (x1 != prevx || y1 != prevy) + ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); - drawx = axisx.p2c(x2); - drawy = axisy.p2c(y2) + offset; - ctx.lineTo(drawx, drawy); + prevx = x2; + prevy = y2; + ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); } ctx.stroke(); } - function plotLineArea(data, axisx, axisy) { - var prev, cur = null; - - var bottom = Math.min(Math.max(0, axisy.min), axisy.max); - var top, lastX = 0; + function plotLineArea(datapoints, axisx, axisy) { + var points = datapoints.points, + ps = datapoints.pointsize, + bottom = Math.min(Math.max(0, axisy.min), axisy.max), + i = 0, top, areaOpen = false, + ypos = 1, segmentStart = 0, segmentEnd = 0; - var areaOpen = false; - - for (var i = 0; i < data.length; ++i) { - prev = cur; - cur = data[i]; + // we process each segment in two turns, first forward + // direction to sketch out top, then once we hit the + // end we go backwards to sketch the bottom + while (true) { + if (ps > 0 && i > points.length + ps) + break; - if (areaOpen && prev != null && cur == null) { - // close area - ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom)); - ctx.fill(); - areaOpen = false; - continue; + i += ps; // ps is negative if going backwards + + var x1 = points[i - ps], + y1 = points[i - ps + ypos], + x2 = points[i], y2 = points[i + ypos]; + + if (areaOpen) { + if (ps > 0 && x1 != null && x2 == null) { + // at turning point + segmentEnd = i; + ps = -ps; + ypos = 2; + continue; + } + + if (ps < 0 && i == segmentStart + ps) { + // done with the reverse sweep + ctx.fill(); + areaOpen = false; + ps = -ps; + ypos = 1; + i = segmentStart = segmentEnd + ps; + continue; + } } - if (prev == null || cur == null) + if (x1 == null || x2 == null) continue; - - var x1 = prev[0], y1 = prev[1], - x2 = cur[0], y2 = cur[1]; // clip x values @@ -1189,11 +1453,13 @@ } // else it's a bit more complicated, there might - // be two rectangles and two triangles we need to fill - // in; to find these keep track of the current x values + // be a flat maxed out rectangle first, then a + // triangular cutout or reverse; to find these + // keep track of the current x values var x1old = x1, x2old = x2; - // and clip the y values, without shortcutting + // clip the y values, without shortcutting, we + // go through all cases in turn // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { @@ -1215,98 +1481,73 @@ y2 = axisy.max; } - // if the x value was changed we got a rectangle // to fill if (x1 != x1old) { - if (y1 <= axisy.min) - top = axisy.min; - else - top = axisy.max; - - ctx.lineTo(axisx.p2c(x1old), axisy.p2c(top)); - ctx.lineTo(axisx.p2c(x1), axisy.p2c(top)); + ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); + // it goes to (x1, y1), but we fill that below } - // fill the triangles + // fill triangular section, this sometimes result + // in redundant points if (x1, y1) hasn't changed + // from previous line to, but we just ignore that ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); // fill the other rectangle if it's there if (x2 != x2old) { - if (y2 <= axisy.min) - top = axisy.min; - else - top = axisy.max; - - ctx.lineTo(axisx.p2c(x2old), axisy.p2c(top)); - ctx.lineTo(axisx.p2c(x2), axisy.p2c(top)); + ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); + ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2)); } - - lastX = Math.max(x2, x2old); - } - - if (areaOpen) { - ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom)); - ctx.fill(); } } - + ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.lineJoin = "round"; - var lw = series.lines.lineWidth; - var sw = series.shadowSize; + var lw = series.lines.lineWidth, + sw = series.shadowSize; // FIXME: consider another form of shadow when filling is turned on - if (sw > 0) { - // draw shadow in two steps - ctx.lineWidth = sw / 2; + if (lw > 0 && sw > 0) { + // draw shadow as a thick and thin line with transparency + ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; - plotLine(series.data, lw/2 + sw/2 + ctx.lineWidth/2, series.xaxis, series.yaxis); - - ctx.lineWidth = sw / 2; - ctx.strokeStyle = "rgba(0,0,0,0.2)"; - plotLine(series.data, lw/2 + ctx.lineWidth/2, series.xaxis, series.yaxis); + // position shadow at angle from the mid of line + var angle = Math.PI/18; + plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis); + ctx.lineWidth = sw/2; + plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; - setFillStyle(series.lines, series.color); - if (series.lines.fill) - plotLineArea(series.data, series.xaxis, series.yaxis); - plotLine(series.data, 0, series.xaxis, series.yaxis); + var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); + if (fillStyle) { + ctx.fillStyle = fillStyle; + plotLineArea(series.datapoints, series.xaxis, series.yaxis); + } + + if (lw > 0) + plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); ctx.restore(); } function drawSeriesPoints(series) { - function plotPoints(data, radius, fill, axisx, axisy) { - for (var i = 0; i < data.length; ++i) { - if (data[i] == null) - continue; - - var x = data[i][0], y = data[i][1]; - if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) + function plotPoints(datapoints, radius, fillStyle, offset, circumference, axisx, axisy) { + var points = datapoints.points, ps = datapoints.pointsize; + + for (var i = 0; i < points.length; i += ps) { + var x = points[i], y = points[i + 1]; + if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); - ctx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, true); - if (fill) + ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, circumference, false); + if (fillStyle) { + ctx.fillStyle = fillStyle; ctx.fill(); - ctx.stroke(); - } - } - - function plotPointShadows(data, offset, radius, axisx, axisy) { - for (var i = 0; i < data.length; ++i) { - if (data[i] == null) - continue; - - var x = data[i][0], y = data[i][1]; - if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) - continue; - ctx.beginPath(); - ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, Math.PI, false); + } ctx.stroke(); } } @@ -1314,43 +1555,70 @@ ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); - var lw = series.lines.lineWidth; - var sw = series.shadowSize; - if (sw > 0) { + var lw = series.lines.lineWidth, + sw = series.shadowSize, + radius = series.points.radius; + if (lw > 0 && sw > 0) { // draw shadow in two steps - ctx.lineWidth = sw / 2; + var w = sw / 2; + ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; - plotPointShadows(series.data, sw/2 + ctx.lineWidth/2, - series.points.radius, series.xaxis, series.yaxis); + plotPoints(series.datapoints, radius, null, w + w/2, Math.PI, + series.xaxis, series.yaxis); - ctx.lineWidth = sw / 2; ctx.strokeStyle = "rgba(0,0,0,0.2)"; - plotPointShadows(series.data, ctx.lineWidth/2, - series.points.radius, series.xaxis, series.yaxis); + plotPoints(series.datapoints, radius, null, w/2, Math.PI, + series.xaxis, series.yaxis); } - ctx.lineWidth = series.points.lineWidth; + ctx.lineWidth = lw; ctx.strokeStyle = series.color; - setFillStyle(series.points, series.color); - plotPoints(series.data, series.points.radius, series.points.fill, + plotPoints(series.datapoints, radius, + getFillStyle(series.points, series.color), 0, 2 * Math.PI, series.xaxis, series.yaxis); ctx.restore(); } - function drawBar(x, y, barLeft, barRight, offset, fill, axisx, axisy, c) { - var drawLeft = true, drawRight = true, - drawTop = true, drawBottom = false, - left = x + barLeft, right = x + barRight, - bottom = 0, top = y; + function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal) { + var left, right, bottom, top, + drawLeft, drawRight, drawTop, drawBottom, + tmp; - // account for negative bars - if (top < bottom) { - top = 0; - bottom = y; - drawBottom = true; - drawTop = false; + if (horizontal) { + drawBottom = drawRight = drawTop = true; + drawLeft = false; + left = b; + right = x; + top = y + barLeft; + bottom = y + barRight; + + // account for negative bars + if (right < left) { + tmp = right; + right = left; + left = tmp; + drawLeft = true; + drawRight = false; + } } - + else { + drawLeft = drawRight = drawTop = true; + drawBottom = false; + left = x + barLeft; + right = x + barRight; + bottom = b; + top = y; + + // account for negative bars + if (top < bottom) { + tmp = top; + top = bottom; + bottom = tmp; + drawBottom = true; + drawTop = false; + } + } + // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) @@ -1376,24 +1644,27 @@ drawTop = false; } + left = axisx.p2c(left); + bottom = axisy.p2c(bottom); + right = axisx.p2c(right); + top = axisy.p2c(top); + // fill the bar - if (fill) { + if (fillStyleCallback) { c.beginPath(); - c.moveTo(axisx.p2c(left), axisy.p2c(bottom) + offset); - c.lineTo(axisx.p2c(left), axisy.p2c(top) + offset); - c.lineTo(axisx.p2c(right), axisy.p2c(top) + offset); - c.lineTo(axisx.p2c(right), axisy.p2c(bottom) + offset); + c.moveTo(left, bottom); + c.lineTo(left, top); + c.lineTo(right, top); + c.lineTo(right, bottom); + c.fillStyle = fillStyleCallback(bottom, top); c.fill(); } // draw outline if (drawLeft || drawRight || drawTop || drawBottom) { c.beginPath(); - left = axisx.p2c(left); - bottom = axisy.p2c(bottom); - right = axisx.p2c(right); - top = axisy.p2c(top); - + + // FIXME: inline moveTo is buggy with excanvas c.moveTo(left, bottom + offset); if (drawLeft) c.lineTo(left, top + offset); @@ -1416,67 +1687,54 @@ } function drawSeriesBars(series) { - function plotBars(data, barLeft, barRight, offset, fill, axisx, axisy) { - for (var i = 0; i < data.length; i++) { - if (data[i] == null) + function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) { + var points = datapoints.points, ps = datapoints.pointsize; + + for (var i = 0; i < points.length; i += ps) { + if (points[i] == null) continue; - drawBar(data[i][0], data[i][1], barLeft, barRight, offset, fill, axisx, axisy, ctx); + drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); - ctx.lineJoin = "round"; - - // FIXME: figure out a way to add shadows - /* - var bw = series.bars.barWidth; - var lw = series.bars.lineWidth; - var sw = series.shadowSize; - if (sw > 0) { - // draw shadow in two steps - ctx.lineWidth = sw / 2; - ctx.strokeStyle = "rgba(0,0,0,0.1)"; - plotBars(series.data, bw, lw/2 + sw/2 + ctx.lineWidth/2, false); - - ctx.lineWidth = sw / 2; - ctx.strokeStyle = "rgba(0,0,0,0.2)"; - plotBars(series.data, bw, lw/2 + ctx.lineWidth/2, false); - }*/ + // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; - setFillStyle(series.bars, series.color); var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; - plotBars(series.data, barLeft, barLeft + series.bars.barWidth, 0, series.bars.fill, series.xaxis, series.yaxis); + var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; + plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } - function setFillStyle(obj, seriesColor) { - var fill = obj.fill; + function getFillStyle(filloptions, seriesColor, bottom, top) { + var fill = filloptions.fill; if (!fill) - return; + return null; + + if (filloptions.fillColor) + return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); - if (obj.fillColor) - ctx.fillStyle = obj.fillColor; - else { - var c = parseColor(seriesColor); - c.a = typeof fill == "number" ? fill : 0.4; - c.normalize(); - ctx.fillStyle = c.toString(); - } + var c = $.color.parse(seriesColor); + c.a = typeof fill == "number" ? fill : 0.4; + c.normalize(); + return c.toString(); } function insertLegend() { - target.find(".legend").remove(); + placeholder.find(".legend").remove(); if (!options.legend.show) return; - var fragments = []; - var rowStarted = false; + var fragments = [], rowStarted = false, + lf = options.legend.labelFormatter, s, label; for (i = 0; i < series.length; ++i) { - if (!series[i].label) + s = series[i]; + label = s.label; + if (!label) continue; if (i % options.legend.noColumns == 0) { @@ -1486,12 +1744,11 @@ rowStarted = true; } - var label = series[i].label; - if (options.legend.labelFormatter != null) - label = options.legend.labelFormatter(label); + if (lf) + label = lf(label, s); fragments.push( - '
' + + '
' + '' + label + ''); } if (rowStarted) @@ -1502,35 +1759,38 @@ var table = '' + fragments.join("") + '
'; if (options.legend.container != null) - options.legend.container.html(table); + $(options.legend.container).html(table); else { - var pos = ""; - var p = options.legend.position, m = options.legend.margin; + var pos = "", + p = options.legend.position, + m = options.legend.margin; + if (m[0] == null) + m = [m, m]; if (p.charAt(0) == "n") - pos += 'top:' + (m + plotOffset.top) + 'px;'; + pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; else if (p.charAt(0) == "s") - pos += 'bottom:' + (m + plotOffset.bottom) + 'px;'; + pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; if (p.charAt(1) == "e") - pos += 'right:' + (m + plotOffset.right) + 'px;'; + pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") - pos += 'left:' + (m + plotOffset.left) + 'px;'; - var legend = $('
' + table.replace('style="', 'style="position:absolute;' + pos +';') + '
').appendTo(target); + pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; + var legend = $('
' + table.replace('style="', 'style="position:absolute;' + pos +';') + '
').appendTo(placeholder); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { - var tmp; - if (options.grid.backgroundColor) - tmp = options.grid.backgroundColor; + c = options.grid.backgroundColor; + if (c && typeof c == "string") + c = $.color.parse(c); else - tmp = extractColor(legend); - c = parseColor(tmp).adjust(null, null, null, 1).toString(); + c = $.color.extract(legend, 'background-color'); + c.a = 1; + c = c.toString(); } var div = legend.children(); $('
').prependTo(legend).css('opacity', options.legend.backgroundOpacity); - } } } @@ -1538,144 +1798,104 @@ // interactive features - var lastMousePos = { pageX: null, pageY: null }, - selection = { - first: { x: -1, y: -1}, second: { x: -1, y: -1}, - show: false, active: false }, - highlights = [], - clickIsMouseUp = false, - redrawTimeout = null, - hoverTimeout = null; + var highlights = [], + redrawTimeout = null; - // Returns the data item the mouse is over, or null if none is found - function findNearbyItem(mouseX, mouseY) { + // returns the data item the mouse is over, or null if none is found + function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, - lowestDistance = maxDistance * maxDistance + 1, - item = null, foundPoint = false; + smallestDistance = maxDistance * maxDistance + 1, + item = null, foundPoint = false, i, j; - function result(i, j) { - return { datapoint: series[i].data[j], + for (i = series.length - 1; i >= 0; --i) { + if (!seriesFilter(series[i])) + continue; + + var s = series[i], + axisx = s.xaxis, + axisy = s.yaxis, + points = s.datapoints.points, + ps = s.datapoints.pointsize, + mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster + my = axisy.c2p(mouseY), + maxx = maxDistance / axisx.scale, + maxy = maxDistance / axisy.scale; + + if (s.lines.show || s.points.show) { + for (j = 0; j < points.length; j += ps) { + var x = points[j], y = points[j + 1]; + if (x == null) + continue; + + // For points and lines, the cursor must be within a + // certain distance to the data point + if (x - mx > maxx || x - mx < -maxx || + y - my > maxy || y - my < -maxy) + continue; + + // We have to calculate distances in pixels, not in + // data units, because the scales of the axes may be different + var dx = Math.abs(axisx.p2c(x) - mouseX), + dy = Math.abs(axisy.p2c(y) - mouseY), + dist = dx * dx + dy * dy; // we save the sqrt + + // use <= to ensure last point takes precedence + // (last generally means on top of) + if (dist < smallestDistance) { + smallestDistance = dist; + item = [i, j / ps]; + } + } + } + + if (s.bars.show && !item) { // no other point can be nearby + var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2, + barRight = barLeft + s.bars.barWidth; + + for (j = 0; j < points.length; j += ps) { + var x = points[j], y = points[j + 1], b = points[j + 2]; + if (x == null) + continue; + + // for a bar graph, the cursor must be inside the bar + if (series[i].bars.horizontal ? + (mx <= Math.max(b, x) && mx >= Math.min(b, x) && + my >= y + barLeft && my <= y + barRight) : + (mx >= x + barLeft && mx <= x + barRight && + my >= Math.min(b, y) && my <= Math.max(b, y))) + item = [i, j / ps]; + } + } + } + + if (item) { + i = item[0]; + j = item[1]; + ps = series[i].datapoints.pointsize; + + return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } - for (var i = 0; i < series.length; ++i) { - var data = series[i].data, - axisx = series[i].xaxis, - axisy = series[i].yaxis, - - // precompute some stuff to make the loop faster - mx = axisx.c2p(mouseX), - my = axisy.c2p(mouseY), - maxx = maxDistance / axisx.scale, - maxy = maxDistance / axisy.scale, - checkbar = series[i].bars.show, - checkpoint = !(series[i].bars.show && !(series[i].lines.show || series[i].points.show)), - barLeft = series[i].bars.align == "left" ? 0 : -series[i].bars.barWidth/2, - barRight = barLeft + series[i].bars.barWidth; - for (var j = 0; j < data.length; ++j) { - if (data[j] == null) - continue; - - var x = data[j][0], y = data[j][1]; - - if (checkbar) { - // For a bar graph, the cursor must be inside the bar - // and no other point can be nearby - if (!foundPoint && mx >= x + barLeft && - mx <= x + barRight && - my >= Math.min(0, y) && my <= Math.max(0, y)) - item = result(i, j); - } - - if (checkpoint) { - // For points and lines, the cursor must be within a - // certain distance to the data point - - // check bounding box first - if ((x - mx > maxx || x - mx < -maxx) || - (y - my > maxy || y - my < -maxy)) - continue; - - // We have to calculate distances in pixels, not in - // data units, because the scale of the axes may be different - var dx = Math.abs(axisx.p2c(x) - mouseX), - dy = Math.abs(axisy.p2c(y) - mouseY), - dist = dx * dx + dy * dy; - if (dist < lowestDistance) { - lowestDistance = dist; - foundPoint = true; - item = result(i, j); - } - } - } - } - - return item; + return null; } - function onMouseMove(ev) { - // FIXME: temp. work-around until jQuery bug 1871 is fixed - var e = ev || window.event; - if (e.pageX == null && e.clientX != null) { - var de = document.documentElement, b = document.body; - lastMousePos.pageX = e.clientX + (de && de.scrollLeft || b.scrollLeft || 0); - lastMousePos.pageY = e.clientY + (de && de.scrollTop || b.scrollTop || 0); - } - else { - lastMousePos.pageX = e.pageX; - lastMousePos.pageY = e.pageY; - } - - if (options.grid.hoverable && !hoverTimeout) - hoverTimeout = setTimeout(onHover, 100); - - if (selection.active) - updateSelection(lastMousePos); + function onMouseMove(e) { + if (options.grid.hoverable) + triggerClickHoverEvent("plothover", e, + function (s) { return s["hoverable"] != false; }); } - function onMouseDown(e) { - if (e.which != 1) // only accept left-click - return; - - // cancel out any text selections - document.body.focus(); - - // prevent text selection and drag in old-school browsers - if (document.onselectstart !== undefined && workarounds.onselectstart == null) { - workarounds.onselectstart = document.onselectstart; - document.onselectstart = function () { return false; }; - } - if (document.ondrag !== undefined && workarounds.ondrag == null) { - workarounds.ondrag = document.ondrag; - document.ondrag = function () { return false; }; - } - - setSelectionPos(selection.first, e); - - lastMousePos.pageX = null; - selection.active = true; - $(document).one("mouseup", onSelectionMouseUp); - } - function onClick(e) { - if (clickIsMouseUp) { - clickIsMouseUp = false; - return; - } - - triggerClickHoverEvent("plotclick", e); - } - - function onHover() { - triggerClickHoverEvent("plothover", lastMousePos); - hoverTimeout = null; + triggerClickHoverEvent("plotclick", e, + function (s) { return s["clickable"] != false; }); } // trigger click or hover event (they send the same parameters // so we share their code) - function triggerClickHoverEvent(eventname, event) { + function triggerClickHoverEvent(eventname, event, seriesFilter) { var offset = eventHolder.offset(), pos = { pageX: event.pageX, pageY: event.pageY }, canvasX = event.pageX - offset.left - plotOffset.left, @@ -1690,45 +1910,44 @@ if (axes.y2axis.used) pos.y2 = axes.y2axis.c2p(canvasY); - var item = findNearbyItem(canvasX, canvasY); + var item = findNearbyItem(canvasX, canvasY, seriesFilter); if (item) { // fill in mouse pos for any listeners out there item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left); item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top); - - } if (options.grid.autoHighlight) { + // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; - if (h.auto && + if (h.auto == eventname && !(item && h.series == item.series && h.point == item.datapoint)) unhighlight(h.series, h.point); } if (item) - highlight(item.series, item.datapoint, true); + highlight(item.series, item.datapoint, eventname); } - target.trigger(eventname, [ pos, item ]); + placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { if (!redrawTimeout) - redrawTimeout = setTimeout(redrawOverlay, 50); + redrawTimeout = setTimeout(drawOverlay, 30); } - function redrawOverlay() { + function drawOverlay() { redrawTimeout = null; - // redraw highlights + // draw highlights octx.save(); octx.clearRect(0, 0, canvasWidth, canvasHeight); octx.translate(plotOffset.left, plotOffset.top); - var i, hi; + var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; @@ -1738,22 +1957,8 @@ drawPointHighlight(hi.series, hi.point); } octx.restore(); - - // redraw selection - if (selection.show && selectionIsSane()) { - octx.strokeStyle = parseColor(options.selection.color).scale(null, null, null, 0.8).toString(); - octx.lineWidth = 1; - ctx.lineJoin = "round"; - octx.fillStyle = parseColor(options.selection.color).scale(null, null, null, 0.4).toString(); - - var x = Math.min(selection.first.x, selection.second.x), - y = Math.min(selection.first.y, selection.second.y), - w = Math.abs(selection.second.x - selection.first.x), - h = Math.abs(selection.second.y - selection.first.y); - - octx.fillRect(x + plotOffset.left, y + plotOffset.top, w, h); - octx.strokeRect(x + plotOffset.left, y + plotOffset.top, w, h); - } + + executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { @@ -1774,6 +1979,11 @@ } function unhighlight(s, point) { + if (s == null && point == null) { + highlights = []; + triggerRedrawOverlay(); + } + if (typeof s == "number") s = series[s]; @@ -1807,151 +2017,52 @@ var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; - octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); + octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var radius = 1.5 * pointRadius; octx.beginPath(); - octx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, true); + octx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, false); octx.stroke(); } function drawBarHighlight(series, point) { - octx.lineJoin = "round"; octx.lineWidth = series.bars.lineWidth; - octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); - octx.fillStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); + octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); + var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; - drawBar(point[0], point[1], barLeft, barLeft + series.bars.barWidth, - 0, true, series.xaxis, series.yaxis, octx); - } - - function triggerSelectedEvent() { - var x1 = Math.min(selection.first.x, selection.second.x), - x2 = Math.max(selection.first.x, selection.second.x), - y1 = Math.max(selection.first.y, selection.second.y), - y2 = Math.min(selection.first.y, selection.second.y); - - var r = {}; - if (axes.xaxis.used) - r.xaxis = { from: axes.xaxis.c2p(x1), to: axes.xaxis.c2p(x2) }; - if (axes.x2axis.used) - r.x2axis = { from: axes.x2axis.c2p(x1), to: axes.x2axis.c2p(x2) }; - if (axes.yaxis.used) - r.yaxis = { from: axes.yaxis.c2p(y1), to: axes.yaxis.c2p(y2) }; - if (axes.y2axis.used) - r.yaxis = { from: axes.y2axis.c2p(y1), to: axes.y2axis.c2p(y2) }; - - target.trigger("plotselected", [ r ]); - - // backwards-compat stuff, to be removed in future - if (axes.xaxis.used && axes.yaxis.used) - target.trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); - } - - function onSelectionMouseUp(e) { - // revert drag stuff for old-school browsers - if (document.onselectstart !== undefined) - document.onselectstart = workarounds.onselectstart; - if (document.ondrag !== undefined) - document.ondrag = workarounds.ondrag; - - // no more draggy-dee-drag - selection.active = false; - updateSelection(e); - - if (selectionIsSane()) { - triggerSelectedEvent(); - clickIsMouseUp = true; - } - - return false; + drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, + 0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal); } - function setSelectionPos(pos, e) { - var offset = eventHolder.offset(); - if (options.selection.mode == "y") { - if (pos == selection.first) - pos.x = 0; - else - pos.x = plotWidth; - } + function getColorOrGradient(spec, bottom, top, defaultColor) { + if (typeof spec == "string") + return spec; else { - pos.x = e.pageX - offset.left - plotOffset.left; - pos.x = Math.min(Math.max(0, pos.x), plotWidth); - } - - if (options.selection.mode == "x") { - if (pos == selection.first) - pos.y = 0; - else - pos.y = plotHeight; - } - else { - pos.y = e.pageY - offset.top - plotOffset.top; - pos.y = Math.min(Math.max(0, pos.y), plotHeight); - } - } - - function updateSelection(pos) { - if (pos.pageX == null) - return; - - setSelectionPos(selection.second, pos); - if (selectionIsSane()) { - selection.show = true; - triggerRedrawOverlay(); - } - else - clearSelection(); - } - - function clearSelection() { - if (selection.show) { - selection.show = false; - triggerRedrawOverlay(); - } - } - - function setSelection(ranges, preventEvent) { - var range; - - if (options.selection.mode == "y") { - selection.first.x = 0; - selection.second.x = plotWidth; - } - else { - range = extractRange(ranges, "x"); + // assume this is a gradient spec; IE currently only + // supports a simple vertical gradient properly, so that's + // what we support too + var gradient = ctx.createLinearGradient(0, top, 0, bottom); - selection.first.x = range.axis.p2c(range.from); - selection.second.x = range.axis.p2c(range.to); - } - - if (options.selection.mode == "x") { - selection.first.y = 0; - selection.second.y = plotHeight; - } - else { - range = extractRange(ranges, "y"); + for (var i = 0, l = spec.colors.length; i < l; ++i) { + var c = spec.colors[i]; + if (typeof c != "string") { + var co = $.color.parse(defaultColor); + if (c.brightness != null) + co = co.scale('rgb', c.brightness) + if (c.opacity != null) + co.a *= c.opacity; + c = co.toString(); + } + gradient.addColorStop(i / (l - 1), c); + } - selection.first.y = range.axis.p2c(range.from); - selection.second.y = range.axis.p2c(range.to); + return gradient; } - - selection.show = true; - triggerRedrawOverlay(); - if (!preventEvent) - triggerSelectedEvent(); - } - - function selectionIsSane() { - var minSize = 5; - return Math.abs(selection.second.x - selection.first.x) >= minSize && - Math.abs(selection.second.y - selection.first.y) >= minSize; } } - - $.plot = function(target, data, options) { - var plot = new Plot(target, data, options); - /*var t0 = new Date(); + + $.plot = function(placeholder, data, options) { + var plot = new Plot($(placeholder), data, options, $.plot.plugins); + /*var t0 = new Date(); var t1 = new Date(); var tstr = "time used (msecs): " + (t1.getTime() - t0.getTime()) if (window.console) @@ -1960,177 +2071,65 @@ alert(tstr);*/ return plot; }; + + $.plot.plugins = []; + + // returns a string with the date d formatted according to fmt + $.plot.formatDate = function(d, fmt, monthNames) { + var leftPad = function(n) { + n = "" + n; + return n.length == 1 ? "0" + n : n; + }; + + var r = []; + var escape = false; + var hours = d.getUTCHours(); + var isAM = hours < 12; + if (monthNames == null) + monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + + if (fmt.search(/%p|%P/) != -1) { + if (hours > 12) { + hours = hours - 12; + } else if (hours == 0) { + hours = 12; + } + } + for (var i = 0; i < fmt.length; ++i) { + var c = fmt.charAt(i); + + if (escape) { + switch (c) { + case 'h': c = "" + hours; break; + case 'H': c = leftPad(hours); break; + case 'M': c = leftPad(d.getUTCMinutes()); break; + case 'S': c = leftPad(d.getUTCSeconds()); break; + case 'd': c = "" + d.getUTCDate(); break; + case 'm': c = "" + (d.getUTCMonth() + 1); break; + case 'y': c = "" + d.getUTCFullYear(); break; + case 'b': c = "" + monthNames[d.getUTCMonth()]; break; + case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; + case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; + } + r.push(c); + escape = false; + } + else { + if (c == "%") + escape = true; + else + r.push(c); + } + } + return r.join(""); + }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } - function clamp(min, value, max) { - if (value < min) - return value; - else if (value > max) - return max; - else - return value; - } - - // color helpers, inspiration from the jquery color animation - // plugin by John Resig - function Color (r, g, b, a) { - - var rgba = ['r','g','b','a']; - var x = 4; //rgba.length - - while (-1<--x) { - this[rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0); - } - - this.toString = function() { - if (this.a >= 1.0) { - return "rgb("+[this.r,this.g,this.b].join(",")+")"; - } else { - return "rgba("+[this.r,this.g,this.b,this.a].join(",")+")"; - } - }; - - this.scale = function(rf, gf, bf, af) { - x = 4; //rgba.length - while (-1<--x) { - if (arguments[x] != null) - this[rgba[x]] *= arguments[x]; - } - return this.normalize(); - }; - - this.adjust = function(rd, gd, bd, ad) { - x = 4; //rgba.length - while (-1<--x) { - if (arguments[x] != null) - this[rgba[x]] += arguments[x]; - } - return this.normalize(); - }; - - this.clone = function() { - return new Color(this.r, this.b, this.g, this.a); - }; - - var limit = function(val,minVal,maxVal) { - return Math.max(Math.min(val, maxVal), minVal); - }; - - this.normalize = function() { - this.r = limit(parseInt(this.r), 0, 255); - this.g = limit(parseInt(this.g), 0, 255); - this.b = limit(parseInt(this.b), 0, 255); - this.a = limit(this.a, 0, 1); - return this; - }; - - this.normalize(); - } - - var lookupColors = { - aqua:[0,255,255], - azure:[240,255,255], - beige:[245,245,220], - black:[0,0,0], - blue:[0,0,255], - brown:[165,42,42], - cyan:[0,255,255], - darkblue:[0,0,139], - darkcyan:[0,139,139], - darkgrey:[169,169,169], - darkgreen:[0,100,0], - darkkhaki:[189,183,107], - darkmagenta:[139,0,139], - darkolivegreen:[85,107,47], - darkorange:[255,140,0], - darkorchid:[153,50,204], - darkred:[139,0,0], - darksalmon:[233,150,122], - darkviolet:[148,0,211], - fuchsia:[255,0,255], - gold:[255,215,0], - green:[0,128,0], - indigo:[75,0,130], - khaki:[240,230,140], - lightblue:[173,216,230], - lightcyan:[224,255,255], - lightgreen:[144,238,144], - lightgrey:[211,211,211], - lightpink:[255,182,193], - lightyellow:[255,255,224], - lime:[0,255,0], - magenta:[255,0,255], - maroon:[128,0,0], - navy:[0,0,128], - olive:[128,128,0], - orange:[255,165,0], - pink:[255,192,203], - purple:[128,0,128], - violet:[128,0,128], - red:[255,0,0], - silver:[192,192,192], - white:[255,255,255], - yellow:[255,255,0] - }; - - function extractColor(element) { - var color, elem = element; - do { - color = elem.css("background-color").toLowerCase(); - // keep going until we find an element that has color, or - // we hit the body - if (color != '' && color != 'transparent') - break; - elem = elem.parent(); - } while (!$.nodeName(elem.get(0), "body")); - - // catch Safari's way of signalling transparent - if (color == "rgba(0, 0, 0, 0)") - return "transparent"; - - return color; - } - - // parse string, returns Color - function parseColor(str) { - var result; - - // Look for rgb(num,num,num) - if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) - return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10)); - - // Look for rgba(num,num,num,num) - if (result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) - return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4])); - - // Look for rgb(num%,num%,num%) - if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) - return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55); - - // Look for rgba(num%,num%,num%,num) - if (result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) - return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4])); - - // Look for #a0b1c2 - if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) - return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)); - - // Look for #fff - if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) - return new Color(parseInt(result[1]+result[1], 16), parseInt(result[2]+result[2], 16), parseInt(result[3]+result[3], 16)); - - // Otherwise, we're most likely dealing with a named color - var name = $.trim(str).toLowerCase(); - if (name == "transparent") - return new Color(255, 255, 255, 0); - else { - result = lookupColors[name]; - return new Color(result[0], result[1], result[2]); - } - } - })(jQuery); + +// for the progress bar +myBar.loaded('jquery.flot.js'); diff --git a/xCAT-UI/js/jquery.flot.pie.js b/xCAT-UI/js/jquery.flot.pie.js new file mode 100644 index 000000000..94213013a --- /dev/null +++ b/xCAT-UI/js/jquery.flot.pie.js @@ -0,0 +1,757 @@ +/* +Flot plugin for rendering pie charts. The plugin assumes the data is +coming is as a single data value for each series, and each of those +values is a positive value or zero (negative numbers don't make +any sense and will cause strange effects). The data values do +NOT need to be passed in as percentage values because it +internally calculates the total and percentages. + +* Created by Brian Medendorp, June 2009 +* Updated November 2009 with contributions from: btburnett3, Anthony Aragues and Xavi Ivars + +* Changes: + 2009-10-22: lineJoin set to round + 2009-10-23: IE full circle fix, donut + 2009-11-11: Added basic hover from btburnett3 - does not work in IE, and center is off in Chrome and Opera + 2009-11-17: Added IE hover capability submitted by Anthony Aragues + 2009-11-18: Added bug fix submitted by Xavi Ivars (issues with arrays when other JS libraries are included as well) + + +Available options are: +series: { + pie: { + show: true/false + radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto' + innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect + startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result + tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show) + offset: { + top: integer value to move the pie up or down + left: integer value to move the pie left or right, or 'auto' + }, + stroke: { + color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF') + width: integer pixel width of the stroke + }, + label: { + show: true/false, or 'auto' + formatter: a user-defined function that modifies the text/style of the label text + radius: 0-1 for percentage of fullsize, or a specified pixel length + background: { + color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000') + opacity: 0-1 + }, + threshold: 0-1 for the percentage value at which to hide labels (if they're too small) + }, + combine: { + threshold: 0-1 for the percentage value at which to combine slices (if they're too small) + color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined + label: any text value of what the combined slice should be labeled + } + highlight: { + opacity: 0-1 + } + } +} + +More detail and specific examples can be found in the included HTML file. + +*/ + +(function ($) +{ + function init(plot) // this is the "body" of the plugin + { + var canvas = null; + var target = null; + var maxRadius = null; + var centerLeft = null; + var centerTop = null; + var total = 0; + var redraw = true; + var redrawAttempts = 10; + var shrink = 0.95; + var legendWidth = 0; + var processed = false; + var raw = false; + + // interactive variables + var highlights = []; + + // add hook to determine if pie plugin in enabled, and then perform necessary operations + plot.hooks.processOptions.push(checkPieEnabled); + plot.hooks.bindEvents.push(bindEvents); + + // check to see if the pie plugin is enabled + function checkPieEnabled(plot, options) + { + if (options.series.pie.show) + { + //disable grid + options.grid.show = false; + + // set labels.show + if (options.series.pie.label.show=='auto') + if (options.legend.show) + options.series.pie.label.show = false; + else + options.series.pie.label.show = true; + + // set radius + if (options.series.pie.radius=='auto') + if (options.series.pie.label.show) + options.series.pie.radius = 3/4; + else + options.series.pie.radius = 1; + + // ensure sane tilt + if (options.series.pie.tilt>1) + options.series.pie.tilt=1; + if (options.series.pie.tilt<0) + options.series.pie.tilt=0; + + // add processData hook to do transformations on the data + plot.hooks.processDatapoints.push(processDatapoints); + plot.hooks.drawOverlay.push(drawOverlay); + + // add draw hook + plot.hooks.draw.push(draw); + } + } + + // bind hoverable events + function bindEvents(plot, eventHolder) + { + var options = plot.getOptions(); + + if (options.series.pie.show && options.grid.hoverable) + eventHolder.unbind('mousemove').mousemove(onMouseMove); + + if (options.series.pie.show && options.grid.clickable) + eventHolder.unbind('click').click(onClick); + } + + + // debugging function that prints out an object + function alertObject(obj) + { + var msg = ''; + function traverse(obj, depth) + { + if (!depth) + depth = 0; + for (var i = 0; i < obj.length; ++i) + { + for (var j=0; jcanvas.width-maxRadius) + centerLeft = canvas.width-maxRadius; + } + + function fixData(data) + { + for (var i = 0; i < data.length; ++i) + { + if (typeof(data[i].data)=='number') + data[i].data = [[1,data[i].data]]; + else if (typeof(data[i].data)=='undefined' || typeof(data[i].data[0])=='undefined') + { + if (typeof(data[i].data)!='undefined' && typeof(data[i].data.label)!='undefined') + data[i].label = data[i].data.label; // fix weirdness coming from flot + data[i].data = [[1,0]]; + + } + } + return data; + } + + function combine(data) + { + data = fixData(data); + calcTotal(data); + var combined = 0; + var numCombined = 0; + var color = options.series.pie.combine.color; + + var newdata = []; + for (var i = 0; i < data.length; ++i) + { + // make sure its a number + data[i].data[0][1] = parseFloat(data[i].data[0][1]); + if (!data[i].data[0][1]) + data[i].data[0][1] = 0; + + if (data[i].data[0][1]/total<=options.series.pie.combine.threshold) + { + combined += data[i].data[0][1]; + numCombined++; + if (!color) + color = data[i].color; + } + else + { + newdata.push({ + data: [[1,data[i].data[0][1]]], + color: data[i].color, + label: data[i].label, + angle: (data[i].data[0][1]*(Math.PI*2))/total, + percent: (data[i].data[0][1]/total*100) + }); + } + } + if (numCombined>0) + newdata.push({ + data: [[1,combined]], + color: color, + label: options.series.pie.combine.label, + angle: (combined*(Math.PI*2))/total, + percent: (combined/total*100) + }); + return newdata; + } + + function draw(plot, newCtx) + { + if (!target) return; // if no series were passed + ctx = newCtx; + + setupPie(); + var slices = plot.getData(); + + var attempts = 0; + while (redraw && attempts0) + maxRadius *= shrink; + attempts += 1; + clear(); + if (options.series.pie.tilt<=0.8) + drawShadow(); + drawPie(); + } + if (attempts >= redrawAttempts) { + clear(); + target.prepend('
Could not draw pie with labels contained inside canvas
'); + } + + if ( plot.setSeries && plot.insertLegend ) + { + plot.setSeries(slices); + plot.insertLegend(); + } + + // we're actually done at this point, just defining internal functions at this point + + function clear() + { + ctx.clearRect(0,0,canvas.width,canvas.height); + target.children().filter('.pieLabel, .pieLabelBackground').remove(); + } + + function drawShadow() + { + var shadowLeft = 5; + var shadowTop = 15; + var edge = 10; + var alpha = 0.02; + + // set radius + if (options.series.pie.radius>1) + var radius = options.series.pie.radius; + else + var radius = maxRadius * options.series.pie.radius; + + if (radius>=(canvas.width/2)-shadowLeft || radius*options.series.pie.tilt>=(canvas.height/2)-shadowTop || radius<=edge) + return; // shadow would be outside canvas, so don't draw it + + ctx.save(); + ctx.translate(shadowLeft,shadowTop); + ctx.globalAlpha = alpha; + ctx.fillStyle = '#000'; + + // center and rotate to starting position + ctx.translate(centerLeft,centerTop); + ctx.scale(1, options.series.pie.tilt); + + //radius -= edge; + for (var i=1; i<=edge; i++) + { + ctx.beginPath(); + ctx.arc(0,0,radius,0,Math.PI*2,false); + ctx.fill(); + radius -= i; + } + + ctx.restore(); + } + + function drawPie() + { + startAngle = Math.PI*options.series.pie.startAngle; + + // set radius + if (options.series.pie.radius>1) + var radius = options.series.pie.radius; + else + var radius = maxRadius * options.series.pie.radius; + + // center and rotate to starting position + ctx.save(); + ctx.translate(centerLeft,centerTop); + ctx.scale(1, options.series.pie.tilt); + //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera + + // draw slices + ctx.save(); + var currentAngle = startAngle; + for (var i = 0; i < slices.length; ++i) + { + slices[i].startAngle = currentAngle; + drawSlice(slices[i].angle, slices[i].color, true); + } + ctx.restore(); + + // draw slice outlines + ctx.save(); + ctx.lineWidth = options.series.pie.stroke.width; + currentAngle = startAngle; + for (var i = 0; i < slices.length; ++i) + drawSlice(slices[i].angle, options.series.pie.stroke.color, false); + ctx.restore(); + + // draw donut hole + drawDonutHole(ctx); + + // draw labels + if (options.series.pie.label.show) + drawLabels(); + + // restore to original state + ctx.restore(); + + function drawSlice(angle, color, fill) + { + if (angle<=0) + return; + + if (fill) + ctx.fillStyle = color; + else + { + ctx.strokeStyle = color; + ctx.lineJoin = 'round'; + } + + ctx.beginPath(); + if (angle!=Math.PI*2) + ctx.moveTo(0,0); // Center of the pie + else if ($.browser.msie) + angle -= 0.0001; + //ctx.arc(0,0,radius,0,angle,false); // This doesn't work properly in Opera + ctx.arc(0,0,radius,currentAngle,currentAngle+angle,false); + ctx.closePath(); + //ctx.rotate(angle); // This doesn't work properly in Opera + currentAngle += angle; + + if (fill) + ctx.fill(); + else + ctx.stroke(); + } + + function drawLabels() + { + var currentAngle = startAngle; + + // set radius + if (options.series.pie.label.radius>1) + var radius = options.series.pie.label.radius; + else + var radius = maxRadius * options.series.pie.label.radius; + + for (var i = 0; i < slices.length; ++i) + { + if (slices[i].percent >= options.series.pie.label.threshold*100) + drawLabel(slices[i], currentAngle, i); + currentAngle += slices[i].angle; + } + + function drawLabel(slice, startAngle, index) + { + if (slice.data[0][1]==0) + return; + + // format label text + var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter; + if (lf) + text = lf(slice.label, slice); + else + text = slice.label; + if (plf) + text = plf(text, slice); + + var halfAngle = ((startAngle+slice.angle) + startAngle)/2; + var x = centerLeft + Math.round(Math.cos(halfAngle) * radius); + var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt; + + var html = '' + text + ""; + target.append(html); + var label = target.children('#pieLabel'+index); + var labelTop = (y - label.height()/2); + var labelLeft = (x - label.width()/2); + label.css('top', labelTop); + label.css('left', labelLeft); + + // check to make sure that the label is not outside the canvas + if (0-labelTop>0 || 0-labelLeft>0 || canvas.height-(labelTop+label.height())<0 || canvas.width-(labelLeft+label.width())<0) + redraw = true; + + if (options.series.pie.label.background.opacity != 0) { + // put in the transparent background separately to avoid blended labels and label boxes + var c = options.series.pie.label.background.color; + if (c == null) { + c = slice.color; + } + var pos = 'top:'+labelTop+'px;left:'+labelLeft+'px;'; + $('
').insertBefore(label).css('opacity', options.series.pie.label.background.opacity); + } + } // end individual label function + } // end drawLabels function + } // end drawPie function + } // end draw function + + // Placed here because it needs to be accessed from multiple locations + function drawDonutHole(layer) + { + // draw donut hole + if(options.series.pie.innerRadius > 0) + { + // subtract the center + layer.save(); + innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius; + layer.globalCompositeOperation = 'destination-out'; // this does not work with excanvas, but it will fall back to using the stroke color + layer.beginPath(); + layer.fillStyle = options.series.pie.stroke.color; + layer.arc(0,0,innerRadius,0,Math.PI*2,false); + layer.fill(); + layer.closePath(); + layer.restore(); + + // add inner stroke + layer.save(); + layer.beginPath(); + layer.strokeStyle = options.series.pie.stroke.color; + layer.arc(0,0,innerRadius,0,Math.PI*2,false); + layer.stroke(); + layer.closePath(); + layer.restore(); + // TODO: add extra shadow inside hole (with a mask) if the pie is tilted. + } + } + + //-- Additional Interactive related functions -- + + function isPointInPoly(poly, pt) + { + for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) + ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1])) + && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0]) + && (c = !c); + return c; + } + + function findNearbySlice(mouseX, mouseY) + { + var slices = plot.getData(), + options = plot.getOptions(), + radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; + + for (var i = 0; i < slices.length; ++i) + { + var s = slices[i]; + + if(s.pie.show) + { + ctx.save(); + ctx.beginPath(); + ctx.moveTo(0,0); // Center of the pie + //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here. + ctx.arc(0,0,radius,s.startAngle,s.startAngle+s.angle,false); + ctx.closePath(); + x = mouseX-centerLeft; + y = mouseY-centerTop; + if(ctx.isPointInPath) + { + if (ctx.isPointInPath(mouseX-centerLeft, mouseY-centerTop)) + { + //alert('found slice!'); + ctx.restore(); + return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i}; + } + } + else + { + // excanvas for IE doesn;t support isPointInPath, this is a workaround. + p1X = (radius * Math.cos(s.startAngle)); + p1Y = (radius * Math.sin(s.startAngle)); + p2X = (radius * Math.cos(s.startAngle+(s.angle/4))); + p2Y = (radius * Math.sin(s.startAngle+(s.angle/4))); + p3X = (radius * Math.cos(s.startAngle+(s.angle/2))); + p3Y = (radius * Math.sin(s.startAngle+(s.angle/2))); + p4X = (radius * Math.cos(s.startAngle+(s.angle/1.5))); + p4Y = (radius * Math.sin(s.startAngle+(s.angle/1.5))); + p5X = (radius * Math.cos(s.startAngle+s.angle)); + p5Y = (radius * Math.sin(s.startAngle+s.angle)); + arrPoly = [[0,0],[p1X,p1Y],[p2X,p2Y],[p3X,p3Y],[p4X,p4Y],[p5X,p5Y]]; + arrPoint = [x,y]; + // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt? + if(isPointInPoly(arrPoly, arrPoint)) + { + ctx.restore(); + return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i}; + } + } + ctx.restore(); + } + } + + return null; + } + + function onMouseMove(e) + { + triggerClickHoverEvent('plothover', e); + } + + function onClick(e) + { + triggerClickHoverEvent('plotclick', e); + } + + // trigger click or hover event (they send the same parameters so we share their code) + function triggerClickHoverEvent(eventname, e) + { + var offset = plot.offset(), + canvasX = parseInt(e.pageX - offset.left), + canvasY = parseInt(e.pageY - offset.top), + item = findNearbySlice(canvasX, canvasY); + + if (options.grid.autoHighlight) + { + // clear auto-highlights + for (var i = 0; i < highlights.length; ++i) + { + var h = highlights[i]; + if (h.auto == eventname && !(item && h.series == item.series)) + unhighlight(h.series); + } + } + + // if no slice was found, quit + if (!item) + return; + + // highlight the slice + highlight(item.series, eventname); + + // trigger any hover bind events + var pos = { pageX: e.pageX, pageY: e.pageY }; + target.trigger(eventname, [ pos, item ]); + } + + function highlight(s, auto) + { + if (typeof s == "number") + s = series[s]; + + var i = indexOfHighlight(s); + if (i == -1) + { + highlights.push({ series: s, auto: auto }); + plot.triggerRedrawOverlay(); + } + else if (!auto) + highlights[i].auto = false; + } + + function unhighlight(s) + { + if (s == null) + { + highlights = []; + plot.triggerRedrawOverlay(); + } + + if (typeof s == "number") + s = series[s]; + + var i = indexOfHighlight(s); + if (i != -1) + { + highlights.splice(i, 1); + plot.triggerRedrawOverlay(); + } + } + + function indexOfHighlight(s) + { + for (var i = 0; i < highlights.length; ++i) + { + var h = highlights[i]; + if (h.series == s) + return i; + } + return -1; + } + + function drawOverlay(plot, octx) + { + //alert(options.series.pie.radius); + var options = plot.getOptions(); + //alert(options.series.pie.radius); + + var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; + + octx.save(); + octx.translate(centerLeft, centerTop); + octx.scale(1, options.series.pie.tilt); + + for (i = 0; i < highlights.length; ++i) + drawHighlight(highlights[i].series); + + drawDonutHole(octx); + + octx.restore(); + + function drawHighlight(series) + { + if (series.angle < 0) return; + + //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString(); + octx.fillStyle = "rgba(255, 255, 255, "+options.series.pie.highlight.opacity+")"; // this is temporary until we have access to parseColor + + octx.beginPath(); + if (series.angle!=Math.PI*2) + octx.moveTo(0,0); // Center of the pie + octx.arc(0,0,radius,series.startAngle,series.startAngle+series.angle,false); + octx.closePath(); + octx.fill(); + } + + } + + } // end init (plugin body) + + // define pie specific options and their default values + var options = { + series: { + pie: { + show: false, + radius: 'auto', // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value) + innerRadius:0, /* for donut */ + startAngle: 3/2, + tilt: 1, + offset: { + top: 0, + left: 'auto' + }, + stroke: { + color: '#FFF', + width: 1 + }, + label: { + show: 'auto', + formatter: function(label, slice){ + return '
'+label+'
'+Math.round(slice.percent)+'%
'; + }, // formatter function + radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value) + background: { + color: null, + opacity: 0 + }, + threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow) + }, + combine: { + threshold: -1, // percentage at which to combine little slices into one larger slice + color: null, // color to give the new slice (auto-generated if null) + label: 'Other' // label to give the new slice + }, + highlight: { + //color: '#FFF', // will add this functionality once parseColor is available + opacity: 0.5 + } + } + } + }; + + $.plot.plugins.push({ + init: init, + options: options, + name: "pie", + version: "1.0" + }); +})(jQuery); + + +// for the progress bar +myBar.loaded('jquery.flot.pie.js'); diff --git a/xCAT-UI/js/loading.js b/xCAT-UI/js/loading.js index e3d44de25..41d1c1d1a 100644 --- a/xCAT-UI/js/loading.js +++ b/xCAT-UI/js/loading.js @@ -105,6 +105,7 @@ var xStart = function(){ myBar.addScript("superfish.js"); myBar.addScript("jquery.tablesorter.js"); myBar.addScript("jquery.flot.js"); + myBar.addScript("jquery.flot.pie.js"); myBar.addScript("excanvas.js"); myBar.addScript("noderangetree.js"); myBar.addScript("monitor.js");