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     * BudgetTreeModel.java
024     *
025     * Created on March 29, 2006, 8:44 PM
026     */
027    
028    package org.jbudget.gui.budget;
029    
030    import org.jbudget.Core.Account;
031    import org.jbudget.Core.AutomaticTransaction;
032    import org.jbudget.Core.Budget;
033    import org.jbudget.Core.ExpenseAllocation;
034    import org.jbudget.Core.ExpenseCategory;
035    import org.jbudget.Core.IncomeSource;
036    import org.jbudget.Core.MoneyPit;
037    import javax.swing.tree.*;
038    import javax.swing.event.*;
039    import java.util.List;
040    import java.util.LinkedList;
041    import java.util.ArrayList;
042    import java.util.Collections;
043    import java.util.HashSet;
044    import java.util.Set;
045    
046    /**
047     * An implementation of the TreeModel interface that 
048     * is used to display a Budget class as a jTree.
049     * @author petrov
050     */
051    public class BudgetTreeModel implements TreeModel
052    {
053      final Budget budget;
054      List<TreeModelListener> listeners = new LinkedList<TreeModelListener>();
055      
056      static final String root = "Budget Items";
057      static final String expenseCategories = "Expense Categories";
058      static final String accounts = "Accounts";
059      static final String incomeSources = "IncomeSources";
060      
061      private boolean showAllocations = false;
062      private boolean showTransactions = false;
063      
064      private final List<Object> list = new ArrayList<Object>();
065      private final List<Object> typesList = new ArrayList<Object>(3);
066          
067      /** Creates a new instance of BudgetTreeModel */
068      public BudgetTreeModel(Budget budget)
069      {
070        assert budget != null;
071        this.budget = budget;
072        typesList.add(accounts);
073        typesList.add(expenseCategories);
074        typesList.add(incomeSources);
075      }
076      
077      /** Add a listener that will be notified when the model or underlying 
078       * budget object change.
079       */
080      public void addTreeModelListener(TreeModelListener listener)
081      {
082        listeners.add(listener);
083      }
084      
085      /** Remove a listener.*/
086      public void removeTreeModelListener(TreeModelListener listener)
087      {
088        listeners.remove(listener);
089      }
090      
091      /** returns a child object */
092      public Object getChild(Object parent, int index)
093      {
094        List<Object> list = getChildrenList(parent);
095        if (index >= list.size())
096          return null;
097        return list.get(index);
098      }
099      
100      /** returns number of children of an object */
101      public int getChildCount(Object parent)
102      {
103        return getChildrenList(parent).size();
104      }
105      
106      /** returns the index of a child */
107      public int getIndexOfChild(Object parent, Object child)
108      {
109        if (parent == null)
110          parent = root;
111        return getChildrenList(parent).indexOf(child);
112      }
113      
114      /** returns the root of the tree */
115      public Object getRoot() {return root;}
116      
117      /** returns true if the object does not have any children */
118      public boolean isLeaf(Object node)
119      {
120        return getChildrenList(node).size() == 0;
121      }
122      
123      /** called when the object is changed */
124      public void  valueForPathChanged(TreePath path, Object newValue) 
125      {
126        //FIX ME.
127      }
128      
129      /**
130       * get a list of children of a particular object. Returns empty list for
131       * ExpenseAllocations and AutomaticTransactions. Returns a list of 
132       * subcategories for an ExpenseCategory. If enabled adds ExpenseAllocations
133       * and AutomaticTransactions to the list for ExpenseCategories, Accounts,
134       * and IncomeSources.
135       */
136      private List<Object> getChildrenList(Object parent)
137      {
138        list.clear();
139        
140        if (parent == root)
141          return typesList;
142        
143        if (parent == accounts){
144          list.addAll(budget.getRegisteredAccounts());
145          return list;
146        }
147        
148        if (parent == expenseCategories){
149          list.addAll(budget.getRootExpenseCategories());
150          return list;
151        }
152        
153          
154        if (parent == incomeSources) {
155          list.addAll(budget.getIncomeSources());
156          return list;
157        }
158        
159        if (parent instanceof IncomeSource && showTransactions) 
160        {
161          IncomeSource incomeSource = (IncomeSource)parent;
162          list.addAll(budget.getAutoTransactionsSource(
163              new MoneyPit(incomeSource, budget)));
164          return list;
165        }
166        
167        if (parent instanceof Account && showTransactions) 
168        {
169          Account account = (Account)parent;
170          MoneyPit moneyPit = new MoneyPit(account);
171          Set<Object> set = new HashSet<Object>();
172          set.addAll(budget.getAutoTransactionsSource(moneyPit));
173          set.addAll(budget.getAutoTransactionsDest(moneyPit));
174          list.addAll(set);
175          
176          return list;
177        }
178        
179        if (parent instanceof ExpenseCategory) 
180        {
181          ExpenseCategory parentCategory = (ExpenseCategory)parent;
182          list.addAll(budget.getSubcategories(parentCategory));
183          if (showAllocations)
184            list.addAll(budget.getAllocations(parentCategory));
185          if (showTransactions)
186            list.addAll(budget.getAutoTransactionsDest(
187                new MoneyPit(parentCategory, budget)));
188    
189           return list;
190        }
191        
192        return Collections.emptyList();
193      }
194      
195      
196      /** Returns a TreePath to the given Object 
197       *@param object the object the path to will be returned.
198       *@param bySource some leaf nodes can appear in two places if they have both
199       *       source and destination. If this flag is true a path through the 
200       *       source of a transaction will be returned. In the opposite case a 
201       *       path through a destinaiton will be returned.
202       */
203      public TreePath getTreePath(Object object, boolean bySource) {
204        return new TreePath(getPath(object, bySource));
205      }
206      
207      /** Returns a path that identifies a given object in the tree
208       *@param object the object the path to will be returned.
209       *@param bySource Some leaf nodes can appear in two places if they have both
210       *       source and destination. If this flag is true a path through the 
211       *       source of a transaction will be returned. In the opposite case a 
212       *       path through a destinaiton will be returned.
213       */
214      public Object[] getPath(Object object, boolean bySource)
215      {
216        List<Object> path = new ArrayList<Object>(4);
217        path.add(root);
218        
219        if (object instanceof ExpenseCategory)
220        {
221          path.add(expenseCategories);
222          ExpenseCategory category = (ExpenseCategory) object;
223          path.addAll(getCategoryPath(category));
224          return path.toArray();
225        } 
226        else if (object instanceof Account)
227          path.add(accounts);
228        else if (object instanceof IncomeSource)
229          path.add(incomeSources);
230        else if (object instanceof ExpenseAllocation)
231        {
232          path.add(expenseCategories);
233          ExpenseCategory category = 
234              ((ExpenseAllocation)object).getExpenseCategory();
235          path.addAll(getCategoryPath(category));
236        } 
237        else if (object instanceof AutomaticTransaction)
238        {
239          AutomaticTransaction autoTr = (AutomaticTransaction)object;
240          MoneyPit thePit = bySource ? autoTr.getSource() : autoTr.getDestination();
241          if (thePit != null)
242          {
243            if (thePit.getType() == MoneyPit.Type.EXPENSE)
244            {
245              path.add(expenseCategories);
246              path.addAll(getCategoryPath(thePit.getExpenseCategory()));
247            }
248            else if (thePit.getType() == MoneyPit.Type.ACCOUNT)
249            {
250              path.add(accounts);
251              path.add(thePit.getContent());
252            }
253            else if (thePit.getType() == MoneyPit.Type.INCOME)
254            {
255              path.add(incomeSources);
256              path.add(thePit.getContent());
257            }
258          }
259          else
260            return new Object[0];
261        }
262          
263        path.add(object);
264        return path.toArray();
265      }
266      
267      /** Returns a path to a given expense category */
268      private List<ExpenseCategory> getCategoryPath(ExpenseCategory category)
269      {
270        List<ExpenseCategory> path = new LinkedList<ExpenseCategory>();
271        path.add(category);
272        ExpenseCategory parent = budget.getParentCategory(category);
273        while (parent != null){
274          path.add(0,parent);
275          parent = budget.getParentCategory(parent);
276        }
277        return path;
278      }
279      //======================= Accessors =========================//
280      
281      /** Shows/hides allocations */
282      public void setShowAllocations(boolean showAllocations)
283      {
284        if (this.showAllocations == showAllocations)
285          return;
286        List<Object> path = new ArrayList<Object>();
287        path.add(root);
288        if (showAllocations)
289          this.showAllocations = true;
290        signalDisplayAllocations(path, showAllocations);
291        if (!showAllocations)
292          this.showAllocations = false;
293      }
294      
295      /** Returns true if allocations are shown */
296      public boolean getShowAllcations(){return showAllocations;}
297      
298      /** Shows/hides automatic transactions */
299      public void setShowTransactions(boolean showTransactions)
300      {
301        if (this.showTransactions == showTransactions)
302          return;
303        List<Object> path = new ArrayList<Object>();
304        path.add(root);
305        if (showTransactions)
306          this.showTransactions = true;
307        signalDisplayTransactions(path, showTransactions);
308        if (!showTransactions)
309          this.showTransactions = false;
310      }
311      
312      /** Returns true if deductions are shown */
313      public boolean getShowTransactions(){return showTransactions;}
314      
315      //==================== Helper Methods ======================//
316      
317      /** Recursively applies a 'signal' function to a given node and to all
318       *  its leafs
319       */
320      private void signalRecursively(List<Object> path, Signaler signaler)
321      {
322        assert path.size() > 0;
323        
324        if (listeners.isEmpty())
325          return;
326        
327        signaler.signal(path);
328        List<Object> children = new ArrayList<Object>();
329        children.addAll(getChildrenList(path.get(path.size() - 1)));
330        for (Object child : children)
331        {
332          path.add(child);
333          signalRecursively(path, signaler);
334          path.remove(path.size() - 1);
335        }
336      }
337      
338      /** A helper function that signals the tree model that allocations
339       * should be displayed or hidden
340       */
341      private void signalDisplayAllocations(List<Object> path, boolean display)
342      {
343        signalRecursively(path, new AllocationsSignaler(display));
344      }
345      
346      /** A helper function that signals the tree model that automatic transactions
347       * should be displayed or hidden
348       */
349      private void signalDisplayTransactions(List<Object> path, boolean display)
350      {
351        signalRecursively(path, new TransactionsSignaler(display));
352      }
353      
354      //==================== Extra Methods ======================//
355      
356      /** Removes a node.
357       * @param path the path to the node that will be removed
358       * @param index the index of the node that will be removed in the list of all
359       *        children of the node's parent.
360       */
361      public void signalNodeRemoved (TreePath path, int index)
362      {
363        TreePath parentPath = path.getParentPath();
364        Object[] node = new Object[] {path.getLastPathComponent()};
365        int [] indexes = new int[] {index};
366        
367        assert node[0] != null : "Null node";
368        
369        TreeModelEvent event = new TreeModelEvent(this, parentPath, indexes, node);
370        for (TreeModelListener listener : listeners)
371            listener.treeNodesRemoved(event);
372      }
373      
374      
375      /** signals to all listeners that a node was inserted.
376       * @param path the path to the node that was inserted.
377       * @param index the index given by getChildIndex(...).
378       */
379      public void signalNodeInserted (TreePath path, int index)
380      {
381        TreePath parentPath = path.getParentPath();
382        Object[] node = new Object[] {path.getLastPathComponent()};
383        int [] indexes = new int[] {index};
384        
385        assert node[0] != null : "Null node";
386        
387        TreeModelEvent event = new TreeModelEvent(this, parentPath, indexes, node);
388        for (TreeModelListener listener : listeners)
389            listener.treeNodesInserted(event);
390      }
391      
392      /** signals to all listeners that a node was updated.
393       * @param path the path to the node that was updated.
394       * @param index the index given by getChildIndex(...).
395       */
396      public void signalNodeChanged (TreePath path, int index)
397      {
398        TreePath parentPath = path.getParentPath();
399        Object[] node = new Object[] {path.getLastPathComponent()};
400        int [] indexes = new int[] {index};
401        
402        assert node[0] != null : "Null node";
403        
404        TreeModelEvent event = new TreeModelEvent(this, parentPath, indexes, node);
405        for (TreeModelListener listener : listeners)
406            listener.treeNodesChanged(event);
407      } 
408      
409      /** signals to all listeners that the structure of the tree has changed.
410       * @param path the path to the node that is the root of the part of the tree
411       *        that has changed.
412       * @param index the index given by getChildIndex(...).
413       */
414      public void signalStructureChanged (TreePath path, int index)
415      {
416        TreePath parentPath = path.getParentPath();
417        Object[] node = new Object[] {path.getLastPathComponent()};
418        int [] indexes = new int[] {index};
419        
420        assert node[0] != null : "Null node";
421        
422        TreeModelEvent event = new TreeModelEvent(this, parentPath, indexes, node);
423        for (TreeModelListener listener : listeners)
424            listener.treeStructureChanged(event);
425      }
426      
427      /** signals to all listeners that the structure of the whole 
428       * tree has changed.
429       */
430      public void signalStructureChanged ()
431      { 
432        TreeModelEvent event = new TreeModelEvent(this, new Object[]{root});
433        for (TreeModelListener listener : listeners)
434            listener.treeStructureChanged(event);
435      } 
436      
437      //============================ Iner classes ============================//
438      
439      private interface Signaler
440      {
441        void signal(List<Object> path);
442      }
443      
444      /** implements the Signaler interface. Sends all listeneres
445       *  show remove signals when allocations are shown or hidden.
446       */
447      private class AllocationsSignaler implements Signaler
448      {
449        private final boolean show;
450        
451        AllocationsSignaler(boolean showAllocations){
452          show = showAllocations;
453        }
454        
455        public void signal(List<Object> path)
456        {
457          if (listeners.isEmpty())
458            return;
459          
460          // generating a list of children that represent allocations.
461          List<Integer> allocationsIndices = new ArrayList<Integer>();
462          List<Object> allocations = new ArrayList<Object>();
463          List<Object> children = getChildrenList(path.get(path.size() - 1));
464          for (int i = 0, s = children.size(); i<s; i++)
465            if (children.get(i) instanceof ExpenseAllocation){
466              allocationsIndices.add(new Integer(i));
467              allocations.add(children.get(i));
468            }
469          
470          int indexes[] = new int[allocationsIndices.size()];
471          for (int i=0, s = allocationsIndices.size(); i < s; i++)
472            indexes[i] = allocationsIndices.get(i).intValue();
473          
474          // Signaling
475          
476          TreeModelEvent event = new TreeModelEvent(this, path.toArray(),
477              indexes, allocations.toArray());
478          for (TreeModelListener listener : listeners)
479            if (show)
480              listener.treeNodesInserted(event);
481            else
482              listener.treeNodesRemoved(event);
483        }
484      }
485      
486      
487      /** implements the Signaler interface. Sends all listeneres
488       *  show remove signals when automatic transactions are shown
489       *  or hidden.
490       */
491      private class TransactionsSignaler implements Signaler
492      {
493        private final boolean show;
494        
495        TransactionsSignaler(boolean showTransactions){
496          show = showTransactions;
497        }
498        
499        public void signal(List<Object> path)
500        {
501          if (listeners.isEmpty())
502            return;
503          
504          // generating a list of children that represent transactions.
505          List<Integer> transactionsIndices = new ArrayList<Integer>();
506          List<Object> transactions = new ArrayList<Object>();
507          List<Object> children = getChildrenList(path.get(path.size() - 1));
508          for (int i = 0, s = children.size(); i<s; i++)
509            if (children.get(i).getClass() == AutomaticTransaction.class){
510              transactionsIndices.add(new Integer(i));
511              transactions.add(children.get(i));
512            }
513          
514          int indexes[] = new int[transactionsIndices.size()];
515          for (int i=0, s = transactionsIndices.size(); i < s; i++)
516            indexes[i] = transactionsIndices.get(i).intValue();
517          
518          // Signaling
519          
520          TreeModelEvent event = new TreeModelEvent(this, path.toArray(),
521              indexes, transactions.toArray());
522          for (TreeModelListener listener : listeners)
523            if (show)
524              listener.treeNodesInserted(event);
525            else
526              listener.treeNodesRemoved(event);
527        }
528      }
529      
530    }