added a simple spike of drawing of graphs of queue depths; its pretty basic so far - a bit more work and it could look quite nice :)

git-svn-id: https://svn.apache.org/repos/asf/incubator/activemq/trunk@397975 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
James Strachan 2006-04-28 18:14:51 +00:00
parent f1a0614066
commit d67246412d
15 changed files with 8144 additions and 3 deletions

View File

@ -0,0 +1,28 @@
Copyright (c) 2006, Alastair Tse
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the Alastair Tse nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,69 @@
MochiKit is dual-licensed software. It is available under the terms of the
MIT License, or the Academic Free License version 2.1. The full text of
each license is included below.
MIT License
===========
Copyright (c) 2005 Bob Ippolito. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Academic Free License v. 2.1
============================
Copyright (c) 2005 Bob Ippolito. All rights reserved.
This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work:
Licensed under the Academic Free License version 2.1
1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following:
a) to reproduce the Original Work in copies;
b) to prepare derivative works ("Derivative Works") based upon the Original Work;
c) to distribute copies of the Original Work and Derivative Works to the public;
d) to perform the Original Work publicly; and
e) to display the Original Work publicly.
2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works.
3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work.
4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license.
5) This section intentionally omitted.
6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work.
7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer.
8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions.
10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware.
11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License.
12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License.
13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable.
14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You.
This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner.

View File

@ -12,9 +12,11 @@
@import url(<c:url value="/styles/sorttable.css"/>);
@import url(<c:url value="/styles/deliciouslyblue.css"/>);
</style>
<script type='text/javascript' src='<c:url value="/js/common.js"/>'/>
<script type='text/javascript' src='<c:url value="/js/css.js"/>'/>
<script type='text/javascript' src='<c:url value="/js/standardista-table-sorting.js"/>'/>
<c:if test="${!disableJavaScript}">
<script type='text/javascript' src='<c:url value="/js/common.js"/>'/>
<script type='text/javascript' src='<c:url value="/js/css.js"/>'/>
<script type='text/javascript' src='<c:url value="/js/standardista-table-sorting.js"/>'/>
</c:if>
<decorator:head />
</head>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
dojo.hostenv.conditionalLoadModule({"common": ["MochiKit.MochiKit"]});
dojo.hostenv.moduleLoaded("MochiKit.*");

View File

@ -0,0 +1,332 @@
/*
PlotKit
=======
PlotKit is a collection of Javascript classes that allows
you to quickly visualise data using different types of charts.
For license/info/documentation: http://www.liquidx.net/plotkit/
Copyright
---------
Copyright 2005,2006 (c) Alastair Tse <alastair^liquidx.net>
For use under the BSD license. <http://www.liquidx.net/plotkit>
*/
// --------------------------------------------------------------------
// Check required components
// --------------------------------------------------------------------
try {
if (typeof(MochiKit.Base) == 'undefined' ||
typeof(MochiKit.DOM) == 'undefined' ||
typeof(MochiKit.Color) == 'undefined' ||
typeof(MochiKit.Format) == 'undefined')
{
throw "";
}
}
catch (e) {
throw "PlotKit depends on MochiKit.{Base,Color,DOM,Format}"
}
// -------------------------------------------------------------------
// Inject Common Shortcuts we use into MochiKit.Color.Color
// -------------------------------------------------------------------
MochiKit.Base.update(MochiKit.Color.Color.prototype, {
asFillColor: function() {
return this.lighterColorWithLevel(0.3);
},
asStrokeColor: function() {
return this.darkerColorWithLevel(0.1);
},
asPointColor: function() {
return this.lighterColorWithLevel(0.1);
}
});
// -------------------------------------------------------------------
// Define our own PlotKit namespace
// -------------------------------------------------------------------
if (typeof(PlotKit) == 'undefined') {
PlotKit = {};
}
PlotKit.NAME = "PlotKit";
PlotKit.VERSION = "0.8";
PlotKit.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.toString = function() {
return this.__repr__();
}
// -------------------------------------------------------------------
// Encapsulate all our utility function into it's own namespace.
// -------------------------------------------------------------------
if (typeof(PlotKit.Base) == 'undefined') {
PlotKit.Base = {};
}
PlotKit.Base.NAME = 'PlotKit.Base';
PlotKit.Base.VERSION = PlotKit.VERSION;
PlotKit.Base.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.Base.toString = function() {
return this.__repr__();
}
MochiKit.Base.update(PlotKit.Base, {
roundInterval: function(range, intervals, precision) {
// We want to make the interval look regular,
var trunc = MochiKit.Format.roundToFixed;
var sep = range/intervals;
return parseFloat(trunc(sep, precision));
},
collapse: function(lst) {
var m = MochiKit.Base;
var biggerList = new Array();
for (var i = 0; i < lst.length; i++) {
biggerList = m.concat(biggerList, lst[i]);
}
return biggerList;
},
uniq: function(sortedList) {
// get unique elements in list, exactly the same as unix shell's uniq.
var m = MochiKit.Base;
if (!m.isArrayLike(sortedList) || (sortedList.length < 1))
return new Array();
var uniq = new Array();
var lastElem = sortedList[0];
uniq.push(sortedList[0]);
for (var i = 1; i < sortedList.length; i++) {
if (m.compare(sortedList[i], lastElem) != 0) {
lastElem = sortedList[i];
uniq.push(sortedList[i]);
}
}
return uniq;
},
colorScheme: function() {
var mb = MochiKit.Base;
var mc = MochiKit.Color
var scheme = ["red", "orange", "yellow", "green", "cyan", "blue", "purple", "magenta"];
var makeColor = function(name) {
return mc.Color[name + "Color"]()
};
return mb.map(makeColor, scheme);
},
baseDarkPrimaryColors: function () {
var hexColor = MochiKit.Color.Color.fromHexString;
return [hexColor("#ad3f40"),
hexColor("#ddac2c"),
hexColor("#dfdd0c"),
hexColor("#5276c4"),
hexColor("#739c5a")];
},
basePrimaryColors: function () {
var hexColor = MochiKit.Color.Color.fromHexString;
return [hexColor("#d24c4d"),
hexColor("#f2b32f"),
hexColor("#ece90e"),
hexColor("#5d83da"),
hexColor("#78a15d")];
},
baseBlueColors: function () {
var hexColor = MochiKit.Color.Color.fromHexString;
return [hexColor("#4b6b94"), hexColor("#5d81b4"), hexColor("#acbad2")];
},
palette: function(baseColor, fromLevel, toLevel, increment) {
var isNil = MochiKit.Base.isUndefinedOrNull;
var fractions = new Array();
if (isNil(increment))
increment = 0.1;
if (isNil(toLevel))
toLevel = 0.4;
if (isNil(fromLevel))
fromLevel = -0.2;
var level = fromLevel;
while (level <= toLevel) {
fractions.push(level);
level += increment;
}
var makeColor = function(color, fraction) {
return color.lighterColorWithLevel(fraction);
};
return MochiKit.Base.map(partial(makeColor, baseColor), fractions);
},
// The follow functions are from quirksmode.org
// http://www.quirksmode.org/js/findpos.html
findPosX: function(obj) {
var curleft = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
curleft += obj.offsetLeft
obj = obj.offsetParent;
}
}
else if (obj.x)
curleft += obj.x;
return curleft;
},
findPosY: function(obj) {
var curtop = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
curtop += obj.offsetTop
obj = obj.offsetParent;
}
}
else if (obj.y)
curtop += obj.y;
return curtop;
}
});
PlotKit.Base.baseColors = function () {
var hexColor = MochiKit.Color.Color.fromHexString;
return [hexColor("#476fb2"),
hexColor("#be2c2b"),
hexColor("#85b730"),
hexColor("#734a99"),
hexColor("#26a1c5"),
hexColor("#fb8707"),
hexColor("#000000")];
};
PlotKit.Base.officeBaseStyle = {
"axisLineWidth": 2.0,
"axisLabelColor": Color.grayColor(),
"axisLineColor": Color.whiteColor(),
"padding": {top: 5, bottom: 10, left: 30, right: 30}
};
MochiKit.Base.update(PlotKit.Base,{
officeBlue: function() {
var r = {
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[0]),
"backgroundColor": PlotKit.Base.baseColors()[0].lighterColorWithLevel(0.45)
};
MochiKit.Base.update(r, PlotKit.Base.officeBaseStyle);
return r;
},
officeRed: function() {
var r = {
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[1]),
"backgroundColor": PlotKit.Base.baseColors()[1].lighterColorWithLevel(0.5)
};
MochiKit.Base.update(r, PlotKit.Base.officeBaseStyle);
return r;
},
officeGreen: function() {
var r = {
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[2]),
"backgroundColor": PlotKit.Base.baseColors()[2].lighterColorWithLevel(0.5)
};
MochiKit.Base.update(r, PlotKit.Base.officeBaseStyle);
return r;
},
officePurple: function() {
var r = {
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[3]),
"backgroundColor": PlotKit.Base.baseColors()[3].lighterColorWithLevel(0.5)
};
MochiKit.Base.update(r, PlotKit.Base.officeBaseStyle);
return r;
},
officeCyan: function() {
var r = {
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[4]),
"backgroundColor": PlotKit.Base.baseColors()[4].lighterColorWithLevel(0.5)
};
MochiKit.Base.update(r, PlotKit.Base.officeBaseStyle);
return r;
},
officeOrange: function() {
var r = {
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[5]),
"backgroundColor": PlotKit.Base.baseColors()[5].lighterColorWithLevel(0.4)
};
MochiKit.Base.update(r, PlotKit.Base.officeBaseStyle);
return r;
},
officeBlack: function() {
var r = {
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[6], 0.0, 0.6),
"backgroundColor": PlotKit.Base.baseColors()[6].lighterColorWithLevel(0.9)
};
MochiKit.Base.update(r, PlotKit.Base.officeBaseStyle);
return r;
}
});
PlotKit.Base.EXPORT = [
"baseColors",
"collapse",
"colorScheme",
"findPosX",
"findPosY",
"officeBaseStyle",
"officeBlue",
"officeRed",
"officeGreen",
"officePurple",
"officeCyan",
"officeOrange",
"officeBlack",
"roundInterval",
"uniq",
];
PlotKit.Base.EXPORT_OK = [];
PlotKit.Base.__new__ = function() {
var m = MochiKit.Base;
m.nameFunctions(this);
this.EXPORT_TAGS = {
":common": this.EXPORT,
":all": m.concat(this.EXPORT, this.EXPORT_OK)
};
};
PlotKit.Base.__new__();
MochiKit.Base._exportSymbols(this, PlotKit.Base);

View File

@ -0,0 +1,707 @@
/*
PlotKit Canvas
--------------
Provides HTML Canvas Renderer. This is supported under:
- Safari 2.0
- Mozilla Firefox 1.5
- Opera 9.0 preview 2
- IE 6 (via VML Emulation)
It uses DIVs for labels.
Notes About IE Support
----------------------
This class relies on iecanvas.htc for Canvas Emulation under IE[1].
iecanvas.htc is included in the distribution of PlotKit for convenience. In order to enable IE support, you must set the following option when initialising the renderer:
var renderOptions = {
"IECanvasHTC": "contrib/iecanvas.htc"
};
var engine = new CanvasRenderer(canvasElement, layout, renderOptions);
Where "contrib/iecanvas.htc" is the path to the htc behavior relative
to where your HTML is.
This is only needed for IE support.
Copyright
---------
Copyright 2005,2006 (c) Alastair Tse <alastair^liquidx.net>
For use under the BSD license. <http://www.liquidx.net/plotkit>
*/
// --------------------------------------------------------------------
// Check required components
// --------------------------------------------------------------------
try {
if (typeof(PlotKit.Layout) == 'undefined')
{
throw "";
}
}
catch (e) {
throw "PlotKit.Layout depends on MochiKit.{Base,Color,DOM,Format} and PlotKit.Base and PlotKit.Layout"
}
// ------------------------------------------------------------------------
// Defines the renderer class
// ------------------------------------------------------------------------
if (typeof(PlotKit.CanvasRenderer) == 'undefined') {
PlotKit.CanvasRenderer = {};
}
PlotKit.CanvasRenderer.NAME = "PlotKit.CanvasRenderer";
PlotKit.CanvasRenderer.VERSION = PlotKit.VERSION;
PlotKit.CanvasRenderer.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.CanvasRenderer.toString = function() {
return this.__repr__();
}
PlotKit.CanvasRenderer = function(element, layout, options) {
if (arguments.length > 0)
this.__init__(element, layout, options);
};
PlotKit.CanvasRenderer.prototype.__init__ = function(element, layout, options) {
var isNil = MochiKit.Base.isUndefinedOrNull;
var Color = MochiKit.Color.Color;
// default options
this.options = {
"drawBackground": true,
"backgroundColor": Color.whiteColor(),
"padding": {left: 30, right: 30, top: 5, bottom: 10},
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[0]),
"strokeColor": Color.whiteColor(),
"strokeColorTransform": "asStrokeColor",
"strokeWidth": 0.5,
"shouldFill": true,
"shouldStroke": true,
"drawXAxis": true,
"drawYAxis": true,
"axisLineColor": Color.blackColor(),
"axisLineWidth": 0.5,
"axisTickSize": 3,
"axisLabelColor": Color.blackColor(),
"axisLabelFont": "Arial",
"axisLabelFontSize": 9,
"axisLabelWidth": 50,
"pieRadius": 0.4,
"enableEvents": true,
"IECanvasHTC": "PlotKit/iecanvas.htc"
};
MochiKit.Base.update(this.options, options ? options : {});
// we need to refetch the element because of this horrible Canvas on IE
// crap
this.element_id = element.id ? element.id : element;
// Stuff relating to Canvas on IE support
var self = PlotKit.CanvasRenderer;
this.isIE = self.IECanvasEmulationIfNeeded(this.options.IECanvasHTC);
this.IEDelay = 0.5;
this.maxTries = 5;
this.renderDelay = null;
this.clearDelay = null;
this.layout = layout;
this.style = layout.style;
this.element = MochiKit.DOM.getElement(this.element_id);
//this.element = element;
this.container = this.element.parentNode;
this.height = this.element.height;
this.width = this.element.width;
// --- check whether everything is ok before we return
if (isNil(this.element))
throw "CanvasRenderer() - passed canvas is not found";
if (!this.isIE && !(PlotKit.CanvasRenderer.isSupported(this.element)))
throw "CanvasRenderer() - Canvas is not supported.";
if (isNil(this.container) || (this.container.nodeName.toLowerCase() != "div"))
throw "CanvasRenderer() - <canvas> needs to be enclosed in <div>";
// internal state
this.xlabels = new Array();
this.ylabels = new Array();
this.isFirstRender = true;
this.area = {
x: this.options.padding.left,
y: this.options.padding.top,
w: this.width - this.options.padding.left - this.options.padding.right,
h: this.height - this.options.padding.top - this.options.padding.bottom
};
MochiKit.DOM.updateNodeAttributes(this.container,
{"style":{ "position": "relative", "width": this.width + "px"}});
// load event system if we have Signals
try {
this.event_isinside = null;
if (MochiKit.Signal && this.options.enableEvents) {
this._initialiseEvents();
}
}
catch (e) {
// still experimental
}
};
PlotKit.CanvasRenderer.IECanvasEmulationIfNeeded = function(htc) {
var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
if ((!ie) || (ie[1] < 6) || (opera))
return false;
if (isUndefinedOrNull(MochiKit.DOM.getElement('VMLRender'))) {
// before we add VMLRender, we need to recreate all canvas tags
// programmatically otherwise IE will not recognise it
var nodes = document.getElementsByTagName('canvas');
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.getContext) { return; } // Other implementation, abort
var newNode = MochiKit.DOM.CANVAS(
{id: node.id,
width: "" + parseInt(node.width),
height: "" + parseInt(node.height)}, "");
newNode.style.width = parseInt(node.width) + "px";
newNode.style.height = parseInt(node.height) + "px";
node.id = node.id + "_old";
MochiKit.DOM.swapDOM(node, newNode);
}
document.namespaces.add("v");
var vmlopts = {'id':'VMLRender',
'codebase':'vgx.dll',
'classid':'CLSID:10072CEC-8CC1-11D1-986E-00A0C955B42E'};
var vml = MochiKit.DOM.createDOM('object', vmlopts);
document.body.appendChild(vml);
var vmlStyle = document.createStyleSheet();
vmlStyle.addRule("canvas", "behavior: url('" + htc + "');");
vmlStyle.addRule("v\\:*", "behavior: url(#VMLRender);");
}
return true;
};
PlotKit.CanvasRenderer.prototype.render = function() {
if (this.isIE) {
// VML takes a while to start up, so we just poll every this.IEDelay
try {
if (this.renderDelay) {
this.renderDelay.cancel();
this.renderDelay = null;
}
var context = this.element.getContext("2d");
}
catch (e) {
this.isFirstRender = false;
if (this.maxTries-- > 0) {
this.renderDelay = MochiKit.Async.wait(this.IEDelay);
this.renderDelay.addCallback(bind(this.render, this));
}
return;
}
}
if (this.options.drawBackground)
this._renderBackground();
if (this.style == "bar") {
this._renderBarChart();
this._renderBarAxis();
}
else if (this.style == "pie") {
this._renderPieChart();
this._renderPieAxis();
}
else if (this.style == "line") {
this._renderLineChart();
this._renderLineAxis();
}
};
PlotKit.CanvasRenderer.prototype._renderBarChartWrap = function(data, plotFunc) {
var context = this.element.getContext("2d");
var colorCount = this.options.colorScheme.length;
var colorScheme = this.options.colorScheme;
var setNames = MochiKit.Base.keys(this.layout.datasets);
var setCount = setNames.length;
for (var i = 0; i < setCount; i++) {
var setName = setNames[i];
var color = colorScheme[i%colorCount];
context.save();
context.fillStyle = color.toRGBString();
if (this.options.strokeColor)
context.strokeStyle = this.options.strokeColor.toRGBString();
else if (this.options.strokeColorTransform)
context.strokeStyle = color[this.options.strokeColorTransform]().toRGBString();
context.lineWidth = this.options.strokeWidth;
var forEachFunc = function(obj) {
if (obj.name == setName)
plotFunc(context, obj);
};
MochiKit.Iter.forEach(data, bind(forEachFunc, this));
context.restore();
}
};
PlotKit.CanvasRenderer.prototype._renderBarChart = function() {
var bind = MochiKit.Base.bind;
var drawRect = function(context, bar) {
var x = this.area.w * bar.x + this.area.x;
var y = this.area.h * bar.y + this.area.y;
var w = this.area.w * bar.w;
var h = this.area.h * bar.h;
if ((w < 1) || (h < 1))
return;
if (this.options.shouldFill)
context.fillRect(x, y, w, h);
if (this.options.shouldStroke)
context.strokeRect(x, y, w, h);
};
this._renderBarChartWrap(this.layout.bars, bind(drawRect, this));
};
PlotKit.CanvasRenderer.prototype._renderLineChart = function() {
var context = this.element.getContext("2d");
var colorCount = this.options.colorScheme.length;
var colorScheme = this.options.colorScheme;
var setNames = MochiKit.Base.keys(this.layout.datasets);
var setCount = setNames.length;
var bind = MochiKit.Base.bind;
var partial = MochiKit.Base.partial;
for (var i = 0; i < setCount; i++) {
var setName = setNames[i];
var color = colorScheme[i%colorCount];
var strokeX = this.options.strokeColorTransform;
// setup graphics context
context.save();
context.fillStyle = color.toRGBString();
if (this.options.strokeColor)
context.strokeStyle = this.options.strokeColor.toRGBString();
else if (this.options.strokeColorTransform)
context.strokeStyle = color[strokeX]().toRGBString();
context.lineWidth = this.options.strokeWidth;
// create paths
var makePath = function() {
context.beginPath();
context.moveTo(this.area.x, this.area.y + this.area.h);
var addPoint = function(context, point) {
if (point.name == setName)
context.lineTo(this.area.w * point.x + this.area.x,
this.area.h * point.y + this.area.y);
};
MochiKit.Iter.forEach(this.layout.points, partial(addPoint, context), this);
context.lineTo(this.area.w + this.area.x,
this.area.h + this.area.y);
context.lineTo(this.area.x, this.area.y + this.area.h);
context.closePath();
};
if (this.options.shouldFill) {
bind(makePath, this)();
context.fill();
}
if (this.options.shouldStroke) {
bind(makePath, this)();
context.stroke();
}
context.restore();
}
};
PlotKit.CanvasRenderer.prototype._renderPieChart = function() {
var context = this.element.getContext("2d");
var colorCount = this.options.colorScheme.length;
var slices = this.layout.slices;
var centerx = this.area.x + this.area.w * 0.5;
var centery = this.area.y + this.area.h * 0.5;
var radius = Math.min(this.area.w * this.options.pieRadius,
this.area.h * this.options.pieRadius);
if (this.isIE) {
centerx = parseInt(centerx);
centery = parseInt(centery);
radius = parseInt(radius);
}
// NOTE NOTE!! Canvas Tag draws the circle clockwise from the y = 0, x = 1
// so we have to subtract 90 degrees to make it start at y = 1, x = 0
for (var i = 0; i < slices.length; i++) {
var color = this.options.colorScheme[i%colorCount];
context.save();
context.fillStyle = color.toRGBString();
var makePath = function() {
context.beginPath();
context.moveTo(centerx, centery);
context.arc(centerx, centery, radius,
slices[i].startAngle - Math.PI/2,
slices[i].endAngle - Math.PI/2,
false);
context.lineTo(centerx, centery);
context.closePath();
};
if (Math.abs(slices[i].startAngle - slices[i].endAngle) > 0.001) {
if (this.options.shouldFill) {
makePath();
context.fill();
}
if (this.options.shouldStroke) {
makePath();
context.lineWidth = this.options.strokeWidth;
if (this.options.strokeColor)
context.strokeStyle = this.options.strokeColor.toRGBString();
else if (this.options.strokeColorTransform)
context.strokeStyle = color[this.options.strokeColorTransform]().toRGBString();
context.stroke();
}
}
context.restore();
}
};
PlotKit.CanvasRenderer.prototype._renderBarAxis = function() {
this._renderAxis();
}
PlotKit.CanvasRenderer.prototype._renderLineAxis = function() {
this._renderAxis();
};
PlotKit.CanvasRenderer.prototype._renderAxis = function() {
if (!this.options.drawXAxis && !this.options.drawYAxis)
return;
var context = this.element.getContext("2d");
var labelStyle = {"style":
{"position": "absolute",
"fontSize": this.options.axisLabelFontSize + "px",
"zIndex": 10,
"color": this.options.axisLabelColor.toRGBString(),
"width": this.options.axisLabelWidth + "px",
"overflow": "hidden"
}
};
// axis lines
context.save();
context.strokeStyle = this.options.axisLineColor.toRGBString();
context.lineWidth = this.options.axisLineWidth;
if (this.options.drawYAxis) {
if (this.layout.yticks) {
var drawTick = function(tick) {
var x = this.area.x;
var y = this.area.y + tick[0] * this.area.h;
context.beginPath();
context.moveTo(x, y);
context.lineTo(x - this.options.axisTickSize, y);
context.closePath();
context.stroke();
var label = DIV(labelStyle, tick[1]);
label.style.top = (y - this.options.axisLabelFontSize) + "px";
label.style.left = (x - this.options.padding.left - this.options.axisTickSize) + "px";
label.style.textAlign = "right";
label.style.width = (this.options.padding.left - this.options.axisTickSize * 2) + "px";
MochiKit.DOM.appendChildNodes(this.container, label);
this.ylabels.push(label);
};
MochiKit.Iter.forEach(this.layout.yticks, bind(drawTick, this));
}
context.beginPath();
context.moveTo(this.area.x, this.area.y);
context.lineTo(this.area.x, this.area.y + this.area.h);
context.closePath();
context.stroke();
}
if (this.options.drawXAxis) {
if (this.layout.xticks) {
var drawTick = function(tick) {
var x = this.area.x + tick[0] * this.area.w;
var y = this.area.y + this.area.h;
context.beginPath();
context.moveTo(x, y);
context.lineTo(x, y + this.options.axisTickSize);
context.closePath();
context.stroke();
var label = DIV(labelStyle, tick[1]);
label.style.top = (y + this.options.axisTickSize) + "px";
label.style.left = (x - this.options.axisLabelWidth/2) + "px";
label.style.textAlign = "center";
label.style.width = this.options.axisLabelWidth + "px";
MochiKit.DOM.appendChildNodes(this.container, label);
this.xlabels.push(label);
};
MochiKit.Iter.forEach(this.layout.xticks, bind(drawTick, this));
}
context.beginPath();
context.moveTo(this.area.x, this.area.y + this.area.h);
context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
context.closePath();
context.stroke();
}
context.restore();
};
PlotKit.CanvasRenderer.prototype._renderPieAxis = function() {
if (!this.options.drawXAxis)
return;
if (this.layout.xticks) {
// make a lookup dict for x->slice values
var lookup = new Array();
for (var i = 0; i < this.layout.slices.length; i++) {
lookup[this.layout.slices[i].xval] = this.layout.slices[i];
}
var centerx = this.area.x + this.area.w * 0.5;
var centery = this.area.y + this.area.h * 0.5;
var radius = Math.min(this.area.w * this.options.pieRadius,
this.area.h * this.options.pieRadius);
var labelWidth = this.options.axisLabelWidth;
for (var i = 0; i < this.layout.xticks.length; i++) {
var slice = lookup[this.layout.xticks[i][0]];
if (MochiKit.Base.isUndefinedOrNull(slice))
continue;
var angle = (slice.startAngle + slice.endAngle)/2;
// normalize the angle
var normalisedAngle = angle;
if (normalisedAngle > Math.PI * 2)
normalisedAngle = normalisedAngle - Math.PI * 2;
else if (normalisedAngle < 0)
normalisedAngle = normalisedAngle + Math.PI * 2;
var labelx = centerx + Math.sin(normalisedAngle) * (radius + 10);
var labely = centery - Math.cos(normalisedAngle) * (radius + 10);
var attrib = {"position": "absolute",
"zIndex": 11,
"width": labelWidth + "px",
"fontSize": this.options.axisLabelFontSize + "px",
"overflow": "hidden",
"color": this.options.axisLabelColor.toHexString()
};
if (normalisedAngle <= Math.PI * 0.5) {
// text on top and align left
attrib["textAlign"] = "left";
attrib["verticalAlign"] = "top";
attrib["left"] = labelx + "px";
attrib["top"] = (labely - this.options.axisLabelFontSize) + "px";
}
else if ((normalisedAngle > Math.PI * 0.5) && (normalisedAngle <= Math.PI)) {
// text on bottom and align left
attrib["textAlign"] = "left";
attrib["verticalAlign"] = "bottom";
attrib["left"] = labelx + "px";
attrib["top"] = labely + "px";
}
else if ((normalisedAngle > Math.PI) && (normalisedAngle <= Math.PI*1.5)) {
// text on bottom and align right
attrib["textAlign"] = "right";
attrib["verticalAlign"] = "bottom";
attrib["left"] = (labelx - labelWidth) + "px";
attrib["top"] = labely + "px";
}
else {
// text on top and align right
attrib["textAlign"] = "right";
attrib["verticalAlign"] = "bottom";
attrib["left"] = (labelx - labelWidth) + "px";
attrib["top"] = (labely - this.options.axisLabelFontSize) + "px";
}
var label = DIV({'style': attrib}, this.layout.xticks[i][1]);
this.xlabels.push(label);
MochiKit.DOM.appendChildNodes(this.container, label);
}
}
};
PlotKit.CanvasRenderer.prototype._renderBackground = function() {
var context = this.element.getContext("2d");
context.save();
context.fillStyle = this.options.backgroundColor.toRGBString();
context.fillRect(0, 0, this.width, this.height);
context.restore();
};
PlotKit.CanvasRenderer.prototype.clear = function() {
if (this.isIE) {
// VML takes a while to start up, so we just poll every this.IEDelay
try {
if (this.clearDelay) {
this.clearDelay.cancel();
this.clearDelay = null;
}
var context = this.element.getContext("2d");
}
catch (e) {
this.isFirstRender = false;
this.clearDelay = MochiKit.Async.wait(this.IEDelay);
this.clearDelay.addCallback(bind(this.clear, this));
return;
}
}
var context = this.element.getContext("2d");
context.clearRect(0, 0, this.width, this.height);
for (var i = 0; i < this.xlabels.length; i++) {
MochiKit.DOM.removeElement(this.xlabels[i]);
}
for (var i = 0; i < this.ylabels.length; i++) {
MochiKit.DOM.removeElement(this.ylabels[i]);
}
this.xlabels = new Array();
this.ylabels = new Array();
};
PlotKit.CanvasRenderer.prototype._initialiseEvents = function() {
var connect = MochiKit.Signal.connect;
var bind = MochiKit.Base.bind;
MochiKit.Signal.registerSignals(this, ['onmouseover', 'onclick', 'onmouseout', 'onmousemove']);
//connect(this.element, 'onmouseover', bind(this.onmouseover, this));
//connect(this.element, 'onmouseout', bind(this.onmouseout, this));
//connect(this.element, 'onmousemove', bind(this.onmousemove, this));
connect(this.element, 'onclick', bind(this.onclick, this));
};
PlotKit.CanvasRenderer.prototype._resolveObject = function(e) {
// does not work in firefox
//var x = (e.event().offsetX - this.area.x) / this.area.w;
//var y = (e.event().offsetY - this.area.y) / this.area.h;
var x = (e.mouse().page.x - PlotKit.Base.findPosX(this.element) - this.area.x) / this.area.w;
var y = (e.mouse().page.y - PlotKit.Base.findPosY(this.element) - this.area.y) / this.area.h;
//log(x, y);
var isHit = this.layout.hitTest(x, y);
if (isHit)
return isHit;
return null;
};
PlotKit.CanvasRenderer.prototype._createEventObject = function(layoutObj, e) {
if (layoutObj == null) {
return null;
}
e.chart = layoutObj
return e;
};
PlotKit.CanvasRenderer.prototype.onclick = function(e) {
var layoutObject = this._resolveObject(e);
var eventObject = this._createEventObject(layoutObject, e);
if (eventObject != null)
MochiKit.Signal.signal(this, "onclick", eventObject);
};
PlotKit.CanvasRenderer.prototype.onmouseover = function(e) {
var layoutObject = this._resolveObject(e);
var eventObject = this._createEventObject(layoutObject, e);
if (eventObject != null)
signal(this, "onmouseover", eventObject);
};
PlotKit.CanvasRenderer.prototype.onmouseout = function(e) {
var layoutObject = this._resolveObject(e);
var eventObject = this._createEventObject(layoutObject, e);
if (eventObject == null)
signal(this, "onmouseout", e);
else
signal(this, "onmouseout", eventObject);
};
PlotKit.CanvasRenderer.prototype.onmousemove = function(e) {
var layoutObject = this._resolveObject(e);
var eventObject = this._createEventObject(layoutObject, e);
if ((layoutObject == null) && (this.event_isinside == null)) {
// TODO: should we emit an event anyway?
return;
}
if ((layoutObject != null) && (this.event_isinside == null))
signal(this, "onmouseover", eventObject);
if ((layoutObject == null) && (this.event_isinside != null))
signal(this, "onmouseout", eventObject);
if ((layoutObject != null) && (this.event_isinside != null))
signal(this, "onmousemove", eventObject);
this.event_isinside = layoutObject;
//log("move", x, y);
};
PlotKit.CanvasRenderer.isSupported = function(canvasName) {
var canvas = null;
try {
if (MochiKit.Base.isUndefinedOrNull(canvasName))
canvas = MochiKit.DOM.CANVAS({});
else
canvas = MochiKit.DOM.getElement(canvasName);
var context = canvas.getContext("2d");
}
catch (e) {
var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
if ((!ie) || (ie[1] < 6) || (opera))
return false;
return true;
}
return true;
};

View File

@ -0,0 +1,588 @@
/*
PlotKit Layout
--------------
Handles laying out data on to a virtual canvas square canvas between 0.0
and 1.0. If you want to add new chart/plot types such as point plots,
you need to add them here.
Copyright
---------
Copyright 2005,2006 (c) Alastair Tse <alastair^liquidx.net>
For use under the BSD license. <http://www.liquidx.net/plotkit>
*/
try {
if (typeof(PlotKit.Base) == 'undefined')
{
throw ""
}
}
catch (e) {
throw "PlotKit.Layout depends on MochiKit.{Base,Color,DOM,Format} and PlotKit.Base"
}
// --------------------------------------------------------------------
// Start of Layout definition
// --------------------------------------------------------------------
if (typeof(PlotKit.Layout) == 'undefined') {
PlotKit.Layout = {};
}
PlotKit.Layout.NAME = "PlotKit.Layout";
PlotKit.Layout.VERSION = PlotKit.VERSION;
PlotKit.Layout.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.Layout.toString = function() {
return this.__repr__();
}
PlotKit.Layout.valid_styles = ["bar", "line", "pie", "point"];
// --------------------------------------------------------------------
// Start of Layout definition
// --------------------------------------------------------------------
PlotKit.Layout = function(style, options) {
this.options = {
"barWidthFillFraction": 0.75,
"xOriginIsZero": true,
"yOriginIsZero": true,
"xAxis": null, // [xmin, xmax]
"yAxis": null, // [ymin, ymax]
"xTicks": null, // [{label: "somelabel", v: value}, ..] (label opt.)
"yTicks": null, // [{label: "somelabel", v: value}, ..] (label opt.)
"xNumberOfTicks": 10,
"yNumberOfTicks": 5,
"xTickPrecision": 1,
"yTickPrecision": 3,
"pieRadius": 0.4
};
// valid external options : TODO: input verification
this.style = style;
MochiKit.Base.update(this.options, options ? options : {});
// externally visible states
// overriden if xAxis and yAxis are set in options
if (!MochiKit.Base.isUndefinedOrNull(this.options.xAxis)) {
this.minxval = this.options.xAxis[0];
this.maxxval = this.options.xAxis[1];
this.xscale = this.maxxval - this.minxval;
}
else {
this.minxval = 0;
this.maxxval = null;
this.xscale = null; // val -> pos factor (eg, xval * xscale = xpos)
}
if (!MochiKit.Base.isUndefinedOrNull(this.options.yAxis)) {
this.minyval = this.options.yAxis[0];
this.maxyval = this.options.yAxis[1];
this.yscale = this.maxyval - this.maxymin;
}
else {
this.minyval = 0;
this.maxyval = null;
this.yscale = null;
}
this.bars = new Array(); // array of bars to plot for bar charts
this.points = new Array(); // array of points to plot for line plots
this.slices = new Array(); // array of slices to draw for pie charts
this.xticks = new Array();
this.yticks = new Array();
// internal states
this.datasets = new Array();
this.minxdelta = 0;
this.xrange = 1;
this.yrange = 1;
this.hitTestCache = {x2maxy: null};
};
// --------------------------------------------------------------------
// Dataset Manipulation
// --------------------------------------------------------------------
PlotKit.Layout.prototype.addDataset = function(setname, set_xy) {
this.datasets[setname] = set_xy;
};
PlotKit.Layout.prototype.removeDataset = function(setname, set_xy) {
this.datasets[setname] = null;
};
PlotKit.Layout.prototype.addDatasetFromTable = function(name, tableElement, xcol, ycol) {
var isNil = MochiKit.Base.isUndefinedOrNull;
var scrapeText = MochiKit.DOM.scrapeText;
var strip = MochiKit.Format.strip;
if (isNil(xcol))
xcol = 0;
if (isNil(ycol))
ycol = 1;
var rows = tableElement.tBodies[0].rows;
var data = new Array();
if (!isNil(rows)) {
for (var i = 0; i < rows.length; i++) {
data.push([parseFloat(strip(scrapeText(rows[i].cells[xcol]))),
parseFloat(strip(scrapeText(rows[i].cells[ycol])))]);
}
this.addDataset(name, data);
return true;
}
return false;
};
// --------------------------------------------------------------------
// Evaluates the layout for the current data and style.
// --------------------------------------------------------------------
PlotKit.Layout.prototype.evaluate = function() {
this._evaluateLimits();
this._evaluateScales();
if (this.style == "bar") {
this._evaluateBarCharts();
this._evaluateBarTicks();
}
else if (this.style == "line") {
this._evaluateLineCharts();
this._evaluateLineTicks();
}
else if (this.style == "pie") {
this._evaluatePieCharts();
this._evaluatePieTicks();
}
};
// Given the fractional x, y positions, report the corresponding
// x, y values.
PlotKit.Layout.prototype.hitTest = function(x, y) {
// TODO: make this more efficient with better datastructures
// for this.bars, this.points and this.slices
var f = MochiKit.Format.twoDigitFloat;
if ((this.style == "bar") && this.bars && (this.bars.length > 0)) {
for (var i = 0; i < this.bars.length; i++) {
var bar = this.bars[i];
if ((x >= bar.x) && (x <= bar.x + bar.w)
&& (y >= bar.y) && (y - bar.y <= bar.h))
return bar;
}
}
else if (this.style == "line") {
if (this.hitTestCache.x2maxy == null) {
this._regenerateHitTestCache();
}
// 1. find the xvalues that equal or closest to the give x
var xval = x / this.xscale;
var xvalues = this.hitTestCache.xvalues;
var xbefore = null;
var xafter = null;
for (var i = 1; i < xvalues.length; i++) {
if (xvalues[i] > xval) {
xbefore = xvalues[i-1];
xafter = xvalues[i];
break;
}
}
if ((xbefore != null)) {
var ybefore = this.hitTestCache.x2maxy[xbefore];
var yafter = this.hitTestCache.x2maxy[xafter];
var yval = (1.0 - y)/this.yscale;
// interpolate whether we will fall inside or outside
var gradient = (yafter - ybefore) / (xafter - xbefore);
var projmaxy = ybefore + gradient * (xval - xbefore);
if (projmaxy >= yval) {
// inside the highest curve (roughly)
var obj = {xval: xval, yval: yval,
xafter: xafter, yafter: yafter,
xbefore: xbefore, ybefore: ybefore,
yprojected: projmaxy
};
return obj;
}
}
}
else if (this.style == "pie") {
var dist = Math.sqrt((y-0.5)*(y-0.5) + (x-0.5)*(x-0.5));
if (dist > this.options.pieRadius)
return null;
// TODO: actually doesn't work if we don't know how the Canvas
// lays it out, need to fix!
var angle = Math.atan2(y - 0.5, x - 0.5) - Math.PI/2;
for (var i = 0; i < this.slices.length; i++) {
var slice = this.slices[i];
if (slice.startAngle < angle && slice.endAngle >= angle)
return slice;
}
}
return null;
};
// Reports valid position rectangle for X value (only valid for bar charts)
PlotKit.Layout.prototype.rectForX = function(x) {
return null;
};
// Reports valid angles through which X value encloses (only valid for pie charts)
PlotKit.Layout.prototype.angleRangeForX = function(x) {
return null;
};
// --------------------------------------------------------------------
// START Internal Functions
// --------------------------------------------------------------------
PlotKit.Layout.prototype._evaluateLimits = function() {
// take all values from all datasets and find max and min
var map = MochiKit.Base.map;
var items = MochiKit.Base.items;
var itemgetter = MochiKit.Base.itemgetter;
var collapse = PlotKit.Base.collapse;
var listMin = MochiKit.Base.listMin;
var listMax = MochiKit.Base.listMax;
var isNil = MochiKit.Base.isUndefinedOrNull;
var all = collapse(map(itemgetter(1), items(this.datasets)));
if (isNil(this.options.xAxis)) {
if (this.options.xOriginIsZero)
this.minxval = 0;
else
this.minxval = listMin(map(parseFloat, map(itemgetter(0), all)));
}
if (isNil(this.options.yAxis)) {
if (this.options.yOriginIsZero)
this.minyval = 0;
else
this.minyval = listMin(map(parseFloat, map(itemgetter(1), all)));
}
this.maxxval = listMax(map(parseFloat, map(itemgetter(0), all)));
this.maxyval = listMax(map(parseFloat, map(itemgetter(1), all)));
};
PlotKit.Layout.prototype._evaluateScales = function() {
var isNil = MochiKit.Base.isUndefinedOrNull;
this.xrange = this.maxxval - this.minxval;
if (this.xrange == 0)
this.xscale = 1.0;
else
this.xscale = 1/this.xrange;
this.yrange = this.maxyval - this.minyval;
if (this.yrange == 0)
this.yscale = 1.0;
else
this.yscale = 1/this.yrange;
};
PlotKit.Layout.prototype._uniqueXValues = function() {
var collapse = PlotKit.Base.collapse;
var map = MochiKit.Base.map;
var uniq = PlotKit.Base.uniq;
var getter = MochiKit.Base.itemgetter;
var xvalues = map(parseFloat, map(getter(0), collapse(map(getter(1), items(this.datasets)))));
xvalues.sort(MochiKit.Base.compare);
return uniq(xvalues);
};
// Create the bars
PlotKit.Layout.prototype._evaluateBarCharts = function() {
var keys = MochiKit.Base.keys;
var items = MochiKit.Base.items;
var setCount = keys(this.datasets).length;
// work out how far separated values are
var xdelta = 10000000;
var xvalues = this._uniqueXValues();
for (var i = 1; i < xvalues.length; i++) {
xdelta = Math.min(Math.abs(xvalues[i] - xvalues[i-1]), xdelta);
}
var barWidth = 0;
var barWidthForSet = 0;
var barMargin = 0;
if (xvalues.length == 1) {
// note we have to do something smarter if we only plot one value
xdelta = 1.0;
this.xscale = 1.0;
this.minxval = xvalues[0];
barWidth = 1.0 * this.options.barWidthFillFraction;
barWidthForSet = barWidth/setCount;
barMargin = (1.0 - this.options.barWidthFillFraction)/2;
}
else {
// readjust xscale to fix with bar charts
this.xscale = (1.0 - xdelta/this.xrange)/this.xrange;
barWidth = xdelta * this.xscale * this.options.barWidthFillFraction;
barWidthForSet = barWidth / setCount;
barMargin = xdelta * this.xscale * (1.0 - this.options.barWidthFillFraction)/2;
}
this.minxdelta = xdelta; // need this for tick positions
// add all the rects
this.bars = new Array();
var i = 0;
for (var setName in this.datasets) {
var dataset = this.datasets[setName];
for (var j = 0; j < dataset.length; j++) {
var item = dataset[j];
var rect = {
x: ((parseFloat(item[0]) - this.minxval) * this.xscale) + (i * barWidthForSet) + barMargin,
y: 1.0 - ((parseFloat(item[1]) - this.minyval) * this.yscale),
w: barWidthForSet,
h: ((parseFloat(item[1]) - this.minyval) * this.yscale),
xval: parseFloat(item[0]),
yval: parseFloat(item[1]),
name: setName
};
this.bars.push(rect);
}
i++;
}
};
// Create the line charts
PlotKit.Layout.prototype._evaluateLineCharts = function() {
var keys = MochiKit.Base.keys;
var items = MochiKit.Base.items;
var setCount = keys(this.datasets).length;
// add all the rects
this.points = new Array();
var i = 0;
for (var setName in this.datasets) {
var dataset = this.datasets[setName];
dataset.sort(function(a, b) { return compare(parseFloat(a[0]), parseFloat(b[0])); });
for (var j = 0; j < dataset.length; j++) {
var item = dataset[j];
var point = {
x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
y: 1.0 - ((parseFloat(item[1]) - this.minyval) * this.yscale),
xval: parseFloat(item[0]),
yval: parseFloat(item[1]),
name: setName
};
this.points.push(point);
}
i++;
}
};
// Create the pie charts
PlotKit.Layout.prototype._evaluatePieCharts = function() {
var items = MochiKit.Base.items;
var sum = MochiKit.Iter.sum;
var getter = MochiKit.Base.itemgetter;
var setCount = keys(this.datasets).length;
// we plot the y values of the first dataset
var dataset = items(this.datasets)[0][1];
var total = sum(map(getter(1), dataset));
this.slices = new Array();
var currentAngle = 0.0;
for (var i = 0; i < dataset.length; i++) {
var fraction = dataset[i][1] / total;
var startAngle = currentAngle * Math.PI * 2;
var endAngle = (currentAngle + fraction) * Math.PI * 2;
var slice = {fraction: fraction,
xval: dataset[i][0],
yval: dataset[i][1],
startAngle: startAngle,
endAngle: endAngle
};
this.slices.push(slice);
currentAngle += fraction;
}
};
PlotKit.Layout.prototype._evaluateLineTicksForXAxis = function() {
var isNil = MochiKit.Base.isUndefinedOrNull;
if (this.options.xTicks) {
// we use use specified ticks with optional labels
this.xticks = new Array();
var makeTicks = function(tick) {
var label = tick.label;
if (isNil(label))
label = tick.v.toString();
var pos = this.xscale * (tick.v - this.minxval);
this.xticks.push([pos, label]);
};
MochiKit.Iter.forEach(this.options.xTicks, bind(makeTicks, this));
}
else if (this.options.xNumberOfTicks) {
// we use defined number of ticks as hint to auto generate
var xvalues = this._uniqueXValues();
var roughSeparation = this.xrange / this.options.xNumberOfTicks;
var tickCount = 0;
this.xticks = new Array();
for (var i = 0; i <= xvalues.length; i++) {
if (xvalues[i] >= (tickCount) * roughSeparation) {
var pos = this.xscale * (xvalues[i] - this.minxval);
if ((pos > 1.0) || (pos < 0.0))
return;
this.xticks.push([pos, xvalues[i]]);
tickCount++;
}
if (tickCount > this.options.xNumberOfTicks)
break;
}
}
};
PlotKit.Layout.prototype._evaluateLineTicksForYAxis = function() {
var isNil = MochiKit.Base.isUndefinedOrNull;
if (this.options.yTicks) {
this.yticks = new Array();
var makeTicks = function(tick) {
var label = tick.label;
if (isNil(label))
label = tick.v.toString();
var pos = 1.0 - (this.yscale * (tick.v + this.minxval));
if ((pos < 0.0) || (pos > 1.0))
return;
this.yticks.push([pos, label]);
};
MochiKit.Iter.forEach(this.options.yTicks, bind(makeTicks, this));
}
else if (this.options.yNumberOfTicks) {
// We use the optionally defined number of ticks as a guide
this.yticks = new Array();
// if we get this separation right, we'll have good looking graphs
var roundInt = PlotKit.Base.roundInterval;
var prec = this.options.yTickPrecision;
var roughSeparation = roundInt(this.yrange,
this.options.yNumberOfTicks,
this.options.yTickPrecision);
for (var i = 0; i <= this.options.yNumberOfTicks; i++) {
var yval = this.minyval + (i * roughSeparation);
var pos = 1.0 - ((yval - this.minyval) * this.yscale);
this.yticks.push([pos, MochiKit.Format.roundToFixed(yval, 1)]);
}
}
};
PlotKit.Layout.prototype._evaluateLineTicks = function() {
this._evaluateLineTicksForXAxis();
this._evaluateLineTicksForYAxis();
};
PlotKit.Layout.prototype._evaluateBarTicks = function() {
this._evaluateLineTicks();
var centerInBar = function(tick) {
return [tick[0] + (this.minxdelta * this.xscale)/2, tick[1]];
};
this.xticks = MochiKit.Base.map(bind(centerInBar, this), this.xticks);
};
PlotKit.Layout.prototype._evaluatePieTicks = function() {
var isNil = MochiKit.Base.isUndefinedOrNull;
var formatter = MochiKit.Format.numberFormatter("#%");
this.xticks = new Array();
if (this.options.xTicks) {
// make a lookup dict for x->slice values
var lookup = new Array();
for (var i = 0; i < this.slices.length; i++) {
lookup[this.slices[i].xval] = this.slices[i];
}
for (var i =0; i < this.options.xTicks.length; i++) {
var tick = this.options.xTicks[i];
var slice = lookup[tick.v];
var label = tick.label;
if (slice) {
if (isNil(label))
label = tick.v.toString();
label += " (" + formatter(slice.fraction) + ")";
this.xticks.push([tick.v, label]);
}
}
}
else {
// we make our own labels from all the slices
for (var i =0; i < this.slices.length; i++) {
var slice = this.slices[i];
var label = slice.xval + " (" + formatter(slice.fraction) + ")";
this.xticks.push([slice.xval, label]);
}
}
};
PlotKit.Layout.prototype._regenerateHitTestCache = function() {
this.hitTestCache.xvalues = this._uniqueXValues();
this.hitTestCache.xlookup = new Array();
this.hitTestCache.x2maxy = new Array();
var listMax = MochiKit.Base.listMax;
var itemgetter = MochiKit.Base.itemgetter;
var map = MochiKit.Base.map;
// generate a lookup table for x values to y values
var setNames = keys(this.datasets);
for (var i = 0; i < setNames.length; i++) {
var dataset = this.datasets[setNames[i]];
for (var j = 0; j < dataset.length; j++) {
var xval = dataset[j][0];
var yval = dataset[j][1];
if (this.hitTestCache.xlookup[xval])
this.hitTestCache.xlookup[xval].push([yval, setNames[i]]);
else
this.hitTestCache.xlookup[xval] = [[yval, setNames[i]]];
}
}
for (var x in this.hitTestCache.xlookup) {
var yvals = this.hitTestCache.xlookup[x];
this.hitTestCache.x2maxy[x] = listMax(map(itemgetter(0), yvals));
}
};
// --------------------------------------------------------------------
// END Internal Functions
// --------------------------------------------------------------------

View File

@ -0,0 +1,677 @@
/*
PlotKit SVG
===========
SVG Renderer for PlotKit
Copyright
---------
Copyright 2005,2006 (c) Alastair Tse <alastair^liquidx.net>
For use under the BSD license. <http://www.liquidx.net/plotkit>
*/
// -------------------------------------------------------------------------
// NOTES: - If you use XHTML1.1 strict, then you must include each MochiKit
// file individuall.
// - For IE support, you must include the AdobeSVG object hack.
// See tests/svg.html for details.
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Check required components
// -------------------------------------------------------------------------
try {
if (typeof(PlotKit.Layout) == 'undefined')
{
throw "";
}
}
catch (e) {
throw "PlotKit depends on MochiKit.{Base,Color,DOM,Format} and PlotKit.Layout"
}
// ---------------------------------------------------------------------------
// SVG Renderer
// ---------------------------------------------------------------------------
PlotKit.SVGRenderer = function(element, layout, options) {
if (arguments.length > 0)
this.__init__(element, layout, options);
};
PlotKit.SVGRenderer.NAME = "PlotKit.SVGRenderer";
PlotKit.SVGRenderer.VERSION = PlotKit.VERSION;
PlotKit.SVGRenderer.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.SVGRenderer.toString = function() {
return this.__repr__();
}
PlotKit.SVGRenderer.isSupported = function() {
// TODO
return true;
};
PlotKit.SVGRenderer.prototype.__init__ = function(element, layout, options) {
var isNil = MochiKit.Base.isUndefinedOrNull;
// default options
this.options = {
"drawBackground": true,
"backgroundColor": Color.whiteColor(),
"padding": {left: 30, right: 30, top: 5, bottom: 10},
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[1]),
"strokeColor": Color.whiteColor(),
"strokeColorTransform": "asStrokeColor",
"strokeWidth": 0.5,
"shouldFill": true,
"shouldStroke": true,
"drawXAxis": true,
"drawYAxis": true,
"axisLineColor": Color.blackColor(),
"axisLineWidth": 0.5,
"axisTickSize": 3,
"axisLabelColor": Color.blackColor(),
"axisLabelFont": "Arial",
"axisLabelFontSize": 9,
"axisLabelWidth": 50,
"axisLabelUseDiv": true,
"pieRadius": 0.4,
"enableEvents": true
};
MochiKit.Base.update(this.options, options ? options : {});
this.layout = layout;
this.style = layout.style;
this.element = MochiKit.DOM.getElement(element);
this.container = this.element.parentNode;
this.height = parseInt(this.element.getAttribute("height"));
this.width = parseInt(this.element.getAttribute("width"));
this.document = document;
this.root = this.element;
// Adobe SVG Support:
// - if an exception is thrown, then no Adobe SVG Plugin support.
try {
this.document = this.element.getSVGDocument();
this.root = isNil(this.document.documentElement) ? this.element : this.document.documentElement;
}
catch (e) {
}
this.element.style.zIndex = 1;
if (isNil(this.element))
throw "SVGRenderer() - passed SVG object is not found";
if (isNil(this.container) || this.container.nodeName.toLowerCase() != "div")
throw "SVGRenderer() - No DIV's around the SVG.";
// internal state
this.xlabels = new Array();
this.ylabels = new Array();
// initialise some meta structures in SVG
this.defs = this.createSVGElement("defs");
this.area = {
x: this.options.padding.left,
y: this.options.padding.top,
w: this.width - this.options.padding.left - this.options.padding.right,
h: this.height - this.options.padding.top - this.options.padding.bottom
};
MochiKit.DOM.updateNodeAttributes(this.container,
{"style":{ "position": "relative", "width": this.width + "px"}});
};
PlotKit.SVGRenderer.prototype.render = function() {
if (this.options.drawBackground)
this._renderBackground();
if (this.style == "bar") {
this._renderBarChart();
this._renderBarAxis();
}
else if (this.style == "pie") {
this._renderPieChart();
this._renderPieAxis();
}
else if (this.style == "line") {
this._renderLineChart();
this._renderLineAxis();
}
};
PlotKit.SVGRenderer.prototype._renderBarOrLine = function(data, plotFunc, startFunc, endFunc) {
var colorCount = this.options.colorScheme.length;
var colorScheme = this.options.colorScheme;
var setNames = MochiKit.Base.keys(this.layout.datasets);
var setCount = setNames.length;
for (var i = 0; i < setCount; i++) {
var setName = setNames[i];
var attrs = new Array();
var color = colorScheme[i%colorCount];
if (this.options.shouldFill)
attrs["fill"] = color.toRGBString();
else
attrs["fill"] = "none";
if (this.options.shouldStroke &&
(this.options.strokeColor || this.options.strokeColorTransform)) {
if (this.options.strokeColor)
attrs["stroke"] = this.options.strokeColor.toRGBString();
else if (this.options.strokeColorTransform)
attrs["stroke"] = color[this.options.strokeColorTransform]().toRGBString();
attrs["strokeWidth"] = this.options.strokeWidth;
}
if (startFunc)
startFunc(attrs);
var forEachFunc = function(obj) {
if (obj.name == setName)
plotFunc(attrs, obj);
};
MochiKit.Iter.forEach(data, bind(forEachFunc, this));
if (endFunc)
endFunc(attrs);
}
};
PlotKit.SVGRenderer.prototype._renderBarChart = function() {
var bind = MochiKit.Base.bind;
var drawRect = function(attrs, bar) {
var x = this.area.w * bar.x + this.area.x;
var y = this.area.h * bar.y + this.area.y;
var w = this.area.w * bar.w;
var h = this.area.h * bar.h;
this._drawRect(x, y, w, h, attrs);
};
this._renderBarOrLine(this.layout.bars, bind(drawRect, this));
};
PlotKit.SVGRenderer.prototype._renderLineChart = function() {
var bind = MochiKit.Base.bind;
var addPoint = function(attrs, point) {
this._tempPointsBuffer += (this.area.w * point.x + this.area.x) + "," +
(this.area.h * point.y + this.area.y) + " ";
};
var startLine = function(attrs) {
this._tempPointsBuffer = "";
this._tempPointsBuffer += (this.area.x) + "," + (this.area.y+this.area.h) + " ";
};
var endLine = function(attrs) {
this._tempPointsBuffer += (this.area.w + this.area.x) + "," +(this.area.h + this.area.y);
attrs["points"] = this._tempPointsBuffer;
var elem = this.createSVGElement("polygon", attrs);
this.root.appendChild(elem);
};
this._renderBarOrLine(this.layout.points,
bind(addPoint, this),
bind(startLine, this),
bind(endLine, this));
};
PlotKit.SVGRenderer.prototype._renderPieChart = function() {
var colorCount = this.options.colorScheme.length;
var slices = this.layout.slices;
var centerx = this.area.x + this.area.w * 0.5;
var centery = this.area.y + this.area.h * 0.5;
var radius = Math.min(this.area.w * this.options.pieRadius,
this.area.h * this.options.pieRadius);
// NOTE NOTE!! Canvas Tag draws the circle clockwise from the y = 0, x = 1
// so we have to subtract 90 degrees to make it start at y = 1, x = 0
// workaround if we only have 1 slice of 100%
if (slices.length == 1 && (Math.abs(slices[0].startAngle) - Math.abs(slices[0].endAngle) < 0.1)) {
var attrs = {"cx": centerx , "cy": centery , "r": radius };
var color = this.options.colorScheme[0];
if (this.options.shouldFill)
attrs["fill"] = color.toRGBString();
else
attrs["fill"] = "none";
if (this.options.shouldStroke &&
(this.options.strokeColor || this.options.strokeColorTransform)) {
if (this.options.strokeColor)
attrs["stroke"] = this.options.strokeColor.toRGBString();
else if (this.options.strokeColorTransform)
attrs["stroke"] = color[this.options.strokeColorTransform]().toRGBString();
attrs["style"] = "stroke-width: " + this.options.strokeWidth;
}
this.root.appendChild(this.createSVGElement("circle", attrs));
return;
}
for (var i = 0; i < slices.length; i++) {
var attrs = new Array();
var color = this.options.colorScheme[i%colorCount];
if (this.options.shouldFill)
attrs["fill"] = color.toRGBString();
else
attrs["fill"] = "none";
if (this.options.shouldStroke &&
(this.options.strokeColor || this.options.strokeColorTransform)) {
if (this.options.strokeColor)
attrs["stroke"] = this.options.strokeColor.toRGBString();
else if (this.options.strokeColorTransform)
attrs["stroke"] = color[this.options.strokeColorTransform]().toRGBString();
attrs["style"] = "stroke-width:" + this.options.strokeWidth;
}
var largearc = 0;
if (Math.abs(slices[i].endAngle - slices[i].startAngle) > Math.PI)
largearc = 1;
var x1 = Math.cos(slices[i].startAngle - Math.PI/2) * radius;
var y1 = Math.sin(slices[i].startAngle - Math.PI/2) * radius;
var x2 = Math.cos(slices[i].endAngle - Math.PI/2) * radius;
var y2 = Math.sin(slices[i].endAngle - Math.PI/2) * radius;
var rx = x2 - x1;
var ry = y2 - y1;
var pathString = "M" + centerx + "," + centery + " ";
pathString += "l" + x1 + "," + y1 + " ";
pathString += "a" + radius + "," + radius + " 0 " + largearc + ",1 " + rx + "," + ry + " z";
attrs["d"] = pathString;
var elem = this.createSVGElement("path", attrs);
this.root.appendChild(elem);
}
};
PlotKit.SVGRenderer.prototype._renderBarAxis = function() {
this._renderAxis();
}
PlotKit.SVGRenderer.prototype._renderLineAxis = function() {
this._renderAxis();
};
PlotKit.SVGRenderer.prototype._renderAxis = function() {
if (!this.options.drawXAxis && !this.options.drawYAxis)
return;
var labelStyle = {"style":
{"position": "absolute",
"textAlign": "center",
"fontSize": this.options.axisLabelFontSize + "px",
"zIndex": 10,
"color": this.options.axisLabelColor.toRGBString(),
"width": this.options.axisLabelWidth + "px",
"overflow": "hidden"
}
};
// axis lines
var lineAttrs = {
"stroke": this.options.axisLineColor.toRGBString(),
"strokeWidth": this.options.axisLineWidth
};
if (this.options.drawYAxis) {
if (this.layout.yticks) {
var drawTick = function(tick) {
var x = this.area.x;
var y = this.area.y + tick[0] * this.area.h;
this._drawLine(x, y, x - 3, y, lineAttrs);
if (this.options.axisLabelUseDiv) {
var label = DIV(labelStyle, tick[1]);
label.style.top = (y - this.options.axisLabelFontSize) + "px";
label.style.left = (x - this.options.padding.left + this.options.axisTickSize) + "px";
label.style.textAlign = "left";
label.style.width = (this.options.padding.left - 3) + "px";
MochiKit.DOM.appendChildNodes(this.container, label);
this.ylabels.push(label);
}
else {
var attrs = {
y: y + 3,
x: (x - this.options.padding.left + 3),
width: (this.options.padding.left - this.options.axisTickSize) + "px",
height: (this.options.axisLabelFontSize + 3) + "px",
fontFamily: "Arial",
fontSize: this.options.axisLabelFontSize + "px",
fill: this.options.axisLabelColor.toRGBString()
};
/* we can do clipping just like DIVs
http://www.xml.com/pub/a/2004/06/02/svgtype.html */
/*
var mask = this.createSVGElement("mask", {id: "mask" + tick[0]});
var maskShape = this.createSVGElement("rect",
{y: y + 3,
x: (x - this.options.padding.left + 3),
width: (this.options.padding.left - this.options.axisTickSize) + "px",
height: (this.options.axisLabelFontSize + 3) + "px",
style: {"fill": "#ffffff", "stroke": "#000000"}});
mask.appendChild(maskShape);
this.defs.appendChild(mask);
attrs["filter"] = "url(#mask" + tick[0] + ")";
*/
var label = this.createSVGElement("text", attrs);
label.appendChild(this.document.createTextNode(tick[1]));
this.root.appendChild(label);
}
};
MochiKit.Iter.forEach(this.layout.yticks, bind(drawTick, this));
}
this._drawLine(this.area.x, this.area.y, this.area.x, this.area.y + this.area.h, lineAttrs);
}
if (this.options.drawXAxis) {
if (this.layout.xticks) {
var drawTick = function(tick) {
var x = this.area.x + tick[0] * this.area.w;
var y = this.area.y + this.area.h;
this._drawLine(x, y, x, y + this.options.axisTickSize, lineAttrs);
if (this.options.axisLabelUseDiv) {
var label = DIV(labelStyle, tick[1]);
label.style.top = (y + this.options.axisTickSize) + "px";
label.style.left = (x - this.options.axisLabelWidth/2) + "px";
label.style.textAlign = "center";
label.style.width = this.options.axisLabelWidth + "px";
MochiKit.DOM.appendChildNodes(this.container, label);
this.xlabels.push(label);
}
else {
var attrs = {
y: (y + this.options.axisTickSize + this.options.axisLabelFontSize),
x: x - 3,
width: this.options.axisLabelWidth + "px",
height: (this.options.axisLabelFontSize + 3) + "px",
fontFamily: "Arial",
fontSize: this.options.axisLabelFontSize + "px",
fill: this.options.axisLabelColor.toRGBString(),
textAnchor: "middle"
};
var label = this.createSVGElement("text", attrs);
label.appendChild(this.document.createTextNode(tick[1]));
this.root.appendChild(label);
}
};
MochiKit.Iter.forEach(this.layout.xticks, bind(drawTick, this));
}
this._drawLine(this.area.x, this.area.y + this.area.h, this.area.x + this.area.w, this.area.y + this.area.h, lineAttrs)
}
};
PlotKit.SVGRenderer.prototype._renderPieAxis = function() {
if (this.layout.xticks) {
// make a lookup dict for x->slice values
var lookup = new Array();
for (var i = 0; i < this.layout.slices.length; i++) {
lookup[this.layout.slices[i].xval] = this.layout.slices[i];
}
var centerx = this.area.x + this.area.w * 0.5;
var centery = this.area.y + this.area.h * 0.5;
var radius = Math.min(this.area.w * this.options.pieRadius + 10,
this.area.h * this.options.pieRadius + 10);
var labelWidth = this.options.axisLabelWidth;
for (var i = 0; i < this.layout.xticks.length; i++) {
var slice = lookup[this.layout.xticks[i][0]];
if (MochiKit.Base.isUndefinedOrNull(slice))
continue;
var angle = (slice.startAngle + slice.endAngle)/2;
// normalize the angle
var normalisedAngle = angle;
if (normalisedAngle > Math.PI * 2)
normalisedAngle = normalisedAngle - Math.PI * 2;
else if (normalisedAngle < 0)
normalisedAngle = normalisedAngle + Math.PI * 2;
var labelx = centerx + Math.sin(normalisedAngle) * (radius + 10);
var labely = centery - Math.cos(normalisedAngle) * (radius + 10);
var attrib = {
"position": "absolute",
"zIndex": 11,
"width": labelWidth + "px",
"fontSize": this.options.axisLabelFontSize + "px",
"overflow": "hidden",
"color": this.options.axisLabelColor.toHexString()
};
var svgattrib = {
"width": labelWidth + "px",
"fontSize": this.options.axisLabelFontSize + "px",
"height": (this.options.axisLabelFontSize + 3) + "px",
"fill": this.options.axisLabelColor.toRGBString()
};
if (normalisedAngle <= Math.PI * 0.5) {
// text on top and align left
MochiKit.Base.update(attrib, {
'textAlign': 'left', 'verticalAlign': 'top',
'left': labelx + 'px',
'top': (labely - this.options.axisLabelFontSize) + "px"
});
MochiKit.Base.update(svgattrib, {
"x": labelx,
"y" :(labely - this.options.axisLabelFontSize),
"textAnchor": "left"
});
}
else if ((normalisedAngle > Math.PI * 0.5) && (normalisedAngle <= Math.PI)) {
// text on bottom and align left
MochiKit.Base.update(attrib, {
'textAlign': 'left', 'verticalAlign': 'bottom',
'left': labelx + 'px',
'top': labely + "px"
});
MochiKit.Base.update(svgattrib, {
'textAnchor': 'left',
'x': labelx,
'y': labely
});
}
else if ((normalisedAngle > Math.PI) && (normalisedAngle <= Math.PI*1.5)) {
// text on bottom and align right
MochiKit.Base.update(attrib, {
'textAlign': 'right', 'verticalAlign': 'bottom',
'left': labelx + 'px',
'top': labely + "px"
});
MochiKit.Base.update(svgattrib, {
'textAnchor': 'right',
'x': labelx - labelWidth,
'y': labely
});
}
else {
// text on top and align right
MochiKit.Base.update(attrib, {
'textAlign': 'left', 'verticalAlign': 'bottom',
'left': labelx + 'px',
'top': labely + "px"
});
MochiKit.Base.update(svgattrib, {
'textAnchor': 'left',
'x': labelx - labelWidth,
'y': labely - this.options.axisLabelFontSize
});
}
if (this.options.axisLabelUseDiv) {
var label = DIV({'style': attrib}, this.layout.xticks[i][1]);
this.xlabels.push(label);
MochiKit.DOM.appendChildNodes(this.container, label);
}
else {
var label = this.createSVGElement("text", svgattrib);
label.appendChild(this.document.createTextNode(this.layout.xticks[i][1]))
this.root.appendChild(label);
}
}
}
};
PlotKit.SVGRenderer.prototype._renderBackground = function() {
var opts = {"stroke": "none",
"fill": this.options.backgroundColor.toRGBString()
};
this._drawRect(0, 0, this.width, this.height, opts);
};
PlotKit.SVGRenderer.prototype._drawRect = function(x, y, w, h, moreattrs) {
var attrs = {x: x + "px", y: y + "px", width: w + "px", height: h + "px"};
if (moreattrs)
MochiKit.Base.update(attrs, moreattrs);
var elem = this.createSVGElement("rect", attrs);
this.root.appendChild(elem);
};
PlotKit.SVGRenderer.prototype._drawLine = function(x1, y1, x2, y2, moreattrs) {
var attrs = {x1: x1 + "px", y1: y1 + "px", x2: x2 + "px", y2: y2 + "px"};
if (moreattrs)
MochiKit.Base.update(attrs, moreattrs);
var elem = this.createSVGElement("line", attrs);
this.root.appendChild(elem);
}
PlotKit.SVGRenderer.prototype.clear = function() {
while(this.element.firstChild) {
this.element.removeChild(this.element.firstChild);
}
if (this.options.axisLabelUseDiv) {
for (var i = 0; i < this.xlabels.length; i++) {
MochiKit.DOM.removeElement(this.xlabels[i]);
}
for (var i = 0; i < this.ylabels.length; i++) {
MochiKit.DOM.removeElement(this.ylabels[i]);
}
}
this.xlabels = new Array();
this.ylabels = new Array();
};
PlotKit.SVGRenderer.prototype.createSVGElement = function(name, attrs) {
var isNil = MochiKit.Base.isUndefinedOrNull;
var elem;
var doc = isNil(this.document) ? document : this.document;
try {
elem = doc.createElementNS("http://www.w3.org/2000/svg", name);
}
catch (e) {
elem = doc.createElement(name);
elem.setAttribute("xmlns", "http://www.w3.org/2000/svg");
}
if (attrs)
MochiKit.DOM.updateNodeAttributes(elem, attrs);
// TODO: we don't completely emulate the MochiKit.DOM.createElement
// as we don't care about nodes contained. We really should though.
return elem;
};
PlotKit.SVGRenderer.SVGNS = 'http://www.w3.org/2000/svg';
PlotKit.SVGRenderer.SVG = function(attrs) {
// we have to do things differently for IE+AdobeSVG.
// My guess this works (via trial and error) is that we need to
// have an SVG object in order to use SVGDocument.createElementNS
// but IE doesn't allow us to that.
var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
if (ie && (ie[1] >= 6) && (!opera)) {
var width = attrs["width"] ? attrs["width"] : "100";
var height = attrs["height"] ? attrs["height"] : "100";
var eid = attrs["id"] ? attrs["id"] : "notunique";
var html = '<svg:svg width="' + width + '" height="' + height + '" ';
html += 'id="' + eid + '" version="1.1" baseProfile="full">';
var canvas = document.createElement(html);
// create embedded SVG inside SVG.
var group = canvas.getSVGDocument().createElementNS(PlotKit.SVGRenderer.SVGNS, "svg");
group.setAttribute("width", width);
group.setAttribute("height", height);
canvas.getSVGDocument().appendChild(group);
return canvas;
}
else {
return PlotKit.SVGRenderer.prototype.createSVGElement("svg", attrs);
}
};
PlotKit.SVGRenderer.isSupported = function() {
var isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
var ieVersion = navigator.appVersion.match(/MSIE (\d\.\d)/);
var safariVersion = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
var operaVersion = navigator.userAgent.match(/Opera\/(\d*\.\d*)/);
var mozillaVersion = navigator.userAgent.match(/rv:(\d*\.\d*).*Gecko/);
if (ieVersion && (ieVersion[1] >= 6) && !isOpera) {
var dummysvg = document.createElement('<svg:svg width="1" height="1" baseProfile="full" version="1.1" id="dummy">');
try {
dummysvg.getSVGDocument();
dummysvg = null;
return true;
}
catch (e) {
return false;
}
}
/* support not really there yet. no text and paths are buggy
if (safariVersion && (safariVersion[1] > 419))
return true;
*/
if (operaVersion && (operaVersion[1] > 8.9))
return true
if (mozillaVersion && (mozillaVersion > 1.7))
return true;
return false;
};

View File

@ -0,0 +1,281 @@
/*
PlotKit Sweet Canvas Renderer
=============================
Canvas Renderer for PlotKit which looks pretty!
Copyright
---------
Copyright 2005,2006 (c) Alastair Tse <alastair^liquidx.net>
For use under the BSD license. <http://www.liquidx.net/plotkit>
*/
// -------------------------------------------------------------------------
// Check required components
// -------------------------------------------------------------------------
try {
if (typeof(PlotKit.CanvasRenderer) == 'undefined')
{
throw "";
}
}
catch (e) {
throw "SweetCanvas depends on MochiKit.{Base,Color,DOM,Format} and PlotKit.{Layout, Canvas}"
}
if (typeof(PlotKit.SweetCanvasRenderer) == 'undefined') {
PlotKit.SweetCanvasRenderer = {};
}
PlotKit.SweetCanvasRenderer = function(element, layout, options) {
if (arguments.length > 0) {
this.__init__(element, layout, options);
}
};
PlotKit.SweetCanvasRenderer.NAME = "PlotKit.SweetCanvasRenderer";
PlotKit.SweetCanvasRenderer.VERSION = PlotKit.VERSION;
PlotKit.SweetCanvasRenderer.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.SweetCanvasRenderer.toString = function() {
return this.__repr__();
};
// ---------------------------------------------------------------------
// Subclassing Magic
// ---------------------------------------------------------------------
PlotKit.SweetCanvasRenderer.prototype = new PlotKit.CanvasRenderer();
PlotKit.SweetCanvasRenderer.prototype.constructor = PlotKit.SweetCanvasRenderer;
PlotKit.SweetCanvasRenderer.__super__ = PlotKit.CanvasRenderer.prototype;
// ---------------------------------------------------------------------
// Constructor
// ---------------------------------------------------------------------
PlotKit.SweetCanvasRenderer.prototype.__init__ = function(el, layout, opts) {
var moreOpts = PlotKit.Base.officeBlue();
MochiKit.Base.update(moreOpts, opts);
PlotKit.SweetCanvasRenderer.__super__.__init__.call(this, el, layout, moreOpts);
};
// ---------------------------------------------------------------------
// Extended Plotting Functions
// ---------------------------------------------------------------------
PlotKit.SweetCanvasRenderer.prototype._renderBarChart = function() {
var bind = MochiKit.Base.bind;
var shadowColor = Color.blackColor().colorWithAlpha(0.1).toRGBString();
var prepareFakeShadow = function(context, x, y, w, h) {
context.fillStyle = shadowColor;
context.fillRect(x-2, y-2, w+4, h+2);
context.fillStyle = shadowColor;
context.fillRect(x-1, y-1, w+2, h+1);
};
var colorCount = this.options.colorScheme.length;
var colorScheme = this.options.colorScheme;
var setNames = MochiKit.Base.keys(this.layout.datasets);
var setCount = setNames.length;
var chooseColor = function(name) {
for (var i = 0; i < setCount; i++) {
if (name == setNames[i])
return colorScheme[i%colorCount];
}
return colorScheme[0];
};
var drawRect = function(context, bar) {
var x = this.area.w * bar.x + this.area.x;
var y = this.area.h * bar.y + this.area.y;
var w = this.area.w * bar.w;
var h = this.area.h * bar.h;
if ((w < 1) || (h < 1))
return;
context.save();
context.shadowBlur = 5.0;
context.shadowColor = Color.fromHexString("#888888").toRGBString();
if (this.isIE) {
context.save();
context.fillStyle = "#cccccc";
context.fillRect(x-2, y-2, w+4, h+2);
context.restore();
}
else {
prepareFakeShadow(context, x, y, w, h);
}
context.fillStyle = chooseColor(bar.name).toRGBString();
context.fillRect(x, y, w, h);
context.shadowBlur = 0;
context.strokeStyle = Color.whiteColor().toRGBString();
context.lineWidth = 2.0;
context.strokeRect(x, y, w, h);
context.restore();
};
this._renderBarChartWrap(this.layout.bars, bind(drawRect, this));
};
PlotKit.CanvasRenderer.prototype._renderLineChart = function() {
var context = this.element.getContext("2d");
var colorCount = this.options.colorScheme.length;
var colorScheme = this.options.colorScheme;
var setNames = MochiKit.Base.keys(this.layout.datasets);
var setCount = setNames.length;
var bind = MochiKit.Base.bind;
for (var i = 0; i < setCount; i++) {
var setName = setNames[i];
var color = colorScheme[i%colorCount];
var strokeX = this.options.strokeColorTransform;
// setup graphics context
context.save();
// create paths
var makePath = function() {
context.beginPath();
context.moveTo(this.area.x, this.area.y + this.area.h);
var addPoint = function(context, point) {
if (point.name == setName)
context.lineTo(this.area.w * point.x + this.area.x,
this.area.h * point.y + this.area.y);
};
MochiKit.Iter.forEach(this.layout.points, partial(addPoint, context), this);
context.lineTo(this.area.w + this.area.x,
this.area.h + this.area.y);
context.lineTo(this.area.x, this.area.y + this.area.h);
context.closePath();
};
// faux shadow for firefox
context.save();
if (this.isIE) {
context.fillStyle = "#cccccc";
}
else {
context.fillStyle = Color.blackColor().colorWithAlpha(0.2).toRGBString();
}
context.translate(-1, -2);
bind(makePath, this)();
context.fill();
context.restore();
context.shadowBlur = 5.0;
context.shadowColor = Color.fromHexString("#888888").toRGBString();
context.fillStyle = color.toRGBString();
context.lineWidth = 2.0;
context.strokeStyle = Color.whiteColor().toRGBString();
bind(makePath, this)();
context.fill();
bind(makePath, this)();
context.stroke();
context.restore();
}
};
PlotKit.CanvasRenderer.prototype._renderPieChart = function() {
var context = this.element.getContext("2d");
var colorCount = this.options.colorScheme.length;
var slices = this.layout.slices;
var centerx = this.area.x + this.area.w * 0.5;
var centery = this.area.y + this.area.h * 0.5;
var radius = Math.min(this.area.w * this.options.pieRadius,
this.area.h * this.options.pieRadius);
if (this.isIE) {
centerx = parseInt(centerx);
centery = parseInt(centery);
radius = parseInt(radius);
}
// NOTE NOTE!! Canvas Tag draws the circle clockwise from the y = 0, x = 1
// so we have to subtract 90 degrees to make it start at y = 1, x = 0
if (!this.isIE) {
context.save();
var shadowColor = Color.blackColor().colorWithAlpha(0.2);
context.fillStyle = shadowColor.toRGBString();
context.shadowBlur = 5.0;
context.shadowColor = Color.fromHexString("#888888").toRGBString();
context.translate(1, 1);
context.beginPath();
context.moveTo(centerx, centery);
context.arc(centerx, centery, radius + 2, 0, Math.PI*2, false);
context.closePath();
context.fill();
context.restore();
}
context.save();
context.strokeStyle = Color.whiteColor().toRGBString();
context.lineWidth = 2.0;
for (var i = 0; i < slices.length; i++) {
var color = this.options.colorScheme[i%colorCount];
context.fillStyle = color.toRGBString();
var makePath = function() {
context.beginPath();
context.moveTo(centerx, centery);
context.arc(centerx, centery, radius,
slices[i].startAngle - Math.PI/2,
slices[i].endAngle - Math.PI/2,
false);
context.lineTo(centerx, centery);
context.closePath();
};
if (Math.abs(slices[i].startAngle - slices[i].endAngle) > 0.0001) {
makePath();
context.fill();
makePath();
context.stroke();
}
}
context.restore();
};
PlotKit.SweetCanvasRenderer.prototype._renderBackground = function() {
var context = this.element.getContext("2d");
if (this.layout.style == "bar" || this.layout.style == "line") {
context.save();
context.fillStyle = this.options.backgroundColor.toRGBString();
context.fillRect(this.area.x, this.area.y, this.area.w, this.area.h);
context.strokeStyle = Color.whiteColor().toRGBString();
context.lineWidth = 1.0;
for (var i = 0; i < this.layout.yticks.length; i++) {
var y = this.layout.yticks[i][0] * this.area.h + this.area.y;
var x = this.area.x;
context.beginPath();
context.moveTo(x, y);
context.lineTo(x + this.area.w, y);
context.closePath();
context.stroke();
}
context.restore();
}
else {
PlotKit.SweetCanvasRenderer.__super__._renderBackground.call(this);
}
};

View File

@ -0,0 +1,196 @@
/*
PlotKit Sweet SVG Renderer
==========================
SVG Renderer for PlotKit which looks pretty!
Copyright
---------
Copyright 2005,2006 (c) Alastair Tse <alastair^liquidx.net>
For use under the BSD license. <http://www.liquidx.net/plotkit>
*/
// -------------------------------------------------------------------------
// Check required components
// -------------------------------------------------------------------------
try {
if (typeof(PlotKit.SVGRenderer) == 'undefined')
{
throw "";
}
}
catch (e) {
throw "SweetSVG depends on MochiKit.{Base,Color,DOM,Format} and PlotKit.{Layout, SVG}"
}
if (typeof(PlotKit.SweetSVGRenderer) == 'undefined') {
PlotKit.SweetSVGRenderer = {};
}
PlotKit.SweetSVGRenderer = function(element, layout, options) {
if (arguments.length > 0) {
this.__init__(element, layout, options);
}
};
PlotKit.SweetSVGRenderer.NAME = "PlotKit.SweetSVGRenderer";
PlotKit.SweetSVGRenderer.VERSION = PlotKit.VERSION;
PlotKit.SweetSVGRenderer.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.SweetSVGRenderer.toString = function() {
return this.__repr__();
};
// ---------------------------------------------------------------------
// Subclassing Magic
// ---------------------------------------------------------------------
PlotKit.SweetSVGRenderer.prototype = new PlotKit.SVGRenderer();
PlotKit.SweetSVGRenderer.prototype.constructor = PlotKit.SweetSVGRenderer;
PlotKit.SweetSVGRenderer.__super__ = PlotKit.SVGRenderer.prototype;
// ---------------------------------------------------------------------
// Constructor
// ---------------------------------------------------------------------
PlotKit.SweetSVGRenderer.prototype.__init__ = function(element, layout, options) {
var moreOpts = PlotKit.Base.officeBlue();
MochiKit.Base.update(moreOpts, options);
PlotKit.SweetSVGRenderer.__super__.__init__.call(this, element, layout, moreOpts);
//this._addDropShadowFilter();
};
PlotKit.SweetSVGRenderer.prototype._addDropShadowFilter = function() {
var filter = this.createSVGElement("filter", {x: 0, y: 0, "id":"dropShadow"});
var goffset = this.createSVGElement("feOffset",
{"in": "SourceGraphic", "dx": 0, "dy": 0, "result": "topCopy"});
var blur = this.createSVGElement("feGaussianBlur",
{"in": "SourceAlpha", "StdDeviation": 2, "result": "shadow"});
var soffset = this.createSVGElement("feOffset",
{"in": "shadow", "dx": -1, "dy": -2, "result":"movedShadow"});
var merge = this.createSVGElement("feMerge");
var gmerge = this.createSVGElement("feMergeNode", {"in":"topCopy"});
var smerge = this.createSVGElement("feMergeNode", {"in":"movedShadow"});
merge.appendChild(gmerge);
merge.appendChild(smerge);
filter.appendChild(goffset);
filter.appendChild(blur);
filter.appendChild(soffset);
filter.appendChild(merge);
this.defs.appendChild(filter);
};
// ---------------------------------------------------------------------
// Extended Plotting Functions
// ---------------------------------------------------------------------
PlotKit.SweetSVGRenderer.prototype._renderBarChart = function() {
var bind = MochiKit.Base.bind;
var shadowColor = Color.blackColor().toRGBString();
var shadowStyle = "fill:" + shadowColor + ";fill-opacity:0.15";
var strokeStyle = "stroke-width: 2.0; stroke:" + Color.whiteColor().toRGBString();
var drawRect = function(attrs, bar) {
var x = this.area.w * bar.x + this.area.x;
var y = this.area.h * bar.y + this.area.y;
var w = this.area.w * bar.w;
var h = this.area.h * bar.h;
if ((w < 1) || (h < 1))
return;
//attrs["filter"] = "url(#dropShadow)";
attrs["style"] = strokeStyle;
this._drawRect(x - 2, y - 1, w+4, h+2, {"style":shadowStyle});
this._drawRect(x, y, w, h, attrs);
};
this._renderBarOrLine(this.layout.bars, bind(drawRect, this));
};
PlotKit.SweetSVGRenderer.prototype._renderLineChart = function() {
var bind = MochiKit.Base.bind;
var shadowColor = Color.blackColor().toRGBString();
var shadowStyle = "fill:" + shadowColor + ";fill-opacity:0.15";
var strokeStyle = "stroke-width: 2.0; stroke:" + Color.whiteColor().toRGBString();
var addPoint = function(attrs, point) {
this._tempPointsBuffer += (this.area.w * point.x + this.area.x) + "," +
(this.area.h * point.y + this.area.y) + " ";
};
var startLine = function(attrs) {
this._tempPointsBuffer = "";
this._tempPointsBuffer += (this.area.x) + "," + (this.area.y+this.area.h) + " ";
};
var endLine = function(attrs) {
this._tempPointsBuffer += (this.area.w + this.area.x) + "," +(this.area.h + this.area.y);
attrs["points"] = this._tempPointsBuffer;
attrs["stroke"] = "none";
attrs["transform"] = "translate(-2, -1)";
attrs["style"] = shadowStyle;
var shadow = this.createSVGElement("polygon", attrs);
this.root.appendChild(shadow);
attrs["transform"] = "";
attrs["style"] = strokeStyle;
var elem = this.createSVGElement("polygon", attrs);
this.root.appendChild(elem);
};
this._renderBarOrLine(this.layout.points,
bind(addPoint, this),
bind(startLine, this),
bind(endLine, this));
};
PlotKit.SweetSVGRenderer.prototype._renderPieChart = function() {
var centerx = this.area.x + this.area.w * 0.5;
var centery = this.area.y + this.area.h * 0.5;
var shadowColor = Color.blackColor().toRGBString();
var radius = Math.min(this.area.w * this.options.pieRadius,
this.area.h * this.options.pieRadius);
var shadowStyle = "fill:" + shadowColor + ";fill-opacity:0.15";
var shadow = this.createSVGElement("circle",
{"style": shadowStyle, "cx": centerx + 1, "cy": centery + 1, "r": radius + 1});
this.root.appendChild(shadow);
PlotKit.SweetSVGRenderer.__super__._renderPieChart.call(this);
};
PlotKit.SweetSVGRenderer.prototype._renderBackground = function() {
var attrs = {
"fill": this.options.backgroundColor.toRGBString(),
"stroke": "none"
};
if (this.layout.style == "bar" || this.layout.style == "line") {
this._drawRect(this.area.x, this.area.y,
this.area.w, this.area.h, attrs);
for (var i = 0; i < this.layout.yticks.length; i++) {
this._drawRect(this.area.x,
this.layout.yticks[i][0] * this.area.h + this.area.y,
this.area.w,
1,
{"fill": Color.whiteColor().toRGBString()});
}
}
else {
PlotKit.SweetSVGRenderer.__super__._renderBackground.call(this);
}
};

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://web.resource.org/cc/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>

After

Width:  |  Height:  |  Size: 342 B

View File

@ -0,0 +1,389 @@
/*----------------------------------------------------------------------------\
| IE Canvas 1.0 |
|-----------------------------------------------------------------------------|
| Created by Emil A Eklund |
| (http://eae.net/contact/emil) |
|-----------------------------------------------------------------------------|
| Implementation of the canvas API for Internet Explorer. Uses VML. |
|-----------------------------------------------------------------------------|
| Copyright (c) 2005 Emil A Eklund |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| This program is free software; you can redistribute it and/or modify it |
| under the terms of the MIT License. |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| Permission is hereby granted, free of charge, to any person obtaining a |
| copy of this software and associated documentation files (the "Software"), |
| to deal in the Software without restriction, including without limitation |
| the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| and/or sell copies of the Software, and to permit persons to whom the |
| Software is furnished to do so, subject to the following conditions: |
| The above copyright notice and this permission notice shall be included in |
| all copies or substantial portions of the Software. |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| DEALINGS IN THE SOFTWARE. |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| http://eae.net/license/mit |
|-----------------------------------------------------------------------------|
| Dependencies: canvas.js - For initialization of canvas elements |
|-----------------------------------------------------------------------------|
| 2005-12-27 | Work started. |
| 2005-12-29 | First version posted. |
| 2006-01-03 | Fixed bug in moveTo and lineTo, arguments where not converted |
| | to int which could cause IE to enter an endless loop. Disabled |
| | antalias for fillRect to better comply with the Mozilla, Opera |
| | and possibly Safari implementations where using fillRect is |
| | about the only way to raw non antialiased lines. |
|-----------------------------------------------------------------------------|
| Created 2005-12-27 | All changes are in the log above. | Updated 2006-01-03 |
\----------------------------------------------------------------------------*/
<public:component>
<public:method name="getContext" />
<public:attach event="oncontentready" onevent="initCanvas()"/>
</public:component>
<script language="JScript">
function getContext() {
return element.context;
}
function initCanvas() {
element.context = new IECanvasContext();
element.style.position = 'relative';
element.style.display = 'block';
element.style.overflow = 'hidden';
}
function IECanvasContext() {
this.fillStyle = 'black';
this.globalAlpha = 1.0;
this.globalCompositeOperation = '';
this.lineCap = '';
this.lineJoin = '';
this.lineWidth = '0';
this.miterLimit = '';
this.shadowBlur = '';
this.shadowColor = '';
this.shadowOffsetX = '';
this.shadowOffsetY = '';
this.strokeStyle = 'black';
this._path = '';
this._stateStack = new Array();
this._offsetX = 0;
this._offsetY = 0;
this._rotation = 0;
};
IECanvasContext.prototype.save = function() {
var o;
o = new Object();
this._copyState(this, o);
this._stateStack.push(o);
};
IECanvasContext.prototype.restore = function() {
var o, n;
n = this._stateStack.length - 1;
if (n < 0) { return; }
o = this._stateStack[n];
this._copyState(o, this);
this._stateStack.splice(n, 1);
};
IECanvasContext.prototype._copyState = function(oFrom, oTo) {
oTo.fillStyle = oFrom.fillStyle;
oTo.lineCap = oFrom.lineCap;
oTo.lineJoin = oFrom.lineJoin;
oTo.lineWidth = oFrom.lineWidth;
oTo.miterLimit = oFrom.miterLimit;
oTo.shadowBlur = oFrom.shadowBlur;
oTo.shadowColor = oFrom.shadowColor;
oTo.shadowOffsetX = oFrom.shadowOffsetX;
oTo.shadowOffsetY = oFrom.shadowOffsetY;
oTo._offsetX = oFrom._offsetX;
oTo._offsetY = oFrom._offsetY;
oTo._rotation = oFrom._rotation;
};
IECanvasContext.prototype.rotate = function(r) {
var MAX = Math.PI * 2;
this._rotation += r;
while (this._rotation > MAX) { this._rotation = MAX - this._rotation; }
};
IECanvasContext.prototype.scale = function() { };
IECanvasContext.prototype.translate = function(x, y) {
this._offsetX += x;
this._offsetY += y;
};
IECanvasContext.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
if (this._path) { this._path += ' '; }
this._path += 'qb' + cp1x + ',' + cp1y + ',' + cp2x + ',' + cp2y + ',' + x + ',' + y;
};
IECanvasContext.prototype.clip = function() { };
IECanvasContext.prototype.beginPath = function() {
this._path = '';
};
IECanvasContext.prototype.closePath = function() {
if (this._path) { this._path += ' '; }
this._path += 'x';
};
IECanvasContext.prototype.lineTo = function(x, y) {
if (this._path) { this._path += ' '; }
this._path += 'l' + parseInt(x) + ',' + parseInt(y);
};
IECanvasContext.prototype.moveTo = function(x, y) {
if (this._path) { this._path += ' '; }
this._path += 'm' + parseInt(x) + ',' + parseInt(y);
};
IECanvasContext.prototype.stroke = function() {
var o, s, cosa, sina, cx, cy, x, y;
if (!this._path) { return; }
this._path += ' e';
o = element.ownerDocument.createElement('v:shape');
o.fillColor = 'none';
o.filled = false;
o.strokeColor = this.strokeStyle;
o.stroked = true;
o.weight = this.lineWidth;
o.coordsize = element.offsetWidth + ',' + element.offsetHeight;
o.style.position = 'absolute';
o.style.left = this._offsetX;
o.style.top = this._offsetY;
o.style.width = element.offsetWidth;
o.style.height = element.offsetHeight;
o.path = this._path;
s = element.ownerDocument.createElement('v:stroke');
s.opacity = this.globalAlpha;
o.appendChild(s);
if (this._rotation) {
r = element.ownerDocument.createElement('v:group');
r.style.position = 'absolute';
r.style.left = 0;
r.style.top = 0;
r.style.width = element.offsetWidth;
r.style.height = element.offsetHeight;
r.coordsize = o.coordsize;
r.style.rotation = Math.round((this._rotation * 180) / Math.PI);
r.style.rotationCenter = '0,0';
r.appendChild(o);
element.appendChild(r);
cosa = Math.cos(this._rotation);
sina = Math.sin(this._rotation);
cx = element.offsetWidth / 2;
cy = element.offsetHeight / 2;
x = ( cx*(1-cosa) + cy*sina);
y = (-cx*sina + cy*(1-cosa));
r.style.left = x * -1;
r.style.top = y * -1;
}
else { element.appendChild(o); }
};
IECanvasContext.prototype.fill = function() {
var o, f, r;
if (!this._path) { return; }
this._path += ' e';
o = element.ownerDocument.createElement('v:shape');
o.fillColor = this.fillStyle;
o.strokeColor = this.strokeStyle;
o.stroked = false;
o.weight = this.lineWidth;
o.coordsize = element.offsetWidth + ',' + element.offsetHeight;
o.style.position = 'absolute';
o.style.left = this._offsetX;
o.style.top = this._offsetY;
o.style.width = element.offsetWidth;
o.style.height = element.offsetHeight;
o.path = this._path;
f = element.ownerDocument.createElement('v:fill');
f.opacity = this.globalAlpha;
o.appendChild(f);
if (this._rotation) {
r = element.ownerDocument.createElement('v:group');
r.style.position = 'absolute';
r.style.left = 0;
r.style.top = 0;
r.style.width = element.offsetWidth;
r.style.height = element.offsetHeight;
r.coordsize = o.coordsize;
r.style.rotation = Math.round((this._rotation * 180) / Math.PI);
r.style.rotationCenter = '0,0';
r.appendChild(o);
element.appendChild(r);
cosa = Math.cos(this._rotation);
sina = Math.sin(this._rotation);
cx = (element.offsetWidth) / 2;
cy = (element.offsetHeight) / 2;
x = ( cx*(1-cosa) + cy*sina);
y = (-cx*sina + cy*(1-cosa));
r.style.left = x * -1;
r.style.top = y * -1;
}
else { element.appendChild(o); }
};
IECanvasContext.prototype.arcTo = function(x1, y1, x2, y2, radius) {
// not implemented in gecko, not implemented here
};
IECanvasContext.prototype.quadraticCurveTo = function(cpx, cpy, x, y) {
if (this._path) { this._path += ' '; }
this._path += 'qb' + cpx + ',' + cpy + ',' + x + ',' + y;
};
IECanvasContext.prototype.arc = function(x, y, radius, startAngle, endAngle, clockwise) {
var xi, yi, x1, y1, x2, y2, x3, y3, x4, y4;
if (this._path) { this._path += ' '; }
xi = parseFloat(x);
yi = parseFloat(y);
x1 = xi - radius;
y1 = yi - radius;
x2 = xi + radius;
y2 = yi + radius;
if (clockwise) {
x3 = xi + (Math.cos(startAngle) * radius);
y3 = yi + (Math.sin(startAngle) * radius);
x4 = xi + (Math.cos(endAngle) * radius);
y4 = yi + (Math.sin(endAngle) * radius);
}
else {
x3 = xi + (Math.cos(endAngle) * radius);
y3 = yi + (Math.sin(endAngle) * radius);
x4 = xi + (Math.cos(startAngle) * radius);
y4 = yi + (Math.sin(startAngle) * radius);
}
x3 = Math.round(x3);
y3 = Math.round(y3);
x4 = Math.round(x4);
y4 = Math.round(y4);
this._path += 'ar' + x1 + ',' + y1 + ',' + x2 + ',' + y2 + ',' + x3 + ',' + y3 + ',' + x4 + ',' + y4;
};
IECanvasContext.prototype.rect = function(x, y, w, h) {
var x1, y1, x2, y2;
x2 = x + w;
y2 = y + h;
x1 = Math.round(x);
y1 = Math.round(y);
x2 = Math.round(x2);
y2 = Math.round(y2);
this._path += 'm' + x1 + ',' + y1;
this._path += ' l' + x2 + ',' + y1;
this._path += ' l' + x2 + ',' + y2;
this._path += ' l' + x1 + ',' + y2;
this._path += ' x'
};
IECanvasContext.prototype.strokeRect = function(x, y, w, h) {
var o, s;
o = element.ownerDocument.createElement('v:rect');
o.fillColor = 'none';
o.filled = false;
o.strokeColor = this.strokeStyle;
o.stroked = true;
o.weight = this.lineWidth;
o.style.position = 'absolute';
o.style.left = this._offsetX + x;
o.style.top = this._offsetY + y;
o.style.width = w;
o.style.height = h;
s = element.ownerDocument.createElement('v:fill');
s.opacity = this.globalAlpha;
o.appendChild(s);
element.appendChild(o);
};
IECanvasContext.prototype.clearRect = function(x, y, w, h) { };
IECanvasContext.prototype.fillRect = function(x, y, w, h) {
var o, f;
if ((x == 0) && (y == 0) && (w == element.offsetWidth) && (h == element.offsetHeight) && (this._offsetX == 0) && (this._offsetY == 0) && (this.globalAlpha == 1)) {
while (element.firstChild) { element.removeChild(element.lastChild); }
}
o = element.ownerDocument.createElement('v:rect');
o.fillColor = this.fillStyle;
o.filled = true;
o.stroked = false;
o.weight = 0;
o.style.position = 'absolute';
o.style.left = this._offsetX + x;
o.style.top = this._offsetY + y;
o.style.width = w;
o.style.height = h;
o.style.antialias = 'false';
f = element.ownerDocument.createElement('v:fill');
f.opacity = this.globalAlpha;
o.appendChild(f);
element.appendChild(o);
};
IECanvasContext.prototype.addColorStop = function() { };
IECanvasContext.prototype.createLinearGradient = function() { };
IECanvasContext.prototype.createPattern = function() { };
IECanvasContext.prototype.createRadialGradient = function() { };
IECanvasContext.prototype.drawImage = function() { };
IECanvasContext.prototype.drawImageFromRect = function() { };
</script>

View File

@ -0,0 +1,55 @@
<html>
<head>
<title>Queues</title>
<c:set var="disableJavaScript" value="true" scope="request"/>
<script src='<c:url value="/js/mochi/MochiKit.js"/>' type="text/javascript"></script>
<script src='<c:url value="/js/plotkit/Base.js"/>' type="text/javascript"></script>
<script src='<c:url value="/js/plotkit/Layout.js"/>' type="text/javascript"></script>
<script src='<c:url value="/js/plotkit/Canvas.js"/>' type="text/javascript"></script>
<script src='<c:url value="/js/plotkit/SweetCanvas.js"/>' type="text/javascript"></script>
</head>
<body>
<script>
function drawGraph() {
var layout = new PlotKit.Layout("bar", {});
layout.addDataset(
"Queue Sizes",
[ <c:forEach items="${requestContext.brokerQuery.queues}" var="row" varStatus="status"> [${status.count},
${row.queueSize}], </c:forEach> ] );
layout.evaluate();
var options = {
"IECanvasHTC": "<c:url value="/js/plotkit/iecanvas.htc"/>",
"colorScheme": PlotKit.Base.palette(PlotKit.Base.baseColors()[0]),
"padding": {left: 0, right: 0, top: 10, bottom: 30},
"xTicks": [
<c:forEach items="${requestContext.brokerQuery.queues}" var="row" varStatus="status"> {v:${status.count}, label:"${row.name}"}, </c:forEach>
],
"drawYAxis": false
};
var canvas = MochiKit.DOM.getElement("graph");
var plotter = new PlotKit.SweetCanvasRenderer(canvas, layout, options);
plotter.render();
}
MochiKit.DOM.addLoadEvent(drawGraph);
</script>
<div><canvas id="graph" height="400" width="760"></canvas></div>
<%---
Other values we can graph...
<td>${row.consumerCount}</td>
<td>${row.enqueueCount}</td>
<td>${row.dequeueCount}</td>
--%>
</body>
</html>

View File

@ -17,6 +17,8 @@
<h2>Queues</h2>
<a href="queueGraph.jsp">Queue Graph</a>
<table id="queues" class="sortable autostripe">
<thead>
<tr>