Path: blob/master/src/jdk.jconsole/share/classes/sun/tools/jconsole/Plotter.java
40948 views
/*1* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.tools.jconsole;2627import java.awt.*;28import java.awt.event.*;29import java.beans.*;30import java.io.*;31import java.lang.reflect.Array;32import java.util.*;3334import javax.accessibility.*;35import javax.swing.*;36import javax.swing.border.*;37import javax.swing.filechooser.*;38import javax.swing.filechooser.FileFilter;394041import com.sun.tools.jconsole.JConsoleContext;4243import static sun.tools.jconsole.Formatter.*;44import static sun.tools.jconsole.ProxyClient.*;4546@SuppressWarnings("serial")47public class Plotter extends JComponent48implements Accessible, ActionListener, PropertyChangeListener {4950public static enum Unit {51NONE, BYTES, PERCENT52}5354static final String[] rangeNames = {55Messages.ONE_MIN,56Messages.FIVE_MIN,57Messages.TEN_MIN,58Messages.THIRTY_MIN,59Messages.ONE_HOUR,60Messages.TWO_HOURS,61Messages.THREE_HOURS,62Messages.SIX_HOURS,63Messages.TWELVE_HOURS,64Messages.ONE_DAY,65Messages.SEVEN_DAYS,66Messages.ONE_MONTH,67Messages.THREE_MONTHS,68Messages.SIX_MONTHS,69Messages.ONE_YEAR,70Messages.ALL71};7273static final int[] rangeValues = {741,755,7610,7730,781 * 60,792 * 60,803 * 60,816 * 60,8212 * 60,831 * 24 * 60,847 * 24 * 60,851 * 31 * 24 * 60,863 * 31 * 24 * 60,876 * 31 * 24 * 60,88366 * 24 * 60,89-190};919293static final long SECOND = 1000;94static final long MINUTE = 60 * SECOND;95static final long HOUR = 60 * MINUTE;96static final long DAY = 24 * HOUR;9798static final Color bgColor = new Color(250, 250, 250);99static final Color defaultColor = Color.blue.darker();100101static final int ARRAY_SIZE_INCREMENT = 4000;102103private static Stroke dashedStroke;104105private TimeStamps times = new TimeStamps();106private ArrayList<Sequence> seqs = new ArrayList<Sequence>();107private JPopupMenu popupMenu;108private JMenu timeRangeMenu;109private JRadioButtonMenuItem[] menuRBs;110private JMenuItem saveAsMI;111private JFileChooser saveFC;112113private int viewRange = -1; // Minutes (value <= 0 means full range)114private Unit unit;115private int decimals;116private double decimalsMultiplier;117private Border border = null;118private Rectangle r = new Rectangle(1, 1, 1, 1);119private Font smallFont = null;120121// Initial margins, may be recalculated as needed122private int topMargin = 10;123private int bottomMargin = 45;124private int leftMargin = 65;125private int rightMargin = 70;126private final boolean displayLegend;127128public Plotter() {129this(Unit.NONE, 0);130}131132public Plotter(Unit unit) {133this(unit, 0);134}135136public Plotter(Unit unit, int decimals) {137this(unit,decimals,true);138}139140// Note: If decimals > 0 then values must be decimally shifted left141// that many places, i.e. multiplied by Math.pow(10.0, decimals).142public Plotter(Unit unit, int decimals, boolean displayLegend) {143this.displayLegend = displayLegend;144setUnit(unit);145setDecimals(decimals);146147enableEvents(AWTEvent.MOUSE_EVENT_MASK);148149addMouseListener(new MouseAdapter() {150@Override151public void mousePressed(MouseEvent e) {152if (getParent() instanceof PlotterPanel) {153getParent().requestFocusInWindow();154}155}156});157158}159160public void setUnit(Unit unit) {161this.unit = unit;162}163164public void setDecimals(int decimals) {165this.decimals = decimals;166this.decimalsMultiplier = Math.pow(10.0, decimals);167}168169public void createSequence(String key, String name, Color color, boolean isPlotted) {170Sequence seq = getSequence(key);171if (seq == null) {172seq = new Sequence(key);173}174seq.name = name;175seq.color = (color != null) ? color : defaultColor;176seq.isPlotted = isPlotted;177178seqs.add(seq);179}180181public void setUseDashedTransitions(String key, boolean b) {182Sequence seq = getSequence(key);183if (seq != null) {184seq.transitionStroke = b ? getDashedStroke() : null;185}186}187188public void setIsPlotted(String key, boolean isPlotted) {189Sequence seq = getSequence(key);190if (seq != null) {191seq.isPlotted = isPlotted;192}193}194195// Note: If decimals > 0 then values must be decimally shifted left196// that many places, i.e. multiplied by Math.pow(10.0, decimals).197public synchronized void addValues(long time, long... values) {198assert (values.length == seqs.size());199times.add(time);200for (int i = 0; i < values.length; i++) {201seqs.get(i).add(values[i]);202}203repaint();204}205206private Sequence getSequence(String key) {207for (Sequence seq : seqs) {208if (seq.key.equals(key)) {209return seq;210}211}212return null;213}214215/**216* @return the displayed time range in minutes, or -1 for all data217*/218public int getViewRange() {219return viewRange;220}221222/**223* @param minutes the displayed time range in minutes, or -1 to diaplay all data224*/225public void setViewRange(int minutes) {226if (minutes != viewRange) {227int oldValue = viewRange;228viewRange = minutes;229/* Do not i18n this string */230firePropertyChange("viewRange", oldValue, viewRange);231if (popupMenu != null) {232for (int i = 0; i < menuRBs.length; i++) {233if (rangeValues[i] == viewRange) {234menuRBs[i].setSelected(true);235break;236}237}238}239repaint();240}241}242243@Override244public JPopupMenu getComponentPopupMenu() {245if (popupMenu == null) {246popupMenu = new JPopupMenu(Messages.CHART_COLON);247timeRangeMenu = new JMenu(Messages.PLOTTER_TIME_RANGE_MENU);248timeRangeMenu.setMnemonic(Resources.getMnemonicInt(Messages.PLOTTER_TIME_RANGE_MENU));249popupMenu.add(timeRangeMenu);250menuRBs = new JRadioButtonMenuItem[rangeNames.length];251ButtonGroup rbGroup = new ButtonGroup();252for (int i = 0; i < rangeNames.length; i++) {253menuRBs[i] = new JRadioButtonMenuItem(rangeNames[i]);254rbGroup.add(menuRBs[i]);255menuRBs[i].addActionListener(this);256if (viewRange == rangeValues[i]) {257menuRBs[i].setSelected(true);258}259timeRangeMenu.add(menuRBs[i]);260}261262popupMenu.addSeparator();263264saveAsMI = new JMenuItem(Messages.PLOTTER_SAVE_AS_MENU_ITEM);265saveAsMI.setMnemonic(Resources.getMnemonicInt(Messages.PLOTTER_SAVE_AS_MENU_ITEM));266saveAsMI.addActionListener(this);267popupMenu.add(saveAsMI);268}269return popupMenu;270}271272public void actionPerformed(ActionEvent ev) {273JComponent src = (JComponent)ev.getSource();274if (src == saveAsMI) {275saveAs();276} else {277int index = timeRangeMenu.getPopupMenu().getComponentIndex(src);278setViewRange(rangeValues[index]);279}280}281282private void saveAs() {283if (saveFC == null) {284saveFC = new SaveDataFileChooser();285}286int ret = saveFC.showSaveDialog(this);287if (ret == JFileChooser.APPROVE_OPTION) {288saveDataToFile(saveFC.getSelectedFile());289}290}291292private void saveDataToFile(File file) {293try {294PrintStream out = new PrintStream(new FileOutputStream(file));295296// Print header line297out.print("Time");298for (Sequence seq : seqs) {299out.print(","+seq.name);300}301out.println();302303// Print data lines304if (seqs.size() > 0 && seqs.get(0).size > 0) {305for (int i = 0; i < seqs.get(0).size; i++) {306double excelTime = toExcelTime(times.time(i));307out.print(String.format(Locale.ENGLISH, "%.6f", excelTime));308for (Sequence seq : seqs) {309out.print("," + getFormattedValue(seq.value(i), false));310}311out.println();312}313}314315out.close();316JOptionPane.showMessageDialog(this,317Resources.format(Messages.FILE_CHOOSER_SAVED_FILE,318file.getAbsolutePath(),319file.length()));320} catch (IOException ex) {321String msg = ex.getLocalizedMessage();322String path = file.getAbsolutePath();323if (msg.startsWith(path)) {324msg = msg.substring(path.length()).trim();325}326JOptionPane.showMessageDialog(this,327Resources.format(Messages.FILE_CHOOSER_SAVE_FAILED_MESSAGE,328path,329msg),330Messages.FILE_CHOOSER_SAVE_FAILED_TITLE,331JOptionPane.ERROR_MESSAGE);332}333}334335@Override336public void paintComponent(Graphics g) {337super.paintComponent(g);338339int width = getWidth()-rightMargin-leftMargin-10;340int height = getHeight()-topMargin-bottomMargin;341if (width <= 0 || height <= 0) {342// not enough room to paint anything343return;344}345346Color oldColor = g.getColor();347Font oldFont = g.getFont();348Color fg = getForeground();349Color bg = getBackground();350boolean bgIsLight = (bg.getRed() > 200 &&351bg.getGreen() > 200 &&352bg.getBlue() > 200);353354355((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,356RenderingHints.VALUE_ANTIALIAS_ON);357358if (smallFont == null) {359smallFont = oldFont.deriveFont(9.0F);360}361362r.x = leftMargin - 5;363r.y = topMargin - 8;364r.width = getWidth()-leftMargin-rightMargin;365r.height = getHeight()-topMargin-bottomMargin+16;366367if (border == null) {368// By setting colors here, we avoid recalculating them369// over and over.370border = new BevelBorder(BevelBorder.LOWERED,371getBackground().brighter().brighter(),372getBackground().brighter(),373getBackground().darker().darker(),374getBackground().darker());375}376377border.paintBorder(this, g, r.x, r.y, r.width, r.height);378379// Fill background color380g.setColor(bgColor);381g.fillRect(r.x+2, r.y+2, r.width-4, r.height-4);382g.setColor(oldColor);383384long tMin = Long.MAX_VALUE;385long tMax = Long.MIN_VALUE;386long vMin = Long.MAX_VALUE;387long vMax = 1;388389int w = getWidth()-rightMargin-leftMargin-10;390int h = getHeight()-topMargin-bottomMargin;391392if (times.size > 1) {393tMin = Math.min(tMin, times.time(0));394tMax = Math.max(tMax, times.time(times.size-1));395}396long viewRangeMS;397if (viewRange > 0) {398viewRangeMS = viewRange * MINUTE;399} else {400// Display full time range, but no less than a minute401viewRangeMS = Math.max(tMax - tMin, 1 * MINUTE);402}403404// Calculate min/max values405for (Sequence seq : seqs) {406if (seq.size > 0) {407for (int i = 0; i < seq.size; i++) {408if (seq.size == 1 || times.time(i) >= tMax - viewRangeMS) {409long val = seq.value(i);410if (val > Long.MIN_VALUE) {411vMax = Math.max(vMax, val);412vMin = Math.min(vMin, val);413}414}415}416} else {417vMin = 0L;418}419if (unit == Unit.BYTES || !seq.isPlotted) {420// We'll scale only to the first (main) value set.421// TODO: Use a separate property for this.422break;423}424}425426// Normalize scale427vMax = normalizeMax(vMax);428if (vMin > 0) {429if (vMax / vMin > 4) {430vMin = 0;431} else {432vMin = normalizeMin(vMin);433}434}435436437g.setColor(fg);438439// Axes440// Draw vertical axis441int x = leftMargin - 18;442int y = topMargin;443FontMetrics fm = g.getFontMetrics();444445g.drawLine(x, y, x, y+h);446447int n = 5;448if ((""+vMax).startsWith("2")) {449n = 4;450} else if ((""+vMax).startsWith("3")) {451n = 6;452} else if ((""+vMax).startsWith("4")) {453n = 4;454} else if ((""+vMax).startsWith("6")) {455n = 6;456} else if ((""+vMax).startsWith("7")) {457n = 7;458} else if ((""+vMax).startsWith("8")) {459n = 8;460} else if ((""+vMax).startsWith("9")) {461n = 3;462}463464// Ticks465ArrayList<Long> tickValues = new ArrayList<Long>();466tickValues.add(vMin);467for (int i = 0; i < n; i++) {468long v = i * vMax / n;469if (v > vMin) {470tickValues.add(v);471}472}473tickValues.add(vMax);474n = tickValues.size();475476String[] tickStrings = new String[n];477for (int i = 0; i < n; i++) {478long v = tickValues.get(i);479tickStrings[i] = getSizeString(v, vMax);480}481482// Trim trailing decimal zeroes.483if (decimals > 0) {484boolean trimLast = true;485boolean removedDecimalPoint = false;486do {487for (String str : tickStrings) {488if (!(str.endsWith("0") || str.endsWith("."))) {489trimLast = false;490break;491}492}493if (trimLast) {494if (tickStrings[0].endsWith(".")) {495removedDecimalPoint = true;496}497for (int i = 0; i < n; i++) {498String str = tickStrings[i];499tickStrings[i] = str.substring(0, str.length()-1);500}501}502} while (trimLast && !removedDecimalPoint);503}504505// Draw ticks506int lastY = Integer.MAX_VALUE;507for (int i = 0; i < n; i++) {508long v = tickValues.get(i);509y = topMargin+h-(int)(h * (v-vMin) / (vMax-vMin));510g.drawLine(x-2, y, x+2, y);511String s = tickStrings[i];512if (unit == Unit.PERCENT) {513s += "%";514}515int sx = x-6-fm.stringWidth(s);516if (y < lastY-13) {517if (checkLeftMargin(sx)) {518// Wait for next repaint519return;520}521g.drawString(s, sx, y+4);522}523// Draw horizontal grid line524g.setColor(Color.lightGray);525g.drawLine(r.x + 4, y, r.x + r.width - 4, y);526g.setColor(fg);527lastY = y;528}529530// Draw horizontal axis531x = leftMargin;532y = topMargin + h + 15;533g.drawLine(x, y, x+w, y);534535long t1 = tMax;536if (t1 <= 0L) {537// No data yet, so draw current time538t1 = System.currentTimeMillis();539}540long tz = timeDF.getTimeZone().getOffset(t1);541long tickInterval = calculateTickInterval(w, 40, viewRangeMS);542if (tickInterval > 3 * HOUR) {543tickInterval = calculateTickInterval(w, 80, viewRangeMS);544}545long t0 = tickInterval - (t1 - viewRangeMS + tz) % tickInterval;546while (t0 < viewRangeMS) {547x = leftMargin + (int)(w * t0 / viewRangeMS);548g.drawLine(x, y-2, x, y+2);549550long t = t1 - viewRangeMS + t0;551String str = formatClockTime(t);552g.drawString(str, x, y+16);553//if (tickInterval > (1 * HOUR) && t % (1 * DAY) == 0) {554if ((t + tz) % (1 * DAY) == 0) {555str = formatDate(t);556g.drawString(str, x, y+27);557}558// Draw vertical grid line559g.setColor(Color.lightGray);560g.drawLine(x, topMargin, x, topMargin + h);561g.setColor(fg);562t0 += tickInterval;563}564565// Plot values566int start = 0;567int nValues = 0;568int nLists = seqs.size();569if (nLists > 0) {570nValues = seqs.get(0).size;571}572if (nValues == 0) {573g.setColor(oldColor);574return;575} else {576Sequence seq = seqs.get(0);577// Find starting point578for (int p = 0; p < seq.size; p++) {579if (times.time(p) >= tMax - viewRangeMS) {580start = p;581break;582}583}584}585586//Optimization: collapse plot of more than four values per pixel587int pointsPerPixel = (nValues - start) / w;588if (pointsPerPixel < 4) {589pointsPerPixel = 1;590}591592// Draw graphs593// Loop backwards over sequences because the first needs to be painted on top594for (int i = nLists-1; i >= 0; i--) {595int x0 = leftMargin;596int y0 = topMargin + h + 1;597598Sequence seq = seqs.get(i);599if (seq.isPlotted && seq.size > 0) {600// Paint twice, with white and with color601for (int pass = 0; pass < 2; pass++) {602g.setColor((pass == 0) ? Color.white : seq.color);603int x1 = -1;604long v1 = -1;605for (int p = start; p < nValues; p += pointsPerPixel) {606// Make sure we get the last value607if (pointsPerPixel > 1 && p >= nValues - pointsPerPixel) {608p = nValues - 1;609}610int x2 = (int)(w * (times.time(p)-(t1-viewRangeMS)) / viewRangeMS);611long v2 = seq.value(p);612if (v2 >= vMin && v2 <= vMax) {613int y2 = (int)(h * (v2 -vMin) / (vMax-vMin));614if (x1 >= 0 && v1 >= vMin && v1 <= vMax) {615int y1 = (int)(h * (v1-vMin) / (vMax-vMin));616617if (y1 == y2) {618// fillrect is much faster619g.fillRect(x0+x1, y0-y1-pass, x2-x1, 1);620} else {621Graphics2D g2d = (Graphics2D)g;622Stroke oldStroke = null;623if (seq.transitionStroke != null) {624oldStroke = g2d.getStroke();625g2d.setStroke(seq.transitionStroke);626}627g.drawLine(x0+x1, y0-y1-pass, x0+x2, y0-y2-pass);628if (oldStroke != null) {629g2d.setStroke(oldStroke);630}631}632}633}634x1 = x2;635v1 = v2;636}637}638639// Current value640long v = seq.value(seq.size - 1);641if (v >= vMin && v <= vMax) {642if (bgIsLight) {643g.setColor(seq.color);644} else {645g.setColor(fg);646}647x = r.x + r.width + 2;648y = topMargin+h-(int)(h * (v-vMin) / (vMax-vMin));649// a small triangle/arrow650g.fillPolygon(new int[] { x+2, x+6, x+6 },651new int[] { y, y+3, y-3 },6523);653}654g.setColor(fg);655}656}657658int[] valueStringSlots = new int[nLists];659for (int i = 0; i < nLists; i++) valueStringSlots[i] = -1;660for (int i = 0; i < nLists; i++) {661Sequence seq = seqs.get(i);662if (seq.isPlotted && seq.size > 0) {663// Draw current value664665// TODO: collapse values if pointsPerPixel >= 4666667long v = seq.value(seq.size - 1);668if (v >= vMin && v <= vMax) {669x = r.x + r.width + 2;670y = topMargin+h-(int)(h * (v-vMin) / (vMax-vMin));671int y2 = getValueStringSlot(valueStringSlots, y, 2*10, i);672g.setFont(smallFont);673if (bgIsLight) {674g.setColor(seq.color);675} else {676g.setColor(fg);677}678String curValue = getFormattedValue(v, true);679if (unit == Unit.PERCENT) {680curValue += "%";681}682int valWidth = fm.stringWidth(curValue);683String legend = (displayLegend?seq.name:"");684int legendWidth = fm.stringWidth(legend);685if (checkRightMargin(valWidth) || checkRightMargin(legendWidth)) {686// Wait for next repaint687return;688}689g.drawString(legend , x + 17, Math.min(topMargin+h, y2 + 3 - 10));690g.drawString(curValue, x + 17, Math.min(topMargin+h + 10, y2 + 3));691692// Maybe draw a short line to value693if (y2 > y + 3) {694g.drawLine(x + 9, y + 2, x + 14, y2);695} else if (y2 < y - 3) {696g.drawLine(x + 9, y - 2, x + 14, y2);697}698}699g.setFont(oldFont);700g.setColor(fg);701702}703}704g.setColor(oldColor);705}706707private boolean checkLeftMargin(int x) {708// Make sure leftMargin has at least 2 pixels over709if (x < 2) {710leftMargin += (2 - x);711// Repaint from top (above any cell renderers)712SwingUtilities.getWindowAncestor(this).repaint();713return true;714}715return false;716}717718private boolean checkRightMargin(int w) {719// Make sure rightMargin has at least 2 pixels over720if (w + 2 > rightMargin) {721rightMargin = (w + 2);722// Repaint from top (above any cell renderers)723SwingUtilities.getWindowAncestor(this).repaint();724return true;725}726return false;727}728729private int getValueStringSlot(int[] slots, int y, int h, int i) {730for (int s = 0; s < slots.length; s++) {731if (slots[s] >= y && slots[s] < y + h) {732// collide below us733if (slots[s] > h) {734return getValueStringSlot(slots, slots[s]-h, h, i);735} else {736return getValueStringSlot(slots, slots[s]+h, h, i);737}738} else if (y >= h && slots[s] > y - h && slots[s] < y) {739// collide above us740return getValueStringSlot(slots, slots[s]+h, h, i);741}742}743slots[i] = y;744return y;745}746747private long calculateTickInterval(int w, int hGap, long viewRangeMS) {748long tickInterval = viewRangeMS * hGap / w;749if (tickInterval < 1 * MINUTE) {750tickInterval = 1 * MINUTE;751} else if (tickInterval < 5 * MINUTE) {752tickInterval = 5 * MINUTE;753} else if (tickInterval < 10 * MINUTE) {754tickInterval = 10 * MINUTE;755} else if (tickInterval < 30 * MINUTE) {756tickInterval = 30 * MINUTE;757} else if (tickInterval < 1 * HOUR) {758tickInterval = 1 * HOUR;759} else if (tickInterval < 3 * HOUR) {760tickInterval = 3 * HOUR;761} else if (tickInterval < 6 * HOUR) {762tickInterval = 6 * HOUR;763} else if (tickInterval < 12 * HOUR) {764tickInterval = 12 * HOUR;765} else if (tickInterval < 1 * DAY) {766tickInterval = 1 * DAY;767} else {768tickInterval = normalizeMax(tickInterval / DAY) * DAY;769}770return tickInterval;771}772773private long normalizeMin(long l) {774int exp = (int)Math.log10((double)l);775long multiple = (long)Math.pow(10.0, exp);776int i = (int)(l / multiple);777return i * multiple;778}779780private long normalizeMax(long l) {781int exp = (int)Math.log10((double)l);782long multiple = (long)Math.pow(10.0, exp);783int i = (int)(l / multiple);784l = (i+1)*multiple;785return l;786}787788private String getFormattedValue(long v, boolean groupDigits) {789String str;790String fmt = "%";791if (groupDigits) {792fmt += ",";793}794if (decimals > 0) {795fmt += "." + decimals + "f";796str = String.format(fmt, v / decimalsMultiplier);797} else {798fmt += "d";799str = String.format(fmt, v);800}801return str;802}803804private String getSizeString(long v, long vMax) {805String s;806807if (unit == Unit.BYTES && decimals == 0) {808s = formatBytes(v, vMax);809} else {810s = getFormattedValue(v, true);811}812return s;813}814815private static synchronized Stroke getDashedStroke() {816if (dashedStroke == null) {817dashedStroke = new BasicStroke(1.0f,818BasicStroke.CAP_BUTT,819BasicStroke.JOIN_MITER,82010.0f,821new float[] { 2.0f, 3.0f },8220.0f);823}824return dashedStroke;825}826827private static Object extendArray(Object a1) {828int n = Array.getLength(a1);829Object a2 =830Array.newInstance(a1.getClass().getComponentType(),831n + ARRAY_SIZE_INCREMENT);832System.arraycopy(a1, 0, a2, 0, n);833return a2;834}835836837private static class TimeStamps {838// Time stamps (long) are split into offsets (long) and a839// series of times from the offsets (int). A new offset is840// stored when the time value doesn't fit in an int841// (approx every 24 days). An array of indices is used to842// define the starting point for each offset in the times843// array.844long[] offsets = new long[0];845int[] indices = new int[0];846int[] rtimes = new int[ARRAY_SIZE_INCREMENT];847848// Number of stored timestamps849int size = 0;850851/**852* Returns the time stamp for index i853*/854public long time(int i) {855long offset = 0;856for (int j = indices.length - 1; j >= 0; j--) {857if (i >= indices[j]) {858offset = offsets[j];859break;860}861}862return offset + rtimes[i];863}864865public void add(long time) {866// May need to store a new time offset867int n = offsets.length;868if (n == 0 || time - offsets[n - 1] > Integer.MAX_VALUE) {869// Grow offset and indices arrays and store new offset870offsets = Arrays.copyOf(offsets, n + 1);871offsets[n] = time;872indices = Arrays.copyOf(indices, n + 1);873indices[n] = size;874}875876// May need to extend the array size877if (rtimes.length == size) {878rtimes = (int[])extendArray(rtimes);879}880881// Store the time882rtimes[size] = (int)(time - offsets[offsets.length - 1]);883size++;884}885}886887private static class Sequence {888String key;889String name;890Color color;891boolean isPlotted;892Stroke transitionStroke = null;893894// Values are stored in an int[] if all values will fit,895// otherwise in a long[]. An int can represent up to 2 GB.896// Use a random start size, so all arrays won't need to897// be grown during the same update interval898Object values =899new byte[ARRAY_SIZE_INCREMENT + (int)(Math.random() * 100)];900901// Number of stored values902int size = 0;903904public Sequence(String key) {905this.key = key;906}907908/**909* Returns the value at index i910*/911public long value(int i) {912return Array.getLong(values, i);913}914915public void add(long value) {916// May need to switch to a larger array type917if ((values instanceof byte[] ||918values instanceof short[] ||919values instanceof int[]) &&920value > Integer.MAX_VALUE) {921long[] la = new long[Array.getLength(values)];922for (int i = 0; i < size; i++) {923la[i] = Array.getLong(values, i);924}925values = la;926} else if ((values instanceof byte[] ||927values instanceof short[]) &&928value > Short.MAX_VALUE) {929int[] ia = new int[Array.getLength(values)];930for (int i = 0; i < size; i++) {931ia[i] = Array.getInt(values, i);932}933values = ia;934} else if (values instanceof byte[] &&935value > Byte.MAX_VALUE) {936short[] sa = new short[Array.getLength(values)];937for (int i = 0; i < size; i++) {938sa[i] = Array.getShort(values, i);939}940values = sa;941}942943// May need to extend the array size944if (Array.getLength(values) == size) {945values = extendArray(values);946}947948// Store the value949if (values instanceof long[]) {950((long[])values)[size] = value;951} else if (values instanceof int[]) {952((int[])values)[size] = (int)value;953} else if (values instanceof short[]) {954((short[])values)[size] = (short)value;955} else {956((byte[])values)[size] = (byte)value;957}958size++;959}960}961962// Can be overridden by subclasses963long getValue() {964return 0;965}966967long getLastTimeStamp() {968return times.time(times.size - 1);969}970971long getLastValue(String key) {972Sequence seq = getSequence(key);973return (seq != null && seq.size > 0) ? seq.value(seq.size - 1) : 0L;974}975976977// Called on EDT978public void propertyChange(PropertyChangeEvent ev) {979String prop = ev.getPropertyName();980981if (prop == JConsoleContext.CONNECTION_STATE_PROPERTY) {982ConnectionState newState = (ConnectionState)ev.getNewValue();983984switch (newState) {985case DISCONNECTED:986synchronized(this) {987long time = System.currentTimeMillis();988times.add(time);989for (Sequence seq : seqs) {990seq.add(Long.MIN_VALUE);991}992}993break;994}995}996}997998private static class SaveDataFileChooser extends JFileChooser {999private static final long serialVersionUID = -5182890922369369669L;1000SaveDataFileChooser() {1001setFileFilter(new FileNameExtensionFilter("CSV file", "csv"));1002}10031004@Override1005public void approveSelection() {1006File file = getSelectedFile();1007if (file != null) {1008FileFilter filter = getFileFilter();1009if (filter != null && filter instanceof FileNameExtensionFilter) {1010String[] extensions =1011((FileNameExtensionFilter)filter).getExtensions();10121013boolean goodExt = false;1014for (String ext : extensions) {1015if (file.getName().toLowerCase().endsWith("." + ext.toLowerCase())) {1016goodExt = true;1017break;1018}1019}1020if (!goodExt) {1021file = new File(file.getParent(),1022file.getName() + "." + extensions[0]);1023}1024}10251026if (file.exists()) {1027String okStr = Messages.FILE_CHOOSER_FILE_EXISTS_OK_OPTION;1028String cancelStr = Messages.FILE_CHOOSER_FILE_EXISTS_CANCEL_OPTION;1029int ret =1030JOptionPane.showOptionDialog(this,1031Resources.format(Messages.FILE_CHOOSER_FILE_EXISTS_MESSAGE,1032file.getName()),1033Messages.FILE_CHOOSER_FILE_EXISTS_TITLE,1034JOptionPane.OK_CANCEL_OPTION,1035JOptionPane.WARNING_MESSAGE,1036null,1037new Object[] { okStr, cancelStr },1038okStr);1039if (ret != JOptionPane.OK_OPTION) {1040return;1041}1042}1043setSelectedFile(file);1044}1045super.approveSelection();1046}1047}10481049@Override1050public AccessibleContext getAccessibleContext() {1051if (accessibleContext == null) {1052accessibleContext = new AccessiblePlotter();1053}1054return accessibleContext;1055}10561057protected class AccessiblePlotter extends AccessibleJComponent {1058private static final long serialVersionUID = -3847205410473510922L;1059protected AccessiblePlotter() {1060setAccessibleName(Messages.PLOTTER_ACCESSIBLE_NAME);1061}10621063@Override1064public String getAccessibleName() {1065String name = super.getAccessibleName();10661067if (seqs.size() > 0 && seqs.get(0).size > 0) {1068String keyValueList = "";1069for (Sequence seq : seqs) {1070if (seq.isPlotted) {1071String value = "null";1072if (seq.size > 0) {1073if (unit == Unit.BYTES) {1074value = Resources.format(Messages.SIZE_BYTES, seq.value(seq.size - 1));1075} else {1076value =1077getFormattedValue(seq.value(seq.size - 1), false) +1078((unit == Unit.PERCENT) ? "%" : "");1079}1080}1081// Assume format string ends with newline1082keyValueList +=1083Resources.format(Messages.PLOTTER_ACCESSIBLE_NAME_KEY_AND_VALUE,1084seq.key, value);1085}1086}1087name += "\n" + keyValueList + ".";1088} else {1089name += "\n" + Messages.PLOTTER_ACCESSIBLE_NAME_NO_DATA;1090}1091return name;1092}10931094@Override1095public AccessibleRole getAccessibleRole() {1096return AccessibleRole.CANVAS;1097}1098}1099}110011011102