001
002 /*****************************************************************************
003 *
004 * jBudget.
005 * Copyright (C) 2006 Dmitri Petrov
006 *
007 * This program is free software: you can redistribute it and/or modify
008 * it under the terms of the GNU General Public License as published by
009 * the Free Software Foundation, either version 3 of the License, or
010 * (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with this program. If not, see <http://www.gnu.org/licenses/>.
019 *
020 */
021
022 /*
023 * DatesInfoTable.java
024 *
025 * Created on July 26, 2006, 6:09 PM
026 */
027
028 package org.jbudget.gui.month;
029
030 import java.awt.Color;
031 import java.awt.Font;
032 import java.awt.FontMetrics;
033 import java.awt.Graphics;
034 import java.awt.event.ActionEvent;
035 import java.awt.event.ActionListener;
036 import java.util.ArrayList;
037 import java.util.HashMap;
038 import java.util.List;
039 import java.util.Map;
040 import java.util.Set;
041 import javax.swing.JTable;
042 import javax.swing.UIManager;
043 import javax.swing.event.TableColumnModelEvent;
044 import javax.swing.event.TableModelEvent;
045 import javax.swing.table.TableCellRenderer;
046 import javax.swing.table.TableColumn;
047 import javax.swing.table.TableColumnModel;
048 import javax.swing.table.TableModel;
049 import org.jbudget.gui.GuiPreferences;
050 import org.jdom.Attribute;
051 import org.jdom.Element;
052 import org.jdom.JDOMException;
053 import org.jbudget.Core.Account;
054 import org.jbudget.Core.Budget;
055 import org.jbudget.Core.ExpenseCategory;
056 import org.jbudget.Core.MoneyPit;
057 import org.jbudget.gui.month.DatesInfoTableModel.CellData;
058 import org.jbudget.gui.month.renderers.DateInfoCellRendererActBal;
059 import org.jbudget.gui.month.renderers.DateInfoCellRendererActivity;
060 import org.jbudget.gui.month.renderers.DateInfoCellRendererBalance;
061 import org.jbudget.gui.month.renderers.DateInfoCellRendererBase;
062 import org.jbudget.gui.month.renderers.DateInfoCellRendererFull;
063 import org.jbudget.util.ActionSignaler;
064 import org.jbudget.util.ColorParser;
065 import org.jbudget.util.CurrencyFormater;
066 import org.jbudget.util.Pair;
067
068 /**
069 * A JTable specialized for displaying amounts.
070 * Automatically adjusts column widths to accommodate the contents.
071 *
072 * @author petrov
073 */
074 public class DatesInfoTable extends JTable
075 {
076 /** Rendering state. */
077 private RenderingState renderingState;
078
079 /** Column colors */
080 private Colors colors = new Colors();
081
082 /** List of size objects for computing column widths. */
083 private final List<ColumnFieldWidths> widths =
084 new ArrayList<ColumnFieldWidths>();
085
086 /** A helper object that displays tool tips for the column headers. */
087 private final ToolTipManager toolTipManager = new ToolTipManager();
088
089 public final ActionListener stateWatcher = new ActionListener()
090 {
091 public void actionPerformed(ActionEvent ev)
092 {
093 DatesInfoTable.this.initialize();
094 DatesInfoTable.this.repaint();
095 }
096 };
097
098 /** Minimum width of a column. */
099 private final int minColumnWidth = 100;
100
101 /** Set to true when the constructor is done. */
102 boolean initialized = false;
103
104 //========================================================================//
105
106
107 //========================================================================//
108
109
110 /** Creates a new instance of DatesInfoTable */
111 public DatesInfoTable(DatesInfoTableModel tableModel,
112 RenderingState renderingState)
113 {
114 super();
115 setAutoCreateColumnsFromModel(false);
116 setColumnModel(new org.jbudget.gui.month.TableColumnModel());
117 setModel(tableModel);
118 getTableHeader().addMouseMotionListener(toolTipManager);
119 setTooltips();
120 this.renderingState = renderingState;
121 renderingState.addActionListener(stateWatcher);
122 initialized = true;
123 }
124
125 public void dispose()
126 {
127 renderingState.removeActionListener(stateWatcher);
128 }
129
130 @Override
131 public void updateUI()
132 {
133 setFont(UIManager.getFont(GuiPreferences.tableFontKey));
134 setBackground(UIManager.getColor(GuiPreferences.tableBgKey));
135 setForeground(UIManager.getColor(GuiPreferences.tableFgKey));
136 setSelectionBackground(
137 UIManager.getColor(GuiPreferences.tableSelectionBgKey));
138 setSelectionForeground(
139 UIManager.getColor(GuiPreferences.tableSelectionFgKey));
140
141 tableHeader.setFont(
142 UIManager.getFont(GuiPreferences.tableFontKey).deriveFont(Font.BOLD));
143
144 super.updateUI();
145 }
146
147 // ======================= Rendering State & colors ======================//
148
149 public RenderingState getRendereingState()
150 {
151 return renderingState;
152 }
153
154 public void setRenderingState(RenderingState renderingState)
155 {
156 this.renderingState = renderingState;
157 renderingState.addActionListener(stateWatcher);
158 }
159
160 public Colors getColumnColors()
161 {
162 return colors;
163 }
164
165 public void setColumnColors(Colors colors)
166 {
167 this.colors = colors;
168 colors.addActionListener(stateWatcher);
169 initialize();
170 }
171
172 //======================= Initializations ================================//
173
174 /** initializes the table */
175 private void initialize()
176 {
177 if (!initialized || widths == null)
178 return;
179 else
180 widths.clear();
181
182 int nColumns = Math.min(getModel().getColumnCount(),
183 getColumnModel().getColumnCount());
184
185 for (int columnIndex = 0; columnIndex < nColumns; columnIndex++)
186 {
187 RenderingType renderingType = renderingState.getRenderingType();
188 HighlightingType highlightingType = renderingState.getHighlightingType();
189
190 ColumnFieldWidths w = getWidths(columnIndex);
191 widths.add(w);
192
193 TableColumn column = getColumnModel().getColumn(columnIndex);
194
195 DateInfoCellRendererBase renderer;
196 int width;
197
198 if (renderingType == RenderingType.DETAILED)
199 {
200 renderer = new DateInfoCellRendererFull(
201 w.inWidth, w.outWidth, w.balanceWidth,
202 renderingState.getHighlightingType());
203 width = w.detailedWidth;
204 }
205 else if (renderingType == RenderingType.ACTIVITY)
206 {
207 renderer = new DateInfoCellRendererActivity(
208 renderingState.getHighlightingType());
209 width = w.activityWidth;
210 }
211 else if (renderingType == RenderingType.BALANCE)
212 {
213 renderer = new DateInfoCellRendererBalance(
214 renderingState.getHighlightingType());
215 width = w.balanceWidth;
216 }
217 else if (renderingType == RenderingType.ACTIVITY_BALANCE)
218 {
219 renderer = new DateInfoCellRendererActBal(w.activityWidth, w.balanceWidth,
220 renderingState.getHighlightingType());
221 width = w.activityWidth + w.balanceWidth;
222 }
223 else
224 return;
225
226 TableCellRenderer oldRenderer = column.getCellRenderer();
227 column.setCellRenderer(renderer);
228
229 if (width > minColumnWidth)
230 column.setPreferredWidth(width);
231 else
232 column.setPreferredWidth(minColumnWidth);
233 }
234
235 //Now setting up the background.
236 setupBackgroundPainter();
237 }
238
239 private void setupBackgroundPainter()
240 {
241 int nColumns = Math.min(getColumnModel().getColumnCount(),
242 getModel().getColumnCount());
243
244 BackgroundType backgroundType = renderingState.getBackgroundType();
245
246 if (backgroundType.isStructureOFF())
247 {
248 if (backgroundType.isPlain())
249 {
250 for (int columnIndex = 0; columnIndex < nColumns; columnIndex++)
251 {
252 TableColumn column = getColumnModel().getColumn(columnIndex);
253 DateInfoCellRendererBase renderer =
254 (DateInfoCellRendererBase)column.getCellRenderer();
255 renderer.setPainter(renderer.new PlainPainter());
256 }
257 }
258 else if (backgroundType.isStriped())
259 {
260 for (int columnIndex = 0; columnIndex < nColumns; columnIndex++)
261 {
262 TableColumn column = getColumnModel().getColumn(columnIndex);
263 DateInfoCellRendererBase renderer =
264 (DateInfoCellRendererBase)column.getCellRenderer();
265 renderer.setPainter(renderer.new StripedPainter());
266 }
267 }
268 return;
269 }
270
271 ColorStructure colorStructure = getColorStructure();
272
273 for (int columnIndex = 0; columnIndex < nColumns; columnIndex++)
274 {
275 TableColumn column = getColumnModel().getColumn(columnIndex);
276 DateInfoCellRendererBase renderer =
277 (DateInfoCellRendererBase)column.getCellRenderer();
278 List<Color> myColors = colorStructure.colorLists.get(columnIndex);
279
280 if (myColors == null)
281 {
282 if (backgroundType.isPlain())
283 renderer.setPainter(renderer.new PlainPainter());
284 else if (backgroundType.isStriped())
285 renderer.setPainter(renderer.new StripedPainter());
286
287 continue;
288 }
289
290 if (backgroundType.isStructureSimple())
291 {
292 renderer.setPainter(renderer.new FixedColorPainter(myColors.get(0)));
293 continue;
294 }
295
296 if (!backgroundType.isStructureFull())
297 {
298 if (backgroundType.isPlain())
299 renderer.setPainter(renderer.new PlainPainter());
300 else if (backgroundType.isStriped())
301 renderer.setPainter(renderer.new StripedPainter());
302
303 continue;
304 }
305
306 // Now we have to deal with the STRUCTURE_FULL background painter.
307 int left = 0;
308 int right = 0;
309 int nColors = myColors.size();
310 if (columnIndex == 0)
311 left = nColors;
312 else
313 left = nColors - colorStructure.nShared.get(columnIndex-1).intValue();
314 if (columnIndex == nColumns - 1)
315 right = nColors;
316 else
317 right = nColors - colorStructure.nShared.get(columnIndex).intValue();
318
319 if (left < nColors )
320 left ++;
321 if (right < nColors)
322 right ++;
323
324 renderer.setPainter(renderer.new StructurePainter(myColors, left, right));
325 }
326 }
327
328 /** Returns the ColorStructure object corresponding to the current state
329 * of the TableModel and the Color object used by this table.
330 */
331 private ColorStructure getColorStructure()
332 {
333 DatesInfoTableModel model = (DatesInfoTableModel)getModel();
334 int nColumns = Math.min(getColumnModel().getColumnCount(),
335 getModel().getColumnCount());
336 ColorStructure colorStructure = new ColorStructure(nColumns);
337
338 // First let's create a category structure corresponding to each column.
339 // We do not care about columns that do not contain ExpenseCategories
340 // since those are simple. For accounts, we will just assign a color
341 // right away. Anthing else we shall ignore.
342 List<List<ExpenseCategory>> categoriesList =
343 new ArrayList<List<ExpenseCategory>>(nColumns);
344 for (int columnIndex = 0; columnIndex < nColumns; columnIndex ++)
345 {
346
347 MoneyPit topElement = model.getItemsForColumn(columnIndex).get(0);
348 if (topElement.getType() == MoneyPit.Type.ACCOUNT &&
349 model.getState().getExpandAccounts())
350 {
351 Color color = colors.getColor(topElement.getAccount());
352 if (color != null)
353 {
354 List<Color> cl = new ArrayList<Color>(1);
355 cl.add(color);
356 colorStructure.colorLists.set(columnIndex, cl);
357 }
358 categoriesList.add(null);
359 }
360 else if (topElement.getType() == MoneyPit.Type.EXPENSE &&
361 model.getState().getExpandCategories())
362 {
363
364 Budget budget = model.getMonth().getBudget();
365
366 ExpenseCategory category = topElement.getExpenseCategory();
367 List<ExpenseCategory> currentCategories = budget.getAnsestors(category);
368 currentCategories.add(category);
369 categoriesList.add(currentCategories);
370 }
371 else
372 categoriesList.add(null);
373 }
374
375 // Now set up color list for the columns corresponding to expense categories.
376 int columnIndex = -1;
377 for (List<ExpenseCategory> catList : categoriesList)
378 {
379 columnIndex++;
380 if (catList == null)
381 continue;
382
383 List<Color>colorsLst = new ArrayList<Color>(catList.size());
384 for (ExpenseCategory cat : catList)
385 {
386 Color newColor = colors.getColor(cat);
387 if (newColor != null)
388 colorsLst.add(newColor);
389 }
390 if (!colorsLst.isEmpty())
391 colorStructure.colorLists.set(columnIndex,colorsLst);
392 }
393
394 //Now setup the numbers of colors shared between categories.
395 for (columnIndex = 0; columnIndex < nColumns - 1; columnIndex ++)
396 {
397 List<ExpenseCategory> thisCats = categoriesList.get(columnIndex);
398 List<ExpenseCategory> nextCats = categoriesList.get(columnIndex + 1);
399
400 if (thisCats == null || nextCats == null)
401 continue; //Leave the value at zero
402
403 //Figure out the number of shared categories.
404 int n = 0;
405 int count = 0;
406 while (n < thisCats.size() && n < nextCats.size() &&
407 thisCats.get(n) == nextCats.get(n))
408 {
409 if (colors.getColor(thisCats.get(n)) != null)
410 count ++;
411 n++;
412 }
413 colorStructure.nShared.set(columnIndex, new Integer(count));
414 }
415
416 return colorStructure;
417 }
418
419 /** Creates a column widths object for a given column */
420 private ColumnFieldWidths getWidths(int columnIndex)
421 {
422 FontMetrics metrics = getFontMetrics(getFont());
423 ColumnFieldWidths width = new ColumnFieldWidths();
424
425 long maxIn = 0L;
426 long maxOut = 0L;
427 long maxActivity = 0L;
428 long maxBalance = 0L;
429
430 for (int rowIndex = 0, nRows = dataModel.getRowCount();
431 rowIndex < nRows; rowIndex ++)
432 {
433 CellData data = (CellData)dataModel.getValueAt(rowIndex, columnIndex);
434
435 long in, out;
436 if (data.type == MoneyPit.Type.EXPENSE)
437 {
438 in = data.allocatedAmount + data.outAmount;
439 out = data.inAmount;
440 }
441 else
442 {
443 in = data.inAmount;
444 out = data.outAmount;
445 }
446
447 long tmp = Math.abs(in);
448 if (maxIn < tmp)
449 maxIn = tmp;
450
451 tmp = Math.abs(out);
452 if (maxOut < tmp)
453 maxIn = tmp;
454
455 long activity = in - out;
456 long balance = data.balance;
457
458 tmp = Math.abs(activity);
459 if (maxActivity < tmp)
460 maxActivity = tmp;
461
462 tmp = Math.abs(balance);
463 if (maxBalance < tmp)
464 maxBalance = tmp;
465 }
466
467 width.inWidth =
468 (int)(metrics.stringWidth(CurrencyFormater.format(-maxIn))* 1.2);
469 width.outWidth =
470 (int)(metrics.stringWidth(CurrencyFormater.format(-maxOut))* 1.2);
471 width.activityWidth =
472 (int)(metrics.stringWidth(CurrencyFormater.format(maxActivity))* 1.2);
473 width.balanceWidth =
474 (int)(metrics.stringWidth(CurrencyFormater.format(maxBalance))* 1.2);
475
476 width.inWidth += ColumnFieldWidths.padding;
477 width.outWidth += ColumnFieldWidths.padding;
478 width.activityWidth += ColumnFieldWidths.padding;
479 width.balanceWidth += ColumnFieldWidths.padding;
480
481 width.detailedWidth = width.inWidth + width.outWidth + width.balanceWidth;
482 if (width.detailedWidth > ColumnFieldWidths.maxTotalWidth)
483 {
484 width.balanceWidth -= width.detailedWidth -
485 ColumnFieldWidths.maxTotalWidth;
486 width.detailedWidth = ColumnFieldWidths.maxTotalWidth;
487 if (width.balanceWidth < 0)
488 {
489 width.balanceWidth = width.detailedWidth/3;
490 width.inWidth = width.detailedWidth/3;
491 width.outWidth = width.detailedWidth/3;
492 }
493 }
494
495 return width;
496 }
497
498 public void updateColumnWidths()
499 {
500 validate();
501 }
502
503 public void setTooltips()
504 {
505 if ( !(getModel() instanceof DatesInfoTableModel) )
506 return;
507
508 DatesInfoTableModel tableModel = (DatesInfoTableModel)getModel();
509 TableColumnModel myColumnModel = getColumnModel();
510
511 // Make sure that table model and tooltip manager exist.
512 if (tableModel == null || toolTipManager == null ||
513 tableModel.getColumnCount() != myColumnModel.getColumnCount())
514 {
515 return;
516 }
517
518 for (int i = 0, nColumns = myColumnModel.getColumnCount(); i < nColumns; i++)
519 toolTipManager.setToolTip(i, tableModel.getColumnToolTip(i));
520 toolTipManager.update(this);
521 }
522
523 // ======= Owerriding stuff from java.awt.Component =================//
524
525
526 @Override
527 public void validate()
528 {
529 initialize();
530 super.validate();
531 }
532
533
534 @Override
535 public void paintComponent(Graphics g)
536 {
537 super.paintComponent(g);
538 }
539
540 //=========== Overriding javax.swing.JTable =========================//
541
542
543 @Override
544 public void tableChanged(TableModelEvent ev)
545 {
546 super.tableChanged(ev);
547
548 if ( ev.getFirstRow() == TableModelEvent.HEADER_ROW )
549 {
550 TableColumnModel model = getColumnModel();
551 int nColumns = model.getColumnCount();
552
553 List<TableColumn> columns = new ArrayList<TableColumn>(nColumns);
554 for (int i = nColumns - 1; i >= 0; --i)
555 columns.add(model.getColumn(i));
556
557 for (TableColumn column : columns)
558 model.removeColumn(column);
559
560 TableModel tableModel = this.getModel();
561
562 for (int i = 0; i < tableModel.getColumnCount(); ++i)
563 {
564 TableColumn column = new TableColumn(i);
565 column.setHeaderValue(tableModel.getColumnName(i));
566 if (tableModel instanceof DatesInfoTableModel)
567 {
568 column.setIdentifier(((DatesInfoTableModel)tableModel)
569 .getItemsForColumn(i).get(0));
570 }
571 model.addColumn(column);
572 }
573 initialize();
574 }
575
576 setTooltips();
577 }
578
579 //=========================================================================//
580 // //
581 // Inner Classes //
582 // //
583 //=========================================================================//
584
585 /** A class that describes the sizes of fields in a column. */
586 private static class ColumnFieldWidths
587 {
588 private static final int padding = 10;
589 int inWidth = 0;
590 int outWidth = 0;
591 int balanceWidth = 0;
592 int activityWidth = 0;
593 int detailedWidth = 0;
594 static int maxTotalWidth = 500;
595
596 @Override
597 public String toString()
598 {
599 String s = "inWidth: " + Integer.toString(inWidth) +
600 ", outWidth: " + Integer.toString(outWidth) +
601 ", balanceWidth: " + Integer.toString(balanceWidth) +
602 ", activityWidth: " + Integer.toString(activityWidth) +
603 ", detailedWidth: " + Integer.toString(detailedWidth);
604
605 return s;
606 }
607 }
608
609 /** A class that describes the colors that are used for every column.
610 *
611 * It is derived from a Colors object and a Budget that describes the structure
612 * of ExpenseCategories, Accounts ets. In general, a column that corresponds
613 * to an account will have only one collor associated with it (the color that
614 * corresponds to that account in the Colors object). If a column is associated
615 * with one or several expense categories it can have more than one color
616 * associated with it. The list of colors associated with a particular expense
617 * category inclues the color associated with that category in the Colors object
618 * as well as all colors associated with super categories of that category.
619 */
620 private static class ColorStructure
621 {
622 /** Lists of colors associated with a column. If a particular value is null,
623 * then no color is associated with the column.
624 */
625 final List<List<Color>> colorLists;
626
627 /** A list of numbers of colors shared with the next column. For example, if
628 * colum zero has 5 colors t 3 of which are the same (derived from the
629 * same categories) as the colors for the column one, nShared[0] = 3.
630 */
631 final List<Integer> nShared;
632
633 ColorStructure(int nColumns)
634 {
635 colorLists = new ArrayList<List<Color>>(nColumns);
636 nShared = new ArrayList<Integer>(nColumns);
637 Integer zero = new Integer(0);
638 for (int i = 0; i < nColumns; i++)
639 {
640 colorLists.add(null);
641 nShared.add(zero);
642 }
643 }
644 }
645
646 /** Constants that describe rendering method. */
647 public static class RenderingType
648 {
649 private static final List<RenderingType> types =
650 new ArrayList<RenderingType>(4);
651
652 /** Shows detailed information. In/out/balance fields are shown. */
653 public static final RenderingType DETAILED = new RenderingType(1);
654 /** Shows only balance. */
655 public static final RenderingType BALANCE = new RenderingType(2);
656 /** Shows only daily activity (In - Out). */
657 public static final RenderingType ACTIVITY = new RenderingType(3);
658 /** Shows detailed info for the selected column and activity for all others.*/
659 public static final RenderingType HYBRID = new RenderingType(4);
660 /** Shows activity and balance in two separate columns */
661 public static final RenderingType ACTIVITY_BALANCE = new RenderingType(5);
662
663 private final int index;
664
665 private RenderingType(int index)
666 {
667 this.index = index;
668 types.add(this);
669 }
670
671 public int getIndex()
672 {return index;}
673
674 /** Returns a rendering type described by a given index. If no type with
675 * such index is found, DETAILED type is returned.
676 */
677 public static RenderingType get(int index)
678 {
679 for (RenderingType t : types)
680 if (t.index == index)
681 return t;
682 return DETAILED;
683 }
684 }
685
686 /** Constants that describe rendering method. */
687 public static class BackgroundType
688 {
689 private static final List<BackgroundType> types =
690 new ArrayList<BackgroundType>(6);
691
692 private final static int PLAIN_INDEX = 1;
693 private final static int STRIPED_INDEX = 2;
694 private final static int STRIPED_MASK = PLAIN_INDEX | STRIPED_INDEX;
695
696 private final static int STRUCT_FULL_INDEX = 4;
697 private final static int STRUCT_SIMPL_INDEX = 8;
698 private final static int STRUCT_MASK = STRUCT_FULL_INDEX | STRUCT_SIMPL_INDEX;
699
700 /** Plain white background. */
701 public static final BackgroundType PLAIN = new BackgroundType(PLAIN_INDEX);
702 /** Alternating color rows. */
703 public static final BackgroundType STRIPED = new BackgroundType(STRIPED_INDEX);
704 /** Bacground reflects the structure of the budget. */
705 public static final BackgroundType STRUCTURE_FULL =
706 new BackgroundType(STRUCT_FULL_INDEX + PLAIN_INDEX);
707 /** Bacground reflects the structure of the budget. */
708 public static final BackgroundType STRUCTURE_FULL_STRIPED =
709 new BackgroundType(STRUCT_FULL_INDEX + STRIPED_INDEX);
710 /** Bacground reflects the structure of the budget. */
711 public static final BackgroundType STRUCTURE_SIMPLE =
712 new BackgroundType(STRUCT_SIMPL_INDEX + PLAIN_INDEX);
713 /** Bacground reflects the structure of the budget. */
714 public static final BackgroundType STRUCTURE_SIMPLE_STRIPED =
715 new BackgroundType(STRUCT_SIMPL_INDEX + STRIPED_INDEX);
716
717 private final int index;
718
719 private BackgroundType(int index)
720 {
721 this.index = index;
722 types.add(this);
723 }
724
725 public int getIndex()
726 {return index;}
727
728 public boolean isPlain()
729 {
730 return (index & PLAIN_INDEX) != 0;
731 }
732
733 public boolean isStriped()
734 {
735 return (index & STRIPED_INDEX) != 0;
736 }
737
738 public boolean isStructureFull()
739 {
740 return (index & STRUCT_FULL_INDEX) != 0;
741 }
742
743 public boolean isStructureSimple()
744 {
745 return (index & STRUCT_SIMPL_INDEX) != 0;
746 }
747
748 public boolean isStructureOFF()
749 {
750 return (index & STRUCT_MASK) == 0;
751 }
752
753 public BackgroundType getStriped()
754 {
755 return get((index & STRUCT_MASK) | STRIPED_INDEX);
756 }
757
758 public BackgroundType getPlain()
759 {
760 return get((index & STRUCT_MASK) | PLAIN_INDEX);
761 }
762
763 public BackgroundType getStructOFF()
764 {
765 return get(index & STRIPED_MASK);
766 }
767
768 public BackgroundType getStructSimple()
769 {
770 return get((index & STRIPED_MASK) | STRUCT_SIMPL_INDEX);
771 }
772
773 public BackgroundType getStructFull()
774 {
775 return get((index & STRIPED_MASK) | STRUCT_FULL_INDEX);
776 }
777
778 /** Returns a background type described by a given index. If no type with
779 * such index is found, PLAIN type is returned.
780 */
781 public static BackgroundType get(int index)
782 {
783 for (BackgroundType t : types)
784 if (t.index == index)
785 return t;
786 return PLAIN;
787 }
788
789 @Override
790 public String toString()
791 {
792 String res = isPlain() ? "PLAIN:" : "STRIPED:";
793 if (isStructureOFF())
794 res += "NO STRUCTURE";
795 else
796 res += isStructureSimple() ? "SIMPLE STRUCTURE" : "FULL STRUCTURE";
797 return res;
798 }
799 }
800
801 /** Constants that describe highligting method. */
802 public static class HighlightingType
803 {
804 private static final List<HighlightingType> types =
805 new ArrayList<HighlightingType>(3);
806
807 /** Plain white background. */
808 public static final HighlightingType NO_HIGHLIGHTING = new HighlightingType(1);
809 /** Alternating color rows. */
810 public static final HighlightingType UDERLINE = new HighlightingType(2);
811
812 private final int index;
813
814 private HighlightingType(int index)
815 {
816 this.index = index;
817 types.add(this);
818 }
819
820 public int getIndex()
821 {return index;}
822
823 /** Returns a highligting type described by a given index. If no type with
824 * such index is found, PLAIN type is returned.
825 */
826 public static HighlightingType get(int index)
827 {
828 for (HighlightingType t : types)
829 if (t.index == index)
830 return t;
831 return NO_HIGHLIGHTING;
832 }
833 }
834
835 /** Container class for storing rendering settings. */
836 public static class RenderingState extends ActionSignaler
837 {
838 private RenderingType renderingType = RenderingType.DETAILED;
839 private BackgroundType backgroundType = BackgroundType.PLAIN;
840 private HighlightingType highlightingType = HighlightingType.NO_HIGHLIGHTING;
841
842 public RenderingType getRenderingType()
843 {
844 return renderingType;
845 }
846
847 public void setRenderingType(RenderingType renderingType)
848 {
849 this.renderingType = renderingType;
850 signal();
851 }
852
853 public BackgroundType getBackgroundType()
854 {
855 return backgroundType;
856 }
857
858 public void setBackgroundType(BackgroundType backgroundType)
859 {
860 this.backgroundType = backgroundType;
861 signal();
862 }
863
864 public HighlightingType getHighlightingType()
865 {
866 return highlightingType;
867 }
868
869 public void setHighlightingType(HighlightingType highlightingType)
870 {
871 this.highlightingType = highlightingType;
872 signal();
873 }
874
875 //================ Converting to and from JDOM Elements ==========//
876
877 /** Returns a JDOM XML Element representation of the current state */
878 public Element getXmlElement()
879 {
880 Element element = new Element("rendering_state");
881 element.setAttribute("rendering_type",
882 Integer.toString(renderingType.getIndex()));
883 element.setAttribute("background_type",
884 Integer.toString(backgroundType.getIndex()));
885 element.setAttribute("highlighting_type",
886 Integer.toString(highlightingType.getIndex()));
887
888 return element;
889 }
890
891 /** Returns a RenderingState objed represented by a given XML Element */
892 public static RenderingState getInstance(Element element) throws JDOMException
893 {
894 RenderingState renderingState = new RenderingState();
895
896 Attribute attr = element.getAttribute("rendering_type");
897 if (attr == null)
898 throw new JDOMException("No rendering_type attribute");
899 int index = attr.getIntValue();
900 renderingState.renderingType = RenderingType.get(index);
901
902 attr = element.getAttribute("background_type");
903 if (attr == null)
904 throw new JDOMException("No background_type attribute");
905 index = attr.getIntValue();
906 renderingState.backgroundType = BackgroundType.get(index);
907
908 attr = element.getAttribute("highlighting_type");
909 if (attr == null)
910 throw new JDOMException("No highlighting_type attribute");
911 index = attr.getIntValue();
912 renderingState.highlightingType = HighlightingType.get(index);
913
914 return renderingState;
915 }
916 }
917
918 /** Class that stores colors associated with a particular Account or
919 * expense category.
920 */
921 public static class Colors extends ActionSignaler
922 {
923 private final Map<Pair<String,Integer>, Color> accountColors =
924 new HashMap<Pair<String,Integer>, Color>();
925
926 private final Map<Pair<String,Integer>, Color> categoryColors =
927 new HashMap<Pair<String,Integer>, Color>();
928
929 public Color getColor(Object o)
930 {
931 if (o instanceof Account)
932 return getColor((Account)o);
933 if (o instanceof ExpenseCategory)
934 return getColor((ExpenseCategory)o);
935 throw new IllegalArgumentException();
936 }
937
938 public void setColor(Object o, Color color)
939 {
940 if (o instanceof Account)
941 {
942 setColor((Account)o, color);
943 return;
944 }
945 if (o instanceof ExpenseCategory)
946 {
947 setColor((ExpenseCategory)o, color);
948 return;
949 }
950 throw new IllegalArgumentException();
951 }
952
953 /** Returns a color associated with a particular Account or null if there
954 * is no color associated with the account.*/
955 public Color getColor(Account account)
956 {
957 return accountColors.get(new Pair<String,Integer>(
958 account.getName(), new Integer(account.getID())));
959 }
960
961 /** Changes the color associated with a particular account. Notifies all
962 * listeners that the color was changed.
963 */
964 public void setColor(Account account, Color color)
965 {
966 accountColors.put( new Pair<String,Integer>(
967 account.getName(), new Integer(account.getID())), color );
968 signal();
969 }
970
971 /** Returns a color associated with a particular ExpenseCategory or null if
972 * there is no color associated with the expense category.*/
973 public Color getColor(ExpenseCategory category)
974 {
975 return categoryColors.get(new Pair<String,Integer>(
976 category.getName(), new Integer(category.getID())));
977 }
978
979 /** Changes the color associated with a particular expense category.
980 * Notifies all listeners that the color was changed.
981 */
982 public void setColor(ExpenseCategory category, Color color)
983 {
984 categoryColors.put( new Pair<String,Integer>(
985 category.getName(), new Integer(category.getID())), color );
986 signal();
987 }
988
989 /** Returns a JDOMElement describing this object. */
990 public Element getXmlelement()
991 {
992 Element element = new Element("colors");
993 Element accountsE = new Element("account_colors");
994 Element categoriesE = new Element("category_colors");
995
996 element.addContent(accountsE);
997 element.addContent(categoriesE);
998
999 Set<Pair<String,Integer>> allAccounts = accountColors.keySet();
1000 for (Pair<String,Integer> accountInfo : allAccounts)
1001 {
1002 Color color = accountColors.get(accountInfo);
1003 assert(color != null);
1004 Element e = new Element("value");
1005 e.setAttribute("name", accountInfo.first());
1006 e.setAttribute("id", accountInfo.second().toString());
1007 e.setAttribute("color",ColorParser.colorToString(color));
1008 accountsE.addContent(e);
1009 }
1010
1011 Set<Pair<String,Integer>> allCats = categoryColors.keySet();
1012 for (Pair<String,Integer> categoryInfo : allCats)
1013 {
1014 Color color = categoryColors.get(categoryInfo);
1015 assert(color != null);
1016 Element e = new Element("value");
1017 e.setAttribute("name", categoryInfo.first());
1018 e.setAttribute("id", categoryInfo.second().toString());
1019 e.setAttribute("color",ColorParser.colorToString(color));
1020 categoriesE.addContent(e);
1021 }
1022
1023 return element;
1024 }
1025
1026 public static Colors getInstance(Element element) throws JDOMException
1027 {
1028 Colors colors = new Colors();
1029
1030 Element accountsE = element.getChild("account_colors");
1031 Element categoriesE = element.getChild("category_colors");
1032
1033 if (accountsE != null)
1034 {
1035 List<Element> el = accountsE.getChildren("value");
1036 for (Element e : el)
1037 {
1038 Attribute attr = e.getAttribute("name");
1039 if (attr == null)
1040 throw new JDOMException("Corrupt XML data. No name attribute");
1041 String name = attr.getValue();
1042 attr = e.getAttribute("id");
1043 if (attr == null)
1044 throw new JDOMException("Corrupt XML data. No id attribute");
1045 int id = attr.getIntValue();
1046 attr = e.getAttribute("color");
1047 if (attr == null)
1048 throw new JDOMException("Corrupt XML data. No color attribute");
1049 Color color = ColorParser.parse(attr.getValue());
1050
1051 colors.accountColors.put(
1052 new Pair<String,Integer>(name, new Integer(id)), color);
1053 }
1054 }
1055
1056 if (categoriesE != null)
1057 {
1058 List<Element> el = categoriesE.getChildren("value");
1059 for (Element e : el)
1060 {
1061 Attribute attr = e.getAttribute("name");
1062 if (attr == null)
1063 throw new JDOMException("Corrupt XML data. No name attribute");
1064 String name = attr.getValue();
1065 attr = e.getAttribute("id");
1066 if (attr == null)
1067 throw new JDOMException("Corrupt XML data. No id attribute");
1068 int id = attr.getIntValue();
1069 attr = e.getAttribute("color");
1070 if (attr == null)
1071 throw new JDOMException("Corrupt XML data. No color attribute");
1072 Color color = ColorParser.parse(attr.getValue());
1073
1074 colors.categoryColors.put(
1075 new Pair<String,Integer>(name, new Integer(id)), color);
1076 }
1077 }
1078
1079 return colors;
1080
1081 }
1082 }
1083
1084 }