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     * DeatesInfoTableModel.java
024     *
025     * Created on April 15, 2006, 7:09 PM
026     */
027    
028    package org.jbudget.gui.month;
029    
030    import java.awt.Color;
031    import java.text.NumberFormat;
032    import java.util.ArrayList;
033    import java.util.Calendar;
034    import java.util.Collections;
035    import java.util.Date;
036    import java.util.GregorianCalendar;
037    import java.util.HashMap;
038    import java.util.HashSet;
039    import java.util.LinkedList;
040    import java.util.List;
041    import java.util.Map;
042    import java.util.Set;
043    import javax.swing.table.AbstractTableModel;
044    import org.jdom.Attribute;
045    import org.jdom.Element;
046    import org.jdom.JDOMException;
047    import org.jbudget.Core.Account;
048    import org.jbudget.Core.Budget;
049    import org.jbudget.Core.ExpenseCategory;
050    import org.jbudget.Core.MoneyPit;
051    import org.jbudget.Core.Month;
052    import org.jbudget.Core.Transaction;
053    import org.jbudget.Core.User;
054    import org.jbudget.io.DataManager;
055    import org.jbudget.util.CurrencyFormater;
056    import org.jbudget.util.Pair;
057    
058    /** Model for the table that displays the daily income/expense/balance data
059     *  for different categories.
060     *
061     * @author petrov
062     */
063    public class DatesInfoTableModel extends AbstractTableModel 
064                                     implements DataManager.TransactionListener, 
065                                                DataManager.AllocationListener, 
066                                                DataManager.UserListener,
067                                                DataManager.AccountListener
068    {
069      /** List of Budget items associated with columns. */
070      final List<List<MoneyPit>> items = new ArrayList<List<MoneyPit>>();
071      
072      /** A set of MoneyPit objects that correspond to empty (zero balance)
073       * accounts or expense categories. 
074       */
075      final Set<MoneyPit> emptyItems = new HashSet<MoneyPit>();
076      
077      /** A list of MoneyPit objects that correspond to idle (no transactions or
078       * allocations) accounts or expense categories.
079       */
080      final Set<MoneyPit> idleItems = new HashSet<MoneyPit>();
081      
082      /** List of column names. */
083      final List<String> names = new ArrayList<String>();
084      
085      /** List of tool tips for columns. */
086      final List<String> toolTips = new ArrayList<String>();
087      
088      /** List of cell data. Fist list is the same as items, the second list is
089       *  over all dates.
090       */
091      final List<List<CellData>> data = new ArrayList<List<CellData>>();
092      
093      /** A model that gets the appropriate day of the month. */
094      final DatesTableModel datesTableModel;
095      
096      /** The month. */
097      final Month month;
098      
099      /** A calendar instance. */
100      protected final Calendar calendar = new GregorianCalendar();
101      
102      /** State object that describes what columns should be created. */
103      private State state;
104      
105    //==========================================================================//
106      
107      /** Creates a new instance of DeatesInfoTableModel */
108      public DatesInfoTableModel(Month month, DatesTableModel datesTableModel)
109      {
110        state = new State();
111        state.registerModel(this);
112        this.month=month;
113        this.datesTableModel = datesTableModel;
114        initializeItems();
115        initializeData();
116        
117        // Registering with DataManager to receive updates for added/removed
118        // transactions, allocations, and other items of interest.
119        DataManager.getInstance().addTransactionListener(this);
120        DataManager.getInstance().addAllocationListener(this);
121        DataManager.getInstance().addUserListener(this);
122      }
123      
124      /** Creates a new instance of DeatesInfoTableModel */
125      public DatesInfoTableModel(Month month,
126                                 DatesTableModel datesTableModel,
127                                 State state)
128      {
129        this.state = state;
130        state.registerModel(this);
131        this.month=month;
132        this.datesTableModel = datesTableModel;
133        initializeItems();
134        initializeData();
135        
136        
137        //Registering with DataManager to receive updates for added/removed
138        // transactions, allocations, and other items of interest.
139        DataManager.getInstance().addTransactionListener(this);
140        DataManager.getInstance().addAllocationListener(this);
141        DataManager.getInstance().addUserListener(this);
142      }
143      
144      /** copy constructor */
145      public DatesInfoTableModel(DatesInfoTableModel otherModel)
146      {
147        this(otherModel.month, otherModel.datesTableModel, otherModel.state);
148      }
149      
150      /** cleans up */
151      public void dispose(){
152        DataManager.getInstance().removeTransactionListener(this);
153        DataManager.getInstance().removeAllocationListener(this);
154        DataManager.getInstance().removeUserListener(this);
155        state.unregisterModel(this);
156      }
157      
158      /** Changes the State object. */
159      public void setState(State state){
160        this.state.unregisterModel(this);
161        this.state = state;
162        state.registerModel(this);
163        updateModel();
164      }
165      
166      /** Returns the State object used by this model */
167      public State getState(){
168        return state;
169      }
170      
171      /** Returns the month object associated with the model */
172      public Month getMonth(){
173        return month;
174      }
175      
176      /** Reinitializes the table structure and data */
177      private void updateModel(){
178        initializeItems();
179        initializeData();
180        fireTableStructureChanged();
181      }
182      
183      /** Initializes items and names lists. Creates the lists of MoneyPit objects
184       *  that are included in the items list depending on the flag values.
185       */
186      private void initializeItems()
187      {
188        items.clear();
189        names.clear();
190        toolTips.clear();
191        Budget budget = month.getBudget();
192        List<Account> accounts = new LinkedList<Account>();
193        accounts.addAll(budget.getRegisteredAccounts());
194        Collections.sort(accounts);
195        
196        User user = DataManager.getInstance().getCurrentUser();
197        
198        /* Start by finding empty and idle accounts/categories. Save them for 
199         * future use.
200         */
201        
202        emptyItems.clear();
203        idleItems.clear();
204        
205        List<Account> emptyAccounts = getEmptyAccounts();
206        List<Account> idleAccounts = getInactiveAccounts();
207        
208        List<ExpenseCategory> emptyCategories = getEmptyCategories();
209        List<ExpenseCategory> idleCategories = getInactiveCategories();
210        
211        for (Account account : emptyAccounts)
212          emptyItems.add(new MoneyPit(account));
213        
214        for (ExpenseCategory cat : emptyCategories)
215          emptyItems.add(new MoneyPit(cat, budget));
216        
217        for (Account account : idleAccounts)
218          idleItems.add(new MoneyPit(account));
219        
220        for (ExpenseCategory cat : idleCategories)
221          idleItems.add(new MoneyPit(cat, budget));
222        
223        /* If expandAccounts is true, we are showing all accounts that belong to
224         * the current user or all accounts if the current user is SYSTEM. Except 
225         * for the accounts that are hidded or empty or idle depending on the 
226         * settings in the State object associated with this model.
227         */
228        if (state.expandAccounts)
229        {
230          if(state.hideZeroBalanceAccounts)
231            accounts.removeAll(emptyAccounts);
232          else if (state.hideInactiveAccounts)
233            accounts.removeAll(idleAccounts);
234          
235          List<Account> badAccounts = new ArrayList<Account>(10);
236          for (Account account : accounts)
237          {
238            if (state.hiddenAccounts.contains( new Pair<Integer,String>(
239                              new Integer(account.getID()), account.getName()))
240               )
241            {
242              badAccounts.add(account);
243            }
244          }
245          
246          accounts.removeAll(badAccounts);
247          
248          for (Account account : accounts)
249          {
250            List<User> users = account.getAccountHolders();
251            
252            if (user != User.SYSTEM && !users.contains(user))
253              continue;
254            
255            List<MoneyPit> l = new ArrayList<MoneyPit>(1);
256            l.add(new MoneyPit(account));
257            items.add(l);
258            StringBuffer nameBuffer = new StringBuffer();
259            nameBuffer.append(account.getName());
260            
261            // Generating the tooltip for the account.
262            // The tooltip is displayed in the table header.
263            
264            StringBuffer tipBuffer = new StringBuffer();
265            tipBuffer.append("<html>Account: ");
266            tipBuffer.append(account.getName());
267            if (account.getType() != Account.AccountType.UNKNOWN)
268            {
269              tipBuffer.append("<hr>");
270              Account.AccountType type = account.getType();
271              tipBuffer.append("Type: ");
272              tipBuffer.append(type.toString());
273              long limit = account.getLimit();
274              if (limit >= 0)
275              {
276                if (type == Account.AccountType.DEBIT)
277                  tipBuffer.append("<br>Minimum Balance:");
278                else
279                  tipBuffer.append("<br>Credit Limit:");
280                tipBuffer.append(CurrencyFormater.format(limit));
281              }
282              int interestRate = account.getInterestRate();
283              if (interestRate >= 0)
284              {
285                tipBuffer.append("<br>Interest Rate (APY):");
286                NumberFormat formater = NumberFormat.getPercentInstance();
287                formater.setMaximumFractionDigits(2);
288                tipBuffer.append(formater.format(interestRate/10000.0));
289              }
290            }
291            
292            if (!users.isEmpty())
293            {
294              tipBuffer.append("<br>Holders: ");
295              nameBuffer.append("(");
296              
297              int index = 0;
298              for (User holder : users)
299              {
300                String name = holder.getName();
301                if (index < 2)
302                {
303                  if (index > 0)
304                  {
305                    nameBuffer.append(", ");
306                    tipBuffer.append(", ");
307                  }
308                  nameBuffer.append(name);
309                  tipBuffer.append(name);
310                }
311                else
312                {
313                  tipBuffer.append(", ");
314                  tipBuffer.append(name);
315                }
316                index ++;
317              }
318              
319              if (index > 2)
320                nameBuffer.append(", ...");
321              nameBuffer.append(")");
322            }
323            
324            String note = account.getNote();
325            if (note != null && !note.equals(""))
326            {
327              int index = note.indexOf('\n');
328              if (index == note.length() - 1)
329              {
330                note = note.substring(0, index);
331                index = -1;
332              }
333              if (index != -1)
334              {
335                index = note.indexOf('\n', index + 1);
336                if (index == note.length() - 1)
337                {
338                  note = note.substring(0, index);
339                  index = -1;
340                }
341                if (index != -1)
342                  note = note.substring(0, index) + "...";
343              }
344              note = note.replaceAll("\n", "<br>");
345              tipBuffer.append("<br>");
346              tipBuffer.append("<hr>");
347              tipBuffer.append(note);
348            }
349            tipBuffer.append("</html>");
350            
351            names.add(nameBuffer.toString());
352            toolTips.add(tipBuffer.toString());
353          }
354        }
355        else /** expandAccounts is false. Showing a summary of all accounts. */
356        {
357          List<MoneyPit> l = new ArrayList<MoneyPit>();
358          for (Account account : accounts)
359            l.add(new MoneyPit(account));
360          items.add(l);
361          names.add("Accounts");
362          toolTips.add("All accounts combined.");
363        }
364        
365        
366        /* If expandCategoreis is true, we are showing all categories that are used
367         * by all users and categories that are used by the current users. The root
368         * categories that do not hold transactions are not shown if 
369         * collapseSubcategories is false.
370         */
371        if (state.expandCategories)
372        {
373          
374          Map<ExpenseCategory, List<ExpenseCategory>> categoryTree = 
375              new HashMap<ExpenseCategory, List<ExpenseCategory>>();
376          
377          // Start from a "flat tree".
378          List<ExpenseCategory> categories = budget.getAllExpenseCategoriesSorted();
379          for (ExpenseCategory category : categories)
380          {
381            if (user != User.SYSTEM && category.getSelectUsers())
382            {
383              List<User> holders = category.getHolders();
384              if (!holders.contains(user))
385                continue;
386            }
387            List<ExpenseCategory> l = new LinkedList<ExpenseCategory>();
388            l.add(category);
389            categoryTree.put(category, l);
390          }
391          
392          if (state.collapseSubcategories)
393          {
394            // This means that only root categories can be shown, so we need to 
395            // update the tree...
396            List<ExpenseCategory> rootCats = budget.getRootExpenseCategories();
397            for (ExpenseCategory rootCat : rootCats)
398            {
399              List<ExpenseCategory> l = categoryTree.get(rootCat);
400              List<ExpenseCategory>subcats = budget.getSubcategories(rootCat, true);
401              for (ExpenseCategory subcat : subcats)
402              {
403                List<ExpenseCategory> l1 = categoryTree.get(subcat);
404                if (l1 == null)
405                  continue;
406                l.addAll(l1);
407                categoryTree.remove(subcat);
408              }
409            }
410            
411            // It is possible that some users are not using the root categories,
412            // but are using some subcategories. We need to account for this 
413            // (strange) case and collapse all of those subcategories.
414            Set<ExpenseCategory> orphanCats = new HashSet<ExpenseCategory>();
415            orphanCats.addAll(categoryTree.keySet());
416            orphanCats.removeAll(rootCats);
417            for (ExpenseCategory category : orphanCats)
418            {
419              List<ExpenseCategory> l = categoryTree.get(category);
420              if (l == null)
421                continue;
422              List<ExpenseCategory>subcats = budget.getSubcategories(category, true);
423              for (ExpenseCategory subcat : subcats)
424              {
425                List<ExpenseCategory> l1 = categoryTree.get(subcat);
426                if (l1 == null)
427                  continue;
428                l.addAll(l1);
429                categoryTree.remove(subcat);
430              }
431            }
432          }
433          else //state.collapseSubcategories
434          {
435            for (ExpenseCategory category : categories)
436            {
437              Pair<Integer,String> categoryInfo = 
438                  new Pair<Integer,String>(new Integer(category.getID()), 
439                                                       category.getName());
440              if (state.collapsedCategories.contains(categoryInfo))
441              {
442                List<ExpenseCategory> l = categoryTree.get(category);
443                if (l == null)
444                  continue;
445                List<ExpenseCategory>subcats = budget.getSubcategories(category, true);
446                for (ExpenseCategory subcat : subcats)
447                {
448                  List<ExpenseCategory> l1 = categoryTree.get(subcat);
449                  if (l1 == null)
450                    continue;
451                  l.addAll(l1);
452                  categoryTree.remove(subcat);
453                }
454              }
455            }
456          }
457          
458          // All categories that have to be collapsed should have been collapsed 
459          // by now. That is the nodes corresponding to subcategories of collapsed
460          // categories were removed from the hash table categoryTree and were
461          // added to the lists of appropriate super categories. 
462          
463          // Now we need to hide categories that have to be hidden. This is pretty
464          // easy except for the case when a category was collapsed, and now one
465          // entry corresponds to several categories. This case is ambigous. 
466          // We will hide such an entry if  the uppermost category in the category
467          // tree is explicitly marked as hidden in the state object. As luck would
468          // have it, this is also the first category in the list of categories
469          // corresponding to a particular column.  On the other hand, if empty
470          // or idle categories are hidden, then all categories corresponding to 
471          // a given column have to be idle or empty to be hidden.
472          
473          if (!(state.hiddenCategories.isEmpty()))
474          {
475            for (ExpenseCategory category : categories)
476            {
477              
478              Pair<Integer,String> categoryInfo = 
479                  new Pair<Integer,String>(new Integer(category.getID()), 
480                                                       category.getName());
481              if (state.hiddenCategories.contains(categoryInfo))
482                categoryTree.remove(category);
483            }
484          }
485          
486          Set<ExpenseCategory> hiddenCategories = new HashSet<ExpenseCategory>();
487          if (state.hideInactiveCategories)
488            hiddenCategories.addAll(idleCategories);
489          if (state.hideZeroBalanceCategories)
490            hiddenCategories.addAll(emptyCategories);
491          
492          for (ExpenseCategory category : categories)
493          {
494            List<ExpenseCategory> children = categoryTree.get(category);
495            if (children == null)
496              continue;
497            if (hiddenCategories.containsAll(children))
498              categoryTree.remove(category);
499          }
500          
501          
502          // We are done with creating the structure of the categories tree.
503          // Now transfering the data to the items list and creating tool tips and
504          // names.
505          
506          
507          for (ExpenseCategory category : categories)
508          {
509            List<ExpenseCategory> children = categoryTree.get(category);
510            if (children == null)
511              continue;
512            
513              StringBuffer nameBuffer = new StringBuffer();
514              StringBuffer tipBuffer = new StringBuffer();
515              if (children.size() == 1)
516                tipBuffer.append("<html>Exp. Category: ");
517              else
518                tipBuffer.append("<html>Exp. Categories: ");
519              
520              List<MoneyPit> l = new ArrayList<MoneyPit>();
521              int count = 0;
522              for (ExpenseCategory sbc : children){
523                l.add(new MoneyPit(sbc, budget));
524                if (count > 0)
525                  tipBuffer.append(", ");
526                if (count%4 == 2)
527                  tipBuffer.append("<br>                 ");
528                tipBuffer.append(sbc.getName());
529                count ++;
530              }
531              
532              nameBuffer.append(category.getName());
533              if (children.size() > 1)
534              {
535                tipBuffer.append(" combined </html>");
536                nameBuffer.append(" & Sub.");
537              }
538              else
539              {
540                // Here we check for users of a category.
541                // This makes sense only if the item corresponds to only
542                // one category.
543                if (category.getSelectUsers())
544                {
545                  List<User> users = category.getHolders();
546                  
547                  if (!users.isEmpty())
548                  {
549                    tipBuffer.append("<br>Used by: ");
550                    nameBuffer.append("(");
551    
552                    int index = 0;
553                    for (User holder : users)
554                    {
555                      String name = holder.getName();
556                      if (index < 2)
557                      {
558                        if (index > 0)
559                        {
560                          nameBuffer.append(", ");
561                          tipBuffer.append(", ");
562                        }
563                        nameBuffer.append(name);
564                        tipBuffer.append(name);
565                      }
566                      else
567                      {
568                        tipBuffer.append(", ");
569                        tipBuffer.append(name);
570                      }
571                      index ++;
572                    }
573    
574                    if (index > 2)
575                      nameBuffer.append(", ...");
576                    nameBuffer.append(")");
577                  }
578                }
579              }
580                
581              names.add(nameBuffer.toString());
582              tipBuffer.append("</html>");
583              toolTips.add(tipBuffer.toString());
584              items.add(l);
585          }
586        }
587        else /*state.expandCategories*/
588        {
589          List<MoneyPit> l = new ArrayList<MoneyPit>();
590          for (ExpenseCategory exp : budget.getAllExpenseCategories())
591            l.add(new MoneyPit(exp, budget));
592          items.add(l);
593          names.add("Expenses");
594          toolTips.add("All expense categories combined.");
595        }
596          
597      }
598      
599      /** Creates cell data cache. Creates a CellData object for every cell
600       *  and stores it in the data object.
601       */
602      private void initializeData()
603      {
604        data.clear();
605        for (int i = 0, s = items.size(); i<s; i++)
606          data.add(new ArrayList<CellData>(31));
607        for (int row = 0, s = getRowCount(); row < s; row++ )
608        {
609          for (int index = 0, s1 = items.size(); index < s1; index ++){
610            updateData(index, row, false);
611          }
612        }
613      }
614      
615      /** Updates cached data for a given cell. 
616       *@param notify if true the table(listeners) will be notified that the 
617       * content of the cell changed.
618       */
619      private void updateData(int column, int row, boolean notify)
620      {
621        int cDay = datesTableModel.getDayAt(row);
622            
623        List<MoneyPit> pits = items.get(column);
624        
625        if (pits == null || pits.isEmpty())
626          return;
627        
628        CellData cellData = new CellData();
629        cellData.type = pits.get(0).getType();
630        
631        for (MoneyPit pit : pits)
632        {
633          List<Transaction> transactions = month.getTransactions(cDay, pit);
634          cellData.nTransactions += transactions.size();
635          
636          if (pit.getType() == MoneyPit.Type.EXPENSE)
637            cellData.balance += 
638                month.getAllocatedBalance(pit.getExpenseCategory(), cDay);
639          else if (pit.getType() == MoneyPit.Type.ACCOUNT)
640            cellData.balance +=
641                month.getAccountBalance(pit.getAccount(), cDay);
642          
643          for (Transaction transaction : transactions)
644          for (Transaction.Transfer t : transaction.getTransfers())
645          {
646            boolean sourceFlag = pit.equals(t.getSource());
647            boolean destFlag = pit.equals(t.getDestination());
648            long amount = t.getAmount();
649                
650            if (sourceFlag)
651            {
652              if (amount > 0)
653                cellData.outAmount += amount;
654              else
655                cellData.inAmount -= amount;
656            }
657            else if (destFlag)
658            {
659              if (amount > 0)
660                cellData.inAmount += amount;
661              else
662                cellData.outAmount -= amount;
663            }
664          }
665          
666          if (pit.getType() == MoneyPit.Type.EXPENSE)
667          {
668            List<Transaction> allocations = 
669                month.getAllocations(cDay, pit.getExpenseCategory());
670            cellData.nAllocations += allocations.size();
671            for (Transaction allocation : allocations)
672            for (Transaction.Transfer t : allocation.getTransfers())
673            {
674              long amount = t.getAmount();
675              if (pit.equals(t.getDestination()))
676                cellData.allocatedAmount += amount;
677              else if (pit.equals(t.getSource()))
678                cellData.allocatedAmount -= amount;
679            }
680          }
681        }
682        List<CellData> l = data.get(column);
683        if (l.size() <= row)
684          l.add(cellData);
685        else
686          l.set(row, cellData);
687        if (notify)
688          fireTableCellUpdated(row, column);
689      }
690      
691      @Override
692      public Class getColumnClass(int index) 
693      {return CellData.class;}
694      
695      @Override
696      public String getColumnName(int index) 
697      {
698        return names.get(index);
699      }
700      
701      public String getColumnToolTip(int index)
702      {
703        if (index > toolTips.size())
704          return null;
705        return toolTips.get(index);
706      }
707      
708      public int getColumnCount() 
709      {return items.size();}
710      
711      public int getRowCount() 
712      {return datesTableModel.getRowCount();}
713      
714      public Object getValueAt(int rowIndex, int columnIndex)
715      {
716        List<CellData>l = data.get(columnIndex);
717        return l.get(rowIndex);
718      }
719      
720      /**
721       * List of accounts/categories for a given columnIndex.
722       * For a given columnIndex in the table returns an unmodifiable list
723       * of accounts or expense categories that correspond to the columnIndex.
724       */
725      public List<MoneyPit> getItemsForColumn(int columnIndex)
726      {
727        return Collections.unmodifiableList(items.get(columnIndex));
728      }
729     
730      /** Marks the account or the root expense category in the column as hidden */
731      public void hideColumn(int columnIndex)
732      {
733        if (columnIndex >= items.size())
734          return;
735        
736        MoneyPit pit =  items.get(columnIndex).get(0);
737        if(pit.getType() == MoneyPit.Type.EXPENSE)
738        {
739          ExpenseCategory category = pit.getExpenseCategory();
740          state.hideCategory(new Pair(
741              new Integer(category.getID()), category.getName()));
742        }
743        else if(pit.getType() == MoneyPit.Type.ACCOUNT)
744        {
745          Account account = pit.getAccount();
746          state.hideAccount(new Pair(
747              new Integer(account.getID()), account.getName()));
748        }
749      }
750      
751      /** Collapses a column that corresponds to an expense category with 
752       * subcategories. Has no effect for all other types of columns.
753       */
754      public void collapseColumn(int columnIndex)
755      {
756        if (columnIndex >= items.size())
757          return;
758        
759        MoneyPit pit = items.get(columnIndex).get(0);
760        if (pit.getType() != MoneyPit.Type.EXPENSE)
761          return;
762        
763        ExpenseCategory cat = pit.getExpenseCategory();
764        
765        Pair<Integer,String> catInfo = 
766            new Pair<Integer,String>(new Integer(cat.getID()), cat.getName());
767        
768        state.collapseCategory(catInfo);
769      }
770      
771      /** Collapses a parent category of the category corresponding to the selected
772       * column
773       */
774      public void collapseParent(int columnIndex)
775      {
776        if (columnIndex >= items.size())
777          return;
778        
779        MoneyPit pit = items.get(columnIndex).get(0);
780        if (pit.getType() != MoneyPit.Type.EXPENSE)
781          return;
782        
783        ExpenseCategory cat = pit.getExpenseCategory();
784        
785        ExpenseCategory parent = month.getBudget().getParentCategory(cat);
786        if (parent == null)
787          return; 
788        
789        Pair<Integer,String> catInfo = 
790            new Pair<Integer,String>(new Integer(parent.getID()), parent.getName());
791        
792        state.collapseCategory(catInfo);
793      }
794      
795      /** Expands a column that was previously collapsed. Has no effect for other
796       * kinds of columns.
797       */
798      public void expandColumn(int columnIndex)
799      {
800        if (columnIndex >= items.size())
801          return;
802        
803        MoneyPit pit = items.get(columnIndex).get(0);
804        if (pit.getType() != MoneyPit.Type.EXPENSE)
805          return;
806        
807        ExpenseCategory cat = pit.getExpenseCategory();
808        
809        Pair<Integer,String> catInfo = 
810            new Pair<Integer,String>(new Integer(cat.getID()), cat.getName());
811        
812        state.expandCategory(catInfo);
813      }
814      
815      public boolean isExpandable(int columnIndex)
816      {
817        if (columnIndex >= items.size())
818          return false;
819        
820        MoneyPit pit = items.get(columnIndex).get(0);
821        if (pit.getType() != MoneyPit.Type.EXPENSE)
822          return false;
823        
824        ExpenseCategory cat = pit.getExpenseCategory();
825        
826        Pair<Integer,String> catInfo = 
827            new Pair<Integer,String>(new Integer(cat.getID()), cat.getName());
828        
829        return state.getCollapsedCategories().contains(catInfo);
830          
831      }
832      
833      public boolean isCollapsable(int columnIndex)
834      {
835        if (columnIndex >= items.size())
836          return false;
837        
838        MoneyPit pit = items.get(columnIndex).get(0);
839        if (pit.getType() != MoneyPit.Type.EXPENSE)
840          return false;
841        
842        ExpenseCategory cat = pit.getExpenseCategory();
843        
844        if (month.getBudget().getSubcategories(cat).size() == 0)
845          return false;
846        
847        Pair<Integer,String> catInfo = 
848            new Pair<Integer,String>(new Integer(cat.getID()), cat.getName());
849        
850        return !state.getCollapsedCategories().contains(catInfo);
851      }
852      
853      public boolean isParentCollapsable(int columnIndex)
854      {
855        if (columnIndex >= items.size())
856          return false;
857        
858        MoneyPit pit = items.get(columnIndex).get(0);
859        if (pit.getType() != MoneyPit.Type.EXPENSE)
860          return false;
861        
862        ExpenseCategory cat = pit.getExpenseCategory();
863        
864        ExpenseCategory parent = month.getBudget().getParentCategory(cat);
865        if (parent == null)
866          return false; 
867        
868        Pair<Integer,String> catInfo = 
869            new Pair<Integer,String>(new Integer(parent.getID()), parent.getName());
870        
871        return !state.getCollapsedCategories().contains(catInfo);
872        
873      }
874      
875      /** A method that constructs the tool tip for a cell in the table. */
876      public String generateToolTip(int rowIndex, int columnIndex)
877      {
878        StringBuffer buffer = new StringBuffer();
879        CellData cellData = (CellData)getValueAt(rowIndex, columnIndex);
880        
881        String in = "In: ";
882        String out = "Out: ";
883        
884        if (cellData.type == MoneyPit.Type.EXPENSE){
885          in = "Spent: ";
886          out = "Refunded: ";
887        }
888        
889        buffer.append("<html>");
890        
891        if (cellData.nTransactions > 0)
892        {
893          buffer.append(cellData.nTransactions);
894          buffer.append(" Transactions.<br>");
895          buffer.append(in);
896          buffer.append("<b>");
897          buffer.append(CurrencyFormater.format(cellData.inAmount));
898          buffer.append("</b><br>");
899          buffer.append(out);
900          buffer.append("<b>");
901          buffer.append(CurrencyFormater.format(cellData.outAmount));
902          buffer.append("</b><br>");
903        }
904        
905        if (cellData.nAllocations > 0)
906        {
907          buffer.append(cellData.nAllocations);
908          buffer.append(" Allocations.<br>");
909          buffer.append("Allocated:");
910          buffer.append("<b>");
911          buffer.append(CurrencyFormater.format(cellData.allocatedAmount));
912          buffer.append("</b><br>");
913        }
914        
915        buffer.append("Final Balance: ");
916        buffer.append("<b>");
917        buffer.append(CurrencyFormater.format(cellData.balance));
918        buffer.append("</b>"); 
919        buffer.append("</html>");
920        
921        return buffer.toString();
922      }
923      
924      //===========  Implementing Interfaces =================================//
925      
926      /** Called when a transaction is added to the month. */
927      public void transactionAdded(Transaction transaction)
928      {
929            Date date = transaction.getDate();
930            if (date.after(month.endingDate))
931                return;
932    
933            if (date.before(month.startingDate))
934                if (month.getCarryBalance())
935                    date = month.startingDate;
936                else
937                    return;
938    
939            for (Transaction.Transfer transfer : transaction.getTransfers())
940            {
941    
942                MoneyPit source = transfer.getSource();
943                MoneyPit destination = transfer.getDestination();
944    
945                if ((state.getHideInactiveAccounts() ||
946                        state.getHideInactiveCategories() ||
947                        state.getHideZeroBalanceAccounts() ||
948                        state.getHideZeroBalanceCategories()) && 
949                        (checkMoneyPit(source) || checkMoneyPit(destination)))
950                {
951                    updateModel();
952                    break;
953                }
954                else
955                    updateCells(source, destination, date);
956            }
957        }
958      
959      /** Called when a transaction is removed from the month. */
960      public void transactionRemoved(List<Transaction.Transfer> transfers,
961                                           int cDay, int cMonth, int cYear)
962      {
963            calendar.set(Calendar.YEAR, cYear);
964            calendar.set(Calendar.MONTH, cMonth);
965            calendar.set(Calendar.DAY_OF_MONTH, cDay);
966    
967            Date date = calendar.getTime();
968    
969            if (date.after(month.endingDate))
970                return;
971    
972            if (date.before(month.startingDate))
973                if (month.getCarryBalance())
974                    date = month.startingDate;
975                else
976                    return;
977    
978            for (Transaction.Transfer t : transfers)
979            {
980                MoneyPit source = t.getSource();
981                MoneyPit dest = t.getDestination();
982    
983                if (state.getHideInactiveAccounts() ||
984                        state.getHideInactiveCategories() ||
985                        state.getHideZeroBalanceAccounts() ||
986                        state.getHideZeroBalanceCategories())
987                {
988    
989    
990                    boolean reinitialize = false;
991                    if (source != MoneyPit.NONE)
992                    {
993                        Object c = source.getContent();
994                        reinitialize = getEmptyAccounts().contains(c);
995                        reinitialize = reinitialize || getEmptyCategories().contains(c);
996                        reinitialize = reinitialize || getInactiveAccounts().contains(c);
997                        reinitialize = reinitialize || getInactiveCategories().contains(c);
998                    }
999    
1000                    if (dest != MoneyPit.NONE)
1001                    {
1002                        Object c = dest.getContent();
1003                        reinitialize = getEmptyAccounts().contains(c);
1004                        reinitialize = reinitialize || getEmptyCategories().contains(c);
1005                        reinitialize = reinitialize || getInactiveAccounts().contains(c);
1006                        reinitialize = reinitialize || getInactiveCategories().contains(c);
1007                    }
1008    
1009                    if (reinitialize)
1010                    {
1011                        updateModel();
1012                        return;
1013                    }
1014                    updateCells(source, dest, date);
1015                }
1016                else
1017                    updateCells(source, dest, date);
1018            }
1019        }
1020    
1021      /** Called when an allocation is added to the month. */      
1022      public void allocationAdded(Transaction allocation)
1023      {
1024            transactionAdded(allocation);
1025        }
1026      
1027      /** Called when an allocation is removed from the month. */
1028      public void allocationRemoved(List<Transaction.Transfer> transfers, 
1029                                    int cDay, int cMonth, int cYear)
1030      {
1031        transactionRemoved(transfers, cDay, cMonth, cYear);
1032      }
1033      
1034      /** This method is used to check if a transaction/allocation has the source
1035       * or a destination that was hidden because it is empty (zero balance) or
1036       * idle (no trancations  = constant balance)
1037       */
1038      private boolean checkMoneyPit(MoneyPit pit){
1039         return emptyItems.contains(pit) || this.idleItems.contains(pit);
1040      }
1041      
1042      public void userAdded(User user){}
1043      public void userRemoved(int uid){
1044        updateModel();
1045      }
1046      public void userChanged(User user){
1047        updateModel();
1048      }
1049      
1050      public void accountAdded(Account account){}
1051      public void accountRemoved(int accountId){}
1052      public void accountUpdated(Account account){ updateModel(); }
1053      
1054      /** Updates cells that correspond to the given MoneyPit objects.
1055       *  All rows that correspond to dates after the given date(inclusive)
1056       *  are updated. Used to handle transaction and allocation added/removed
1057       *  events.
1058       */
1059      private void updateCells(MoneyPit pit1, MoneyPit pit2, Date  date)
1060      {
1061        int rowStart = datesTableModel.findRow(date);
1062        int rowEnd = datesTableModel.getRowCount();
1063        for (int column = 0, s = items.size(); column < s; column ++)
1064        {
1065          if (items.get(column).contains(pit1) ||
1066              items.get(column).contains(pit2))
1067          {
1068            for (int row = rowStart; row < rowEnd; row ++)
1069              updateData(column, row, true);
1070          }
1071        }
1072      }
1073      
1074      @Override
1075      public void fireTableStructureChanged()
1076      {
1077        super.fireTableStructureChanged();
1078        Object[] listeners = listenerList.getListenerList();
1079         for (int i = listeners.length-1; i>=0; i-=1) 
1080             if (listeners[i] instanceof DatesInfoTable) 
1081               ((DatesInfoTable)listeners[i]).setTooltips();
1082      }
1083      
1084      //====================== Private Methods =================================//
1085      
1086      /** Returns a list of accounts that have zero balance in every day in the 
1087       * current month. This is equivalent to having zero starting balance and 
1088       * no transactions (Assuming nonzero transaction amounts). 
1089       */
1090      List<Account> getEmptyAccounts()
1091      {
1092        List<Account> accounts = new LinkedList<Account>();
1093        accounts.addAll(month.getBudget().getRegisteredAccounts());
1094        
1095        List<Account> emptyAccounts = new LinkedList<Account>();
1096        for (Account account : accounts)
1097        {
1098          if (month.getStartingBalance(account) != 0L)
1099            continue;
1100          if (month.getTransactions(account).size() != 0)
1101            continue;
1102          emptyAccounts.add(account);
1103        }
1104        return emptyAccounts;
1105      }
1106      
1107      /** Returns a list of accounts that have no transactions recorded in the
1108       * current month. 
1109       */
1110      List<Account> getInactiveAccounts()
1111      {
1112        List<Account> accounts = new LinkedList<Account>();
1113        accounts.addAll(month.getBudget().getRegisteredAccounts());
1114        
1115        List<Account> idleAccounts = new LinkedList<Account>();
1116        for (Account account : accounts)
1117        {
1118          if (month.getTransactions(account).size() != 0)
1119            continue;
1120          idleAccounts.add(account);
1121        }
1122        return idleAccounts;
1123      }
1124      
1125      /** Returns a list of expense categories that have zero balance in every day
1126       * in the  current month. This is equivalent to having zero starting balance 
1127       * and no transactions or allocations. (Assuming nonzero transaction amounts). 
1128       */
1129      List<ExpenseCategory> getEmptyCategories()
1130      {
1131        List<ExpenseCategory> categories = new LinkedList<ExpenseCategory>();
1132        categories.addAll(month.getBudget().getAllExpenseCategories());
1133        
1134        List<ExpenseCategory> emptyCategories = new LinkedList<ExpenseCategory>();
1135        for (ExpenseCategory category : categories)
1136        {
1137          if (month.getStartingAllocation(category) != 0L)
1138            continue;
1139          if (month.getTransactions(category).size() != 0)
1140            continue;
1141          if (month.getAllocations(category).size() != 0)
1142            continue;
1143          emptyCategories.add(category);
1144        }
1145        return emptyCategories;
1146      }
1147      
1148      /** Returns a list of expense categories that have no transactions or 
1149       * allocations in the current month. 
1150       */
1151      List<ExpenseCategory> getInactiveCategories()
1152      {
1153        List<ExpenseCategory> categories = new LinkedList<ExpenseCategory>();
1154        categories.addAll(month.getBudget().getAllExpenseCategories());
1155        
1156        List<ExpenseCategory> idleCategories = new LinkedList<ExpenseCategory>();
1157        for (ExpenseCategory category : categories)
1158        {
1159          if (month.getTransactions(category).size() != 0)
1160            continue;
1161          if (month.getAllocations(category).size() != 0)
1162            continue;
1163          idleCategories.add(category);
1164        }
1165        return idleCategories;
1166      }
1167      
1168        
1169      // ===================== NESTED CLASSES ==================================//
1170      
1171      /** A class that is used to return the data that represents the cell */
1172      public static class CellData
1173      {
1174        public long allocatedAmount = 0L;
1175        public long inAmount = 0L;
1176        public long outAmount = 0L;
1177        public long balance = 0L;
1178        
1179        public int nAllocations = 0;
1180        public int nTransactions = 0;
1181        
1182        public MoneyPit.Type type = MoneyPit.Type.UNKNOWN;
1183        
1184        public Color balanceColor = defaultBalanceColor;
1185        public Color activityColor = Color.WHITE;
1186        
1187        static public Color defaultBalanceColor = new Color(216,219,238);
1188      }
1189      
1190      /** A class that describes the state of the table model. It can be shared
1191       * among several DatesInfoTableModel objects so that wen it is changed
1192       * they update automatically.
1193       */
1194      public static class State
1195      {
1196        // =====================  ACCOUNT SETTINGS ===========================//
1197        
1198        /** Show all accounts?  If this is false, all accounts are collapsed into
1199         one column. If it is true the accounts are displayed in accordance with
1200         other "account" settings. */
1201        private boolean expandAccounts = true;
1202        
1203        /** Hide accounts with zero balance */
1204        private boolean hideZeroBalanceAccounts = false;
1205        
1206        /** Hide accounts with no transactions */
1207        private boolean hideInactiveAccounts = false;
1208        
1209        /** A set of IDs of accounts that were explicitly selected to be hidden
1210         * be the user.
1211         */
1212        private Set<Pair<Integer,String>> hiddenAccounts = 
1213            new HashSet<Pair<Integer,String>>();
1214        
1215        
1216        // ================== EXPENSE CATEGORY SETTINGS ========================//
1217        
1218        /** Show all expense categories? If this is false, all expense categories 
1219         * are collapsed into one column. If it is true the expense categories are
1220         * displayed in accordance with other "category" settings.*/
1221        private boolean expandCategories = true;
1222      
1223        /** Collapse subcategories. If this is true only columns corresponding to
1224         * root categories will be created. Information if these columns will 
1225         * reflect the state of the root category and all its subcategories.
1226         */
1227        private boolean collapseSubcategories = false;
1228        
1229        /** Hide Expense categories that do not have zero balance. */
1230        private boolean hideZeroBalanceCategories = false;
1231        
1232        /** Hide expense categories with no transactions. */
1233        private boolean hideInactiveCategories = false;
1234        
1235        /** A set of expense categories that were selected by user to be hidden.
1236         * This setting overrules all the other settings. 
1237         */
1238        private Set<Pair<Integer, String>> hiddenCategories = 
1239            new HashSet<Pair<Integer, String>>();
1240        
1241        /** A set of expense categories that were selected by user to be collapsed
1242         * with their subcategories. For each of this categories and all its 
1243         * subcategories only one column will be displayed in the table that 
1244         * reflects the combined info about the category and subcategories.
1245         */
1246        private Set<Pair<Integer, String>> collapsedCategories =
1247            new HashSet<Pair<Integer, String>>();
1248        
1249        
1250        // ======================= INTERNAL VARIABLES ===========================//
1251        
1252        /** List of DatesInfoTableModel objects that use this State object */
1253        private List<DatesInfoTableModel> models = 
1254            new ArrayList<DatesInfoTableModel>();
1255        
1256        public void registerModel(DatesInfoTableModel model){
1257          models.add(model);
1258        }
1259        
1260        public void unregisterModel(DatesInfoTableModel model){
1261          models.remove(model);
1262        }
1263        
1264        private void update(){
1265          for (DatesInfoTableModel model : models){
1266            model.updateModel();
1267          }
1268        }
1269        
1270        // ========================  Accessor methods =========================//
1271        
1272        public void setExpandAccounts(boolean expandAccounts){
1273          if (this.expandAccounts == expandAccounts)
1274            return;
1275          this.expandAccounts = expandAccounts;
1276          update();
1277        }
1278        
1279        public boolean getExpandAccounts(){ 
1280          return expandAccounts;
1281        }
1282        
1283        
1284        public void setHideZeroBalanceAccounts(boolean hideZeroBalanceAccounts){
1285          if (this.hideZeroBalanceAccounts == hideZeroBalanceAccounts)
1286            return;
1287          this.hideZeroBalanceAccounts = hideZeroBalanceAccounts;
1288          update();
1289        }
1290        
1291        public boolean getHideZeroBalanceAccounts(){ 
1292          return hideZeroBalanceAccounts;
1293        }
1294        
1295        public void setHideInactiveAccounts(boolean hideInactiveAccounts){
1296          if (this.hideInactiveAccounts == hideInactiveAccounts)
1297            return;
1298          this.hideInactiveAccounts = hideInactiveAccounts;
1299          update();
1300        }
1301        
1302        public boolean getHideInactiveAccounts(){ 
1303          return hideInactiveAccounts;
1304        }
1305        
1306        public void hideAccount(Pair<Integer,String> acctInfo){
1307          if (!hiddenAccounts.contains(acctInfo))
1308          {
1309            hiddenAccounts.add(acctInfo);
1310            update();
1311          }
1312        }
1313        
1314        public void showAccount(Pair<Integer,String> acctInfo){
1315          if (hiddenAccounts.contains(acctInfo))
1316          {
1317            hiddenAccounts.remove(acctInfo);
1318            update();
1319          }
1320        }
1321        
1322        Set<Pair<Integer,String>> getHiddenAccounts(){
1323          return Collections.unmodifiableSet(hiddenAccounts);
1324        }
1325        
1326        public void setExpandCategories(boolean expandCategories){
1327          if (this.expandCategories == expandCategories)
1328            return;
1329          this.expandCategories = expandCategories;
1330          update();
1331        }
1332        
1333        public boolean getExpandCategories(){ 
1334          return expandCategories;
1335        }
1336        
1337        public void setCollapseSubcategories(boolean collapseSubcategories){
1338          if (this.collapseSubcategories == collapseSubcategories)
1339            return;
1340          this.collapseSubcategories = collapseSubcategories;
1341          update();
1342        }
1343        
1344        public boolean getCollapseSubcategories(){ 
1345          return collapseSubcategories;
1346        }
1347        
1348        public void setHideZeroBalanceCategories(boolean hideZeroBalanceCategories)
1349        {
1350          if (this.hideZeroBalanceCategories != hideZeroBalanceCategories)
1351          {
1352            this.hideZeroBalanceCategories = hideZeroBalanceCategories;
1353            update();
1354          }
1355        }
1356        
1357        public boolean getHideZeroBalanceCategories(){
1358          return hideZeroBalanceCategories;
1359        }
1360        
1361        public void setHideInactiveCategories(boolean hideInactiveCategories)
1362        {
1363          if (this.hideInactiveCategories != hideInactiveCategories)
1364          {
1365            this.hideInactiveCategories = hideInactiveCategories;
1366            update();
1367          }
1368        }
1369        
1370        public boolean getHideInactiveCategories(){
1371          return hideInactiveCategories;
1372        }
1373        
1374        public void hideCategory(Pair<Integer,String> categoryInfo){
1375          if (!hiddenCategories.contains(categoryInfo))
1376          {
1377            hiddenCategories.add(categoryInfo);
1378            update();
1379          }
1380        }
1381        
1382        public void showCategory(Pair<Integer,String> categoryInfo){
1383          if (hiddenCategories.contains(categoryInfo))
1384          {
1385            hiddenCategories.remove(categoryInfo);
1386            update();
1387          }
1388        }
1389        
1390        public Set<Pair<Integer,String>> getHiddenCategories(){
1391          return Collections.unmodifiableSet(hiddenCategories);
1392        }
1393        
1394        
1395        public void collapseCategory(Pair<Integer,String> categoryInfo){
1396          if (!collapsedCategories.contains(categoryInfo))
1397          {
1398            collapsedCategories.add(categoryInfo);
1399            update();
1400          }
1401        }
1402        
1403        public void expandCategory(Pair<Integer,String> categoryInfo){
1404          if (collapsedCategories.contains(categoryInfo))
1405          {
1406            collapsedCategories.remove(categoryInfo);
1407            update();
1408          }
1409        }
1410        
1411        public Set<Pair<Integer,String>> getCollapsedCategories(){
1412          return Collections.unmodifiableSet(collapsedCategories);
1413        }
1414        
1415         //================ Converting to and from JDOM Elements ==========//
1416      
1417        /** Returns a JDOM XML Element representation of the current state */
1418        public Element getXmlElement()
1419        {
1420          Element stateElement = new Element("column_model_state");
1421          
1422          stateElement.setAttribute(
1423              "expand_accounts", Boolean.toString(expandAccounts));
1424          stateElement.setAttribute(
1425              "hide_zero_balane_accounts", Boolean.toString(hideZeroBalanceAccounts));
1426          stateElement.setAttribute(
1427              "hide_inactive_accounts", Boolean.toString(hideInactiveAccounts));
1428          
1429          stateElement.setAttribute(
1430              "expand_categories", Boolean.toString(expandCategories));
1431          stateElement.setAttribute(
1432              "collapse_subcategories", Boolean.toString(collapseSubcategories));
1433          stateElement.setAttribute(
1434              "hide_zero_balance_categories", Boolean.toString(hideZeroBalanceCategories));
1435          stateElement.setAttribute(
1436              "hide_inactive_categories", Boolean.toString(hideInactiveCategories));
1437          
1438          Element e = new Element("hidden_accounts");
1439          for (Pair<Integer,String> accountInfo : hiddenAccounts)
1440          {
1441            Element e1 = new Element ("account_info");
1442            e1.setAttribute("id", accountInfo.first().toString());
1443            e1.setAttribute("name", accountInfo.second());
1444            e.addContent(e1);
1445          }
1446          stateElement.addContent(e);
1447          
1448          e = new Element("hidden_categories");
1449          for (Pair<Integer,String> catInfo : hiddenCategories)
1450          {
1451            Element e1 = new Element ("category_info");
1452            e1.setAttribute("id", catInfo.first().toString());
1453            e1.setAttribute("name", catInfo.second());
1454            e.addContent(e1);
1455          }
1456          stateElement.addContent(e);
1457          
1458          e = new Element("collapsed_categories");
1459          for (Pair<Integer,String> catInfo : collapsedCategories)
1460          {
1461            Element e1 = new Element ("category_info");
1462            e1.setAttribute("id", catInfo.first().toString());
1463            e1.setAttribute("name", catInfo.second());
1464            e.addContent(e1);
1465          }
1466          stateElement.addContent(e);
1467          
1468          return stateElement;
1469        }
1470        
1471        /** Returns a State object represented by a given XML Element */
1472        static public State getInstance(Element element) throws JDOMException
1473        {
1474          State state = new State();
1475          
1476          Attribute attr = element.getAttribute("expand_accounts");
1477          if (attr == null)
1478            throw new JDOMException("State.getInstance: No expand_accounts attribute");
1479          state.expandAccounts = attr.getBooleanValue();
1480          
1481          attr = element.getAttribute("hide_zero_balane_accounts");
1482          if (attr == null)
1483            throw new JDOMException("State.getInstance: No hide_zero_balane_accounts attribute");
1484          state.hideZeroBalanceAccounts = attr.getBooleanValue();
1485          
1486          attr = element.getAttribute("hide_inactive_accounts");
1487          if (attr == null)
1488            throw new JDOMException("State.getInstance: No hide_inactive_accounts attribute");
1489          state.hideInactiveAccounts = attr.getBooleanValue();
1490          
1491          attr = element.getAttribute("expand_categories");
1492          if (attr == null)
1493            throw new JDOMException("State.getInstance: No expand_categories attribute");
1494          state.expandCategories = attr.getBooleanValue();
1495          
1496          attr = element.getAttribute("collapse_subcategories");
1497          if (attr == null)
1498            throw new JDOMException("State.getInstance: No collapse_subcategories attribute");
1499          state.collapseSubcategories = attr.getBooleanValue();
1500          
1501          attr = element.getAttribute("hide_zero_balance_categories");
1502          if (attr == null)
1503            throw new JDOMException("State.getInstance: No hide_zero_balance_categories attribute");
1504          state.hideZeroBalanceCategories = attr.getBooleanValue();
1505          
1506          attr = element.getAttribute("hide_inactive_categories");
1507          if (attr == null)
1508            throw new JDOMException("State.getInstance: No hide_inactive_categories attribute");
1509          state.hideInactiveCategories = attr.getBooleanValue();
1510          
1511          //
1512          //  Restoring hidden accounts
1513          //
1514          
1515          Element hiddenAccountsElement = element.getChild("hidden_accounts");
1516          for (Element e : (List<Element>)hiddenAccountsElement.getChildren())
1517          {
1518            attr = e.getAttribute("id");
1519            if (attr == null)
1520              throw new JDOMException("State.getInstance: No id attribute for a hidden account");
1521            Integer id = new Integer(attr.getIntValue());
1522            attr = e.getAttribute("name");
1523            if (attr == null)
1524              throw new JDOMException("State.getInstance: No name attribute for a hidden account");
1525            state.hiddenAccounts.add(new Pair<Integer,String>(id, attr.getValue()));
1526          }
1527          
1528          //
1529          //  Restoring hidden categories
1530          //
1531          
1532          Element hiddenCategoriesElement = element.getChild("hidden_categories");
1533          for (Element e : (List<Element>)hiddenCategoriesElement.getChildren())
1534          {
1535            attr = e.getAttribute("id");
1536            if (attr == null)
1537              throw new JDOMException("State.getInstance: No id attribute for a hidden category");
1538            Integer id = new Integer(attr.getIntValue());
1539            attr = e.getAttribute("name");
1540            if (attr == null)
1541              throw new JDOMException("State.getInstance: No name attribute for a hidden category");
1542            state.hiddenCategories.add(new Pair<Integer,String>(id, attr.getValue()));
1543          }
1544          
1545          //
1546          //  Restoring collapsed categories
1547          //
1548          
1549          Element collapsedCategoriesElement = element.getChild("collapsed_categories");
1550          for (Element e : (List<Element>)collapsedCategoriesElement.getChildren())
1551          {
1552            attr = e.getAttribute("id");
1553            if (attr == null)
1554              throw new JDOMException("State.getInstance: No id attribute for a collapsed category");
1555            Integer id = new Integer(attr.getIntValue());
1556            attr = e.getAttribute("name");
1557            if (attr == null)
1558              throw new JDOMException("State.getInstance: No name attribute for a collapsed category");
1559            state.collapsedCategories.add(new Pair<Integer,String>(id, attr.getValue()));
1560          }
1561          
1562          return state;
1563        }
1564      }
1565      
1566    }