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     * MainWindow.java
024     *
025     * Created on May 12, 2006, 7:34 AM
026     */
027    
028    package org.jbudget.gui;
029    
030    import java.awt.BorderLayout;
031    import java.awt.Dimension;
032    import java.awt.Toolkit;
033    import java.awt.event.ActionEvent;
034    import java.awt.event.ActionListener;
035    import java.awt.event.ItemEvent;
036    import java.awt.event.ItemListener;
037    import java.awt.event.WindowAdapter;
038    import java.awt.event.WindowEvent;
039    import java.io.BufferedReader;
040    import java.io.File;
041    import java.io.IOException;
042    import java.io.InputStreamReader;
043    import java.util.ArrayList;
044    import java.util.Calendar;
045    import java.util.Collections;
046    import java.util.List;
047    import java.util.prefs.Preferences;
048    import javax.swing.AbstractAction;
049    import javax.swing.ActionMap;
050    import javax.swing.InputMap;
051    import javax.swing.JFrame;
052    import javax.swing.JLabel;
053    import javax.swing.JOptionPane;
054    import javax.swing.JPanel;
055    import javax.swing.KeyStroke;
056    import javax.swing.SpringLayout;
057    import org.jbudget.Core.Account;
058    import org.jbudget.Core.Budget;
059    import org.jbudget.Core.Month;
060    import org.jbudget.Core.Transaction;
061    import org.jbudget.Core.User;
062    import org.jbudget.analysis.gui.AnalysisFrame;
063    import org.jbudget.gui.budget.AccountEditorDialog;
064    import org.jbudget.gui.budget.AccountSelectorDialog;
065    import org.jbudget.gui.budget.BudgetEditor;
066    import org.jbudget.gui.budget.BudgetSelectorDialog;
067    import org.jbudget.gui.budget.wisard.BudgetWisard;
068    import org.jbudget.gui.components.HtmlDisplayDialog;
069    import org.jbudget.gui.month.DatesInfoTable;
070    import org.jbudget.gui.month.DatesInfoTableModel;
071    import org.jbudget.gui.month.MonthPanel;
072    import org.jbudget.gui.month.MonthSelectorDialog;
073    import org.jbudget.gui.trans.TransactionEditorDialog;
074    import org.jbudget.gui.user.LoginDialog;
075    import org.jbudget.gui.user.NewUserDialog;
076    import org.jbudget.gui.user.UserPreferences;
077    import org.jbudget.gui.user.UserSelectorDialog;
078    import org.jbudget.io.DataManager;
079    import org.jbudget.io.DataManager.PrefKeys;
080    import org.jbudget.io.EventDispatcher.DataSourceListener;
081    import org.jbudget.util.DateFormater;
082    import org.jbudget.util.Pair;
083    
084    /**
085     * Main Window of the program.
086     * @author petrov
087     */
088    
089    public class MainWindow  extends MainWindowBase implements DataSourceListener
090    { 
091      /** Status label */
092      private final JLabel statusLabel = new JLabel("");
093      
094      /** Ananlysi frame. Only one instance of the frame can be created. */
095      private AnalysisFrame analysisFrame = null;
096      
097      /** We assume that only one instance of MainWindow exists and it is
098       * stored in this variable. This is mostly used to get the graphics
099       * object that is used to paint the MainWindow and all its supbcomponents.
100       */
101      private static MainWindow instance;
102      
103      //============================================================================
104      //
105      //       Initialization Methods.
106      //
107      //============================================================================
108      
109      
110      /** Creates a new instance of MainWindow */
111      public MainWindow()
112      {
113        super();
114        DataManager.getInstance().setMainWindow(this);
115        
116        initializeActions();
117        
118        //=========================== Status Bar ===============================//
119        
120        SpringLayout statusBarLayout = new SpringLayout();
121        
122        JPanel statusBar = new JPanel();
123        statusBar.setLayout(statusBarLayout);
124        statusBar.add(statusLabel);
125        statusBarLayout.putConstraint(SpringLayout.WEST, statusLabel, 
126                                      20, SpringLayout.WEST, statusBar);
127        statusBar.setPreferredSize(new Dimension(200,20));
128      
129        add(statusBar, BorderLayout.SOUTH);
130        
131        statusLabel.setText(DataManager.getInstance().getIdString());
132        DataManager.getInstance().addDataSourceListener(this);
133        
134        //=========================== Window Size ===============================//
135        
136        setMinimumSize(new Dimension(400, 300));
137        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
138        setPreferredSize(new Dimension((int)(screenSize.getWidth()*3/4), 
139                                       (int)(screenSize.getHeight()*3/4)));
140        
141        //======================= Handle Window Close ===========================//
142        
143        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
144        addWindowListener(new WindowAdapter(){
145          @Override
146          public void windowClosing(WindowEvent ev){
147            exit();
148          }
149        });
150        
151        //============================ Show Frame ===============================//
152        
153        arrangeMenus();
154        pack();
155        
156        setExtendedState(JFrame.MAXIMIZED_BOTH);
157        setLocationRelativeTo(null);
158        instance = this;
159        
160        setVisible(true);
161        
162        //======================= Initialize Application ========================//
163        
164        if (DataManager.getInstance().isNewDataDir())
165            showGetStartedBox();
166        
167        changeUser();
168      }
169      
170      /** Saves everything and exits */
171      private void exit()
172      {
173        setVisible(false);
174        User currentUser = DataManager.getInstance().getCurrentUser();
175        if (currentUser != User.UNKNOWN)
176        {
177          UserPreferences preferences = currentUser.getUserPreferences();
178          if (preferences == null)
179          {
180            preferences = new UserPreferences();
181            currentUser.setUserPreferences(preferences);
182          }
183          
184          preferences.setTableState(tableState);
185          preferences.setRenderingState(renderingState);
186          preferences.setColors(colors);
187          preferences.setOpenMonths(displayedMonths);
188          DataManager.getInstance().saveUserPreferences(currentUser);
189        }
190        for (int i = 0, s = dataPane.getTabCount(); i < s; i++)
191        {
192          MonthPanel mPanel = (MonthPanel)dataPane.getComponentAt(i);
193          mPanel.dispose();
194        }
195        dispose();
196        DataManager.getInstance().close();
197        System.exit(0);
198      }
199      
200      /** Initializes actions associated with menu items and buttons */
201      private void initializeActions()
202      {
203        
204        ActionMap keysActionMap = dataPane.getActionMap();
205        InputMap keysInputMap = dataPane.getInputMap();
206        
207        //===== File Menu =======//
208        
209        keysActionMap.put("open_month", new AbstractAction("Open Month"){
210          public void actionPerformed(ActionEvent ev){
211            openExistingMonth();
212          }
213        });
214        
215        openMonthBtn.setAction(keysActionMap.get("open_month"));
216        keysInputMap.put(KeyStroke.getKeyStroke("control O"), "open_month");
217        
218        keysActionMap.put("new_month", new AbstractAction("New Month"){
219          public void actionPerformed(ActionEvent ev){
220            createNewMonth();
221          }
222        });
223        
224        addMonthBtn.addActionListener(keysActionMap.get("new_month"));
225        keysInputMap.put(KeyStroke.getKeyStroke("control N"), "new_month");
226        
227        keysActionMap.put("save_all", new AbstractAction("Save All"){
228          public void actionPerformed(ActionEvent ev){
229            DataManager.getInstance().saveAllMonths();
230          }
231        });
232        
233        saveAllBtn.addActionListener(keysActionMap.get("save_all"));
234        keysInputMap.put(KeyStroke.getKeyStroke("control S"), "save_all");
235        
236        closeAllBtn.addActionListener(new ActionListener(){
237          public void actionPerformed(ActionEvent ev){
238            DataManager.getInstance().saveAllMonths();
239            displayedMonths.clear();
240            for (int i = 0, s = dataPane.getTabCount(); i < s; i++)
241            {
242              MonthPanel mPanel = (MonthPanel)dataPane.getComponentAt(i);
243              mPanel.dispose();
244            }
245            dataPane.removeAll();
246          }
247        });
248        
249        keysActionMap.put("exit", new AbstractAction("Exit"){
250          public void actionPerformed(ActionEvent ev){
251            exit();
252          }
253        });
254        
255        exitBtn.addActionListener(keysActionMap.get("exit"));
256        keysInputMap.put(KeyStroke.getKeyStroke("control X"), "exit");
257        
258        //===== View Menu =======//
259        
260        
261        collapseAccountsBtn.addItemListener(new ItemListener(){
262          public void itemStateChanged(ItemEvent ev){
263            tableState.setExpandAccounts(
264                ev.getStateChange() == ItemEvent.DESELECTED);
265          }
266        });
267        
268        collapseCategoriesBtn.addItemListener(new ItemListener(){
269          public void itemStateChanged(ItemEvent ev){
270            tableState.setExpandCategories(
271                ev.getStateChange() == ItemEvent.DESELECTED);
272          }
273        });
274        
275        hideEmptyAccountsBtn.addItemListener(new ItemListener(){
276          public void itemStateChanged(ItemEvent ev){
277            tableState.setHideZeroBalanceAccounts(
278                ev.getStateChange() == ItemEvent.SELECTED);
279          }
280        });
281        
282        hideEmptyCategoriesBtn.addItemListener(new ItemListener(){
283          public void itemStateChanged(ItemEvent ev){
284            tableState.setHideZeroBalanceCategories(
285                ev.getStateChange() == ItemEvent.SELECTED);
286          }
287        });
288        
289        hideIdleAccountsBtn.addItemListener(new ItemListener(){
290          public void itemStateChanged(ItemEvent ev){
291            tableState.setHideInactiveAccounts(
292                ev.getStateChange() == ItemEvent.SELECTED);
293          }
294        });
295        
296        hideIdleCategoriesBtn.addItemListener(new ItemListener(){
297          public void itemStateChanged(ItemEvent ev){
298            tableState.setHideInactiveCategories(
299                ev.getStateChange() == ItemEvent.SELECTED);
300          }
301        });
302        
303       hideSubcategoriesBtn.addItemListener(new ItemListener(){
304          public void itemStateChanged(ItemEvent ev){
305            tableState.setCollapseSubcategories(
306                ev.getStateChange() == ItemEvent.SELECTED);
307          }
308        });
309        
310        detailedRendererBtn.addActionListener(new ActionListener(){
311          public void actionPerformed(ActionEvent ev){
312            renderingState.setRenderingType(DatesInfoTable.RenderingType.DETAILED);
313          }
314        });
315        
316        activityRendererBtn.addActionListener(new ActionListener(){
317          public void actionPerformed(ActionEvent ev){
318            renderingState.setRenderingType(DatesInfoTable.RenderingType.ACTIVITY);
319          }
320        });
321        
322        balanceRendererBtn.addActionListener(new ActionListener(){
323          public void actionPerformed(ActionEvent ev){
324            renderingState.setRenderingType(DatesInfoTable.RenderingType.BALANCE);
325          }
326        });
327        
328        actAndBalRendererBtn.addActionListener(new ActionListener(){
329          public void actionPerformed(ActionEvent ev){
330            renderingState.setRenderingType(DatesInfoTable.RenderingType.ACTIVITY_BALANCE);
331          }
332        });
333            
334        plainBackgrBtn.addActionListener(new ActionListener(){
335          public void actionPerformed(ActionEvent ev){
336            DatesInfoTable.BackgroundType bt = renderingState.getBackgroundType();
337            renderingState.setBackgroundType(bt.getPlain());
338          }
339        });
340        
341        stripedBackgrBtn.addActionListener(new ActionListener(){
342          public void actionPerformed(ActionEvent ev){
343            DatesInfoTable.BackgroundType bt = renderingState.getBackgroundType();
344            renderingState.setBackgroundType(bt.getStriped());
345          }
346        });
347        
348        fullStructureBackgrBtn.addActionListener(new ActionListener(){
349          public void actionPerformed(ActionEvent ev){
350            DatesInfoTable.BackgroundType bt = renderingState.getBackgroundType();
351            renderingState.setBackgroundType(bt.getStructFull());
352          }
353        });
354        
355        simpleStructureBackgrBtn.addActionListener(new ActionListener(){
356          public void actionPerformed(ActionEvent ev){
357            DatesInfoTable.BackgroundType bt = renderingState.getBackgroundType();
358            renderingState.setBackgroundType(bt.getStructSimple());
359          }
360        });
361        
362        noStructureBackgrBtn.addActionListener(new ActionListener(){
363          public void actionPerformed(ActionEvent ev){
364            DatesInfoTable.BackgroundType bt = renderingState.getBackgroundType();
365            renderingState.setBackgroundType(bt.getStructOFF());
366          }
367        });
368        
369        highltOffBtn.addActionListener(new ActionListener(){
370          public void actionPerformed(ActionEvent ev){
371            renderingState.setHighlightingType(DatesInfoTable.HighlightingType.NO_HIGHLIGHTING);
372          }
373        });
374        
375        highltUnderlBtn.addActionListener(new ActionListener(){
376          public void actionPerformed(ActionEvent ev){
377            renderingState.setHighlightingType(DatesInfoTable.HighlightingType.UDERLINE);
378          }
379        });
380        
381        //===== Month Menu =====//
382        
383        
384        saveMonthBtn.addActionListener(new ActionListener(){
385          public void actionPerformed(ActionEvent ev){
386            MonthPanel monthPanel = (MonthPanel)dataPane.getSelectedComponent();
387            if (monthPanel == null)
388              return;
389            DataManager.getInstance().saveMonth(monthPanel.getMonth());
390          }
391        });
392        
393        keysActionMap.put("close_month", new AbstractAction("Close"){
394          public void actionPerformed(ActionEvent ev){
395            closeAndSaveSelectedMonth();
396          }
397        });
398        
399        closeMonthBtn.setAction(keysActionMap.get("close_month"));
400        keysInputMap.put(KeyStroke.getKeyStroke("control W"), "close_month");
401        
402        showBudgetBtn.addActionListener(new ActionListener(){
403          public void actionPerformed(ActionEvent ev){
404            MonthPanel monthPanel = (MonthPanel)dataPane.getSelectedComponent();
405            if (monthPanel == null)
406              return;
407            new BudgetEditor(MainWindow.this, 
408                             monthPanel.getMonth().getBudget(), false);
409          }
410        });
411        
412        changeBudgetBtn.addActionListener(new ActionListener(){
413          public void actionPerformed(ActionEvent ev){
414            MonthPanel monthPanel = (MonthPanel)dataPane.getSelectedComponent();
415            if (monthPanel == null)
416              return;
417            changeBudgetForMonth(monthPanel);
418          }
419        });
420         
421        
422        addAllocationBtn.addActionListener(new ActionListener(){
423          public void actionPerformed(ActionEvent ev){
424            showAddAllocationDialog();
425          }
426        });
427        
428        keysActionMap.put("add_transaction", new AbstractAction("Add Transaction"){
429          public void actionPerformed(ActionEvent ev){
430            showAddTransactionDialog();
431          }
432        });
433        
434        addTransactionBtn.setAction(keysActionMap.get("add_transaction"));
435        keysInputMap.put(KeyStroke.getKeyStroke("control T"), "add_transaction");
436        
437        //=== Budgets Menu ====//
438        
439        viewBudgetBtn.addActionListener(new ActionListener(){
440          public void actionPerformed(ActionEvent ev){
441            showBudget();
442          }
443        });
444        
445        newBudgetBtn.addActionListener(new ActionListener(){
446          public void actionPerformed(ActionEvent ev){
447            createBudget();
448          }
449        });
450        
451        budgetWisardBtn.addActionListener(new ActionListener(){
452          public void actionPerformed(ActionEvent ev){
453            runBudgetWisard();
454          }
455        });
456        
457        removeBudgetBtn.addActionListener(new ActionListener(){
458          public void actionPerformed(ActionEvent ev){
459            removeUnusedBudget();
460          }
461        });
462        
463        removeUnusedBudgetsBtn.addActionListener(new ActionListener(){
464          public void actionPerformed(ActionEvent ev){
465            removeUnusedBudgets();
466          }
467        });
468        
469        //==== Accounts Menu ====//
470        
471        viewAccountBtn.addActionListener(new ActionListener(){
472          public void actionPerformed(ActionEvent ev){
473            showAccount();
474          }
475        });
476        
477        editAccountBtn.addActionListener(new ActionListener(){
478          public void actionPerformed(ActionEvent ev){
479            editAccount();
480          }
481        });
482        
483        newAccountBtn.addActionListener(new ActionListener(){
484          public void actionPerformed(ActionEvent ev){
485            createAccount();
486          }
487        });
488        
489        removeAccountBtn.addActionListener(new ActionListener(){
490          public void actionPerformed(ActionEvent ev){
491            removeUnusedAccount();
492          }
493        });
494        
495        removeUnusedAccountsBtn.addActionListener(new ActionListener(){
496          public void actionPerformed(ActionEvent ev){
497            removeUnusedAccounts();
498          }
499        });
500        
501        //==== Tools Menu ====//
502        
503          analysisBtn.addActionListener(new ActionListener()
504          {
505              public void actionPerformed(ActionEvent ev)
506              {
507                  if (analysisFrame != null)
508                  {
509                      if ((analysisFrame.getExtendedState() & ICONIFIED) != 0)
510                          analysisFrame.setExtendedState(NORMAL);
511                      analysisFrame.toFront();
512                  }
513                  else
514                  {
515                      analysisFrame = new AnalysisFrame(MainWindow.this);
516                      analysisFrame.addWindowListener(new WindowAdapter()
517                      {
518                          @Override
519                          public void windowClosing(WindowEvent e)
520                          {
521                              analysisFrame = null;
522                          }
523                      });
524                      analysisFrame.setVisible(true);
525                  }
526              }
527          });
528    
529          preferencesBtn.addActionListener(new ActionListener()
530          {
531              public void actionPerformed(ActionEvent ev)
532              {
533                  new PreferencesEditorDialog(MainWindow.this, true);
534              }
535          });
536        
537        //==== System Menu ====//
538        
539         keysActionMap.put("switch_user", new AbstractAction("Switch User"){
540          public void actionPerformed(ActionEvent ev){
541            changeUser();
542          }
543        });
544        
545        switchUserBtn.setAction(keysActionMap.get("switch_user"));
546        keysInputMap.put(KeyStroke.getKeyStroke("control U"), "switch_user");
547        
548        newUserBtn.addActionListener(new ActionListener(){
549          public void actionPerformed(ActionEvent ev){
550            NewUserDialog dialog = 
551                new NewUserDialog(MainWindow.this, "New User", true);
552            if (dialog.wasSelectionMade())
553            {
554              String userName = dialog.getUserName();
555              String passwd = dialog.getPasswd();
556              
557              List<Pair<Integer,String>> userData = 
558                  DataManager.getInstance().getValidUsers();
559              
560              for (Pair<Integer,String> userInfo : userData)
561                if (userInfo.second().equals(userName))
562                {
563                  JOptionPane.showMessageDialog(MainWindow.this,
564                      "User with this name already exists.", "Error", 
565                                              JOptionPane.ERROR_MESSAGE);
566                  return;
567                }
568              
569              User newUser = new User(userName, passwd);
570              
571              Account cashAccount = new Account("Cash");
572              cashAccount.addAccountHolder(newUser.getUID());
573              cashAccount.hide();
574              DataManager.getInstance().addAccount(cashAccount);
575              
576              newUser.setCashAccountID(cashAccount.getID());
577              
578              DataManager.getInstance().addUser(newUser);
579            }
580          }
581        });
582        
583        removeUserBtn.addActionListener(new ActionListener(){
584          public void actionPerformed(ActionEvent ev){
585            int uid = UserSelectorDialog.showDialog(MainWindow.this);
586            
587            User user = DataManager.getInstance().getUser(uid);
588            
589            if (user == null)
590              return;
591            
592            int cash_id = user.getCashAccountID();
593            if (cash_id >= 0)
594              DataManager.getInstance().removeAccount(cash_id);
595            
596            if (uid > 1)
597              DataManager.getInstance().removeUser(uid);
598          }
599        });
600        
601        dataDirBtn.addActionListener(new ActionListener(){
602          public void actionPerformed(ActionEvent ev){
603            File dir = DirectoryLocationDialog.showDialog(MainWindow.this);
604            if (dir != null)
605            {
606              List<Month> months = new ArrayList<Month>(displayedMonths.size());
607              months.addAll(displayedMonths);
608              for (Month month : months)
609                closeAndSaveMonth(month);
610              
611              String dataDir = dir.getAbsolutePath();
612              
613              Preferences ioPreferences = 
614                  Preferences.userNodeForPackage(DataManager.class);
615              ioPreferences.put(PrefKeys.MAIN_DIR, dataDir);
616              DataManager.getNewInstance();
617              changeUser();
618            }  
619          }
620        });
621        
622        //==== Help Menu ====//
623        
624        getStartedBtn.addActionListener(new ActionListener(){
625            public void actionPerformed(ActionEvent ev){
626                showGetStartedBox();
627            }
628        });
629        
630        aboutBtn.addActionListener(new ActionListener(){
631            public void actionPerformed(ActionEvent ev){
632                showAboutBox();
633            }
634        });
635      }
636      
637      //============================================================================
638      //
639      // Other methods.
640      //
641      //============================================================================
642      
643      /** Opens an existing month object and adds it to the data panel as a new
644       * tab. First opens a month chooser dialog and then opens the month selected
645       * by the dialog. 
646       */
647      private void openExistingMonth()
648      {
649        Pair<Integer,Integer> monthIndex = 
650            MonthSelectorDialog.showDialog(this,true);
651        if (monthIndex == null)
652          return;
653        int cMonth = monthIndex.first().intValue();
654        int cYear = monthIndex.second().intValue();
655        openMonth(cMonth, cYear);
656      }
657      
658      /** Opens an existing month object and adds it to the data panel as a new
659       * tab. 
660       */
661      private void openMonth(int cMonth, int cYear)
662      {
663        Month month = DataManager.getInstance().getMonth(cMonth, cYear);
664        if (month == null)
665          return;
666        
667        int index = Collections.binarySearch(displayedMonths, month);
668        if (index >= 0){
669            dataPane.setSelectedIndex(index);
670        } else {
671          index = -index - 1;
672          displayedMonths.add(index, month);
673          MonthPanel monthPanel = new MonthPanel(month, tableState, renderingState);
674          monthPanel.setColumnColors(this.colors);
675          String monthName = (new DateFormater()).formatMonth(month.getMonth()) + 
676              ", " + month.getYear();
677          
678          dataPane.insertTab(monthName, null, monthPanel, null, index);
679          dataPane.setSelectedIndex(index);
680          dataPane.revalidate();
681        }
682        
683        // Dealing with automatic transactions
684        synchronized(calendar)
685        {
686          calendar.setTimeInMillis(System.currentTimeMillis());
687          int currentYear = calendar.get(Calendar.YEAR);
688          int currentMonth = calendar.get(Calendar.MONTH);
689          if ((cYear < currentYear) || 
690              (cYear == currentYear && cMonth < currentMonth))
691          {
692            month.generateTransactions(31);
693          }
694          else if (cYear == currentYear && cMonth == currentMonth)
695          {
696            int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
697            month.generateTransactions(currentDay);
698          }
699        }
700      }
701      
702      /** creates a new month object and adds it to the data panel as a new
703       * tab. First opens a month chooser dialog then opens the budget chooser
704       * dialog and finally creates the new month using the budget selected by
705       * the user.
706       */
707      private void createNewMonth()
708      {
709        // get new month info
710        Pair<Integer,Integer> monthIndex = 
711            MonthSelectorDialog.showDialog(this,false);
712        if (monthIndex == null)
713            return;
714        int cMonth = monthIndex.first().intValue();
715        int cYear = monthIndex.second().intValue();
716    
717        // get budget that will be used to create the new month
718        int budgetID = BudgetSelectorDialog.showDialog(this);
719        if (budgetID == -1)
720          return;
721        Budget budget = DataManager.getInstance().getBudget(budgetID);
722        assert budget != null;
723    
724        Month month = new Month(budget, cMonth, cYear);
725    
726        int response = JOptionPane.showConfirmDialog(this, 
727            "Should the new month carry over balances from the previous month?",
728            "Carry balaces?", JOptionPane.YES_NO_OPTION);
729        if (response == JOptionPane.YES_OPTION)
730          month.setCarryBalance(true);
731    
732        DataManager.getInstance().addMonth(month);
733    
734        // Dealing with automatic transactions
735        synchronized(calendar)
736        {
737          calendar.setTimeInMillis(System.currentTimeMillis());
738          int currentYear = calendar.get(Calendar.YEAR);
739          int currentMonth = calendar.get(Calendar.MONTH);
740          if ((cYear < currentYear) || 
741              (cYear == currentYear && cMonth < currentMonth))
742          {
743            month.generateTransactions(31);
744          }
745          else if (cYear == currentYear && cMonth == currentMonth)
746          {
747            int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
748            month.generateTransactions(currentDay);
749          }
750        }
751    
752        displayedMonths.add(month);
753        MonthPanel monthPanel = new MonthPanel(month, tableState, renderingState);
754        monthPanel.setColumnColors(colors);
755        String monthName = (new DateFormater()).formatMonth(month.getMonth()) + 
756            ", " + month.getYear();
757        
758        dataPane.addTab(monthName, monthPanel);
759        dataPane.setSelectedIndex(displayedMonths.size() - 1);
760        dataPane.revalidate();
761        
762      }
763      
764      /** Returns the currently selected month (null if no moths are opened). */
765      public Month getSelectedMonth()
766      {
767          if (displayedMonths.isEmpty())
768              return null;
769          
770          return displayedMonths.get(dataPane.getSelectedIndex());
771      }
772      
773      /** changes the budget used with a given month. First opens a budget chooser
774       *  dialog to choose a new budget.
775       */
776      private void changeBudgetForMonth(MonthPanel monthPanel)
777      {
778        if (monthPanel == null)
779          return;
780        
781        Month month = monthPanel.getMonth();
782        
783        // get budget that will be used to create the new month
784        int budgetID = BudgetSelectorDialog.showDialog(this);
785        if (budgetID == -1)
786          return;
787        Budget budget = DataManager.getInstance().getBudget(budgetID);
788        assert budget != null;
789        
790        List<Transaction> incompatTrans = new ArrayList<Transaction>();
791          if (!month.isCompatible(budget, incompatTrans))
792          {
793              System.out.println(incompatTrans);
794              int answer = JOptionPane.showConfirmDialog(this,
795                      "Changing the budget for this moth to the budget that \n" +
796                      "you have selected will cause some transactions to be lost.\n" +
797                      "Do you want to proceed?", "Warning",
798                      JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
799              if (answer == JOptionPane.NO_OPTION)
800              {
801                  return;
802              }
803          }
804        
805        Month newMonth = month.changeBudget(budget);
806        
807        DataManager.getInstance().removeMonth(month.getMonth(), month.getYear());
808        DataManager.getInstance().addMonth(newMonth);
809        
810        int index = dataPane.indexOfComponent(monthPanel);
811        dataPane.remove(index);
812        displayedMonths.remove(index);
813        
814        String monthName = (new DateFormater()).formatMonth(newMonth.getMonth()) + 
815              ", " + newMonth.getYear();
816        
817        MonthPanel newPanel = new MonthPanel(newMonth, this.tableState, 
818                                                       this.renderingState);
819        newPanel.setColumnColors(this.colors);
820        dataPane.add(newPanel, index);
821        newPanel.validate();
822        
823        dataPane.setTitleAt(index, monthName);
824        dataPane.setSelectedIndex(index);
825        
826        displayedMonths.add(index,newMonth);
827      }
828      
829        /** creates a new budget */
830        private void createBudget()
831        {
832            String budgetName = JOptionPane.showInputDialog(
833                    MainWindow.this,
834                    "Enter name for the new budget.",
835                    "Budget Name",
836                    JOptionPane.QUESTION_MESSAGE);
837            if (budgetName == null || budgetName.equals("") || budgetName.equals(" "))
838            {
839                return;
840            }
841            int response = JOptionPane.NO_OPTION;
842            if (DataManager.getInstance().getValidBudgets().size() > 0)
843            {
844                response = JOptionPane.showConfirmDialog(
845                        MainWindow.this,
846                        "Do you want to initialize the new budget from an existing budget?",
847                        "Question",
848                        JOptionPane.YES_NO_OPTION,
849                        JOptionPane.QUESTION_MESSAGE);
850            }
851    
852            final Budget newBudget;
853            if (response == JOptionPane.YES_OPTION)
854            {
855                int budgetID = BudgetSelectorDialog.showDialog(this);
856                if (budgetID == -1)
857                {
858                    return;
859                }
860                Budget budget = DataManager.getInstance().getBudget(budgetID);
861                assert budget != null;
862                newBudget = new Budget(budget, budgetName);
863            } else
864            {
865                newBudget = new Budget(budgetName);
866            }
867            BudgetEditor editor = new BudgetEditor(MainWindow.this, newBudget, true);
868            editor.addOkListener(new ActionListener()
869            {
870    
871                public void actionPerformed(ActionEvent ev)
872                {
873                    DataManager.getInstance().addBudget(newBudget);
874                }
875            });
876        }
877        
878        /** creates a new budget */
879        private void runBudgetWisard()
880        {
881            String budgetName = JOptionPane.showInputDialog(
882                    MainWindow.this,
883                    "Enter name for the new budget.",
884                    "Budget Name",
885                    JOptionPane.QUESTION_MESSAGE);
886            if (budgetName == null || budgetName.equals("") || budgetName.equals(" "))
887            {
888                return;
889            }
890            int response = JOptionPane.NO_OPTION;
891            if (DataManager.getInstance().getValidBudgets().size() > 0)
892            {
893                response = JOptionPane.showConfirmDialog(
894                        MainWindow.this,
895                        "Do you want to initialize the new budget from an existing budget?",
896                        "Question",
897                        JOptionPane.YES_NO_OPTION,
898                        JOptionPane.QUESTION_MESSAGE);
899            }
900    
901            final Budget newBudget;
902            if (response == JOptionPane.YES_OPTION)
903            {
904                int budgetID = BudgetSelectorDialog.showDialog(this);
905                if (budgetID == -1)
906                {
907                    return;
908                }
909                Budget budget = DataManager.getInstance().getBudget(budgetID);
910                assert budget != null;
911                newBudget = new Budget(budget, budgetName);
912            } else
913            {
914                newBudget = new Budget(budgetName);
915            }
916            
917            BudgetWisard wisard = new BudgetWisard(MainWindow.this, newBudget);
918            
919            // TODO: FINISH ME -- Need to handle wisard result.
920        }
921      
922      /** shows a budget selection dialog and displays a selected budget */
923      private void showBudget()
924      {
925        int budgetID = BudgetSelectorDialog.showDialog(this);
926        if (budgetID == -1)
927          return;
928        Budget budget = DataManager.getInstance().getBudget(budgetID);
929        assert budget != null;
930        
931        new BudgetEditor(MainWindow.this, budget, false);
932      }
933      
934      /** shows a budget selection dialog and removes the selected budget. */
935      private void removeUnusedBudget()
936      {
937        if (DataManager.getInstance().getUnusedBudgets().isEmpty())
938        {
939          JOptionPane.showMessageDialog(this, "There are no unused budgets.", 
940              "Message", JOptionPane.INFORMATION_MESSAGE);
941          return;
942        }
943        
944        int budgetID = BudgetSelectorDialog.showDialog(this, true);
945        if (budgetID == -1)
946          return;
947            
948        assert DataManager.getInstance().isUnusedBudget(budgetID);
949        
950        DataManager.getInstance().removeBudget(budgetID);
951      }
952      
953      /** removes all unused budgets */
954      private void removeUnusedBudgets()
955      {
956        List<Pair<Integer,String>> unusedBudgets = 
957            DataManager.getInstance().getUnusedBudgets();
958        if (unusedBudgets.isEmpty())
959        {
960          JOptionPane.showMessageDialog(this, "There are no unused budgets.", 
961              "Message", JOptionPane.INFORMATION_MESSAGE);
962          return;
963        }
964        
965        int response;
966        
967        if (unusedBudgets.size() > 1)
968            response = JOptionPane.showConfirmDialog(this, "There are " +
969                unusedBudgets.size() + " unused budgets. Do you want to remove" +
970                " them?", "Confirm", JOptionPane.YES_NO_OPTION, 
971                JOptionPane.QUESTION_MESSAGE);
972        else
973            response = JOptionPane.showConfirmDialog(this, "There is one " +
974                "unused budget. Do you want to remove it?", "Confirm", 
975                JOptionPane.YES_NO_OPTION, 
976                JOptionPane.QUESTION_MESSAGE);
977        
978        if(response == JOptionPane.NO_OPTION)
979          return;
980        
981        for(Pair<Integer,String> budgetInfo : unusedBudgets)
982          DataManager.getInstance().removeBudget(budgetInfo.first().intValue());
983      }
984      
985      /** creates a new budget */
986      private void createAccount()
987      { 
988        Account newAccount = AccountEditorDialog.showDilaog(this);
989        if (newAccount != null)
990          DataManager.getInstance().addAccount(newAccount);
991      }
992      
993      /** shows a budget selection dialog and displays a selected budget */
994      private void showAccount()
995      {
996        int accountID = AccountSelectorDialog.showDialog(this);
997        if (accountID == -1)
998          return;
999        Account account = DataManager.getInstance().getAccount(accountID);
1000        assert account != null;
1001        
1002        new AccountEditorDialog(this, account, false);
1003      }
1004      
1005      /** shows a budget selection dialog and displays a selected budget */
1006      private void editAccount()
1007      {
1008        int accountID = AccountSelectorDialog.showDialog(this);
1009        if (accountID == -1)
1010          return;
1011        Account account = DataManager.getInstance().getAccount(accountID);
1012        assert account != null;
1013        
1014        new AccountEditorDialog(this, account, true);
1015      }
1016      
1017      /** shows a budget selection dialog and removes the selected budget. */
1018      private void removeUnusedAccount()
1019      {
1020        if (DataManager.getInstance().getUnusedAccounts().isEmpty())
1021        {
1022          JOptionPane.showMessageDialog(this, "There are no unused accounts.", 
1023              "Message", JOptionPane.INFORMATION_MESSAGE);
1024          return;
1025        }
1026        
1027        int accountID = AccountSelectorDialog.showDialog(this, true);
1028        if (accountID == -1)
1029          return;
1030            
1031        assert DataManager.getInstance().isUnusedAccount(accountID);
1032        
1033        DataManager.getInstance().removeAccount(accountID);
1034      }
1035      
1036      /** removes all unused budgets */
1037      private void removeUnusedAccounts()
1038      {
1039        List<Pair<Integer,String>> unusedAccounts = 
1040            DataManager.getInstance().getUnusedAccounts();
1041        if (unusedAccounts.isEmpty())
1042        {
1043          JOptionPane.showMessageDialog(this, "There are no unused account records.", 
1044              "Message", JOptionPane.INFORMATION_MESSAGE);
1045          return;
1046        }
1047        
1048        int response;
1049        
1050        if (unusedAccounts.size() > 1)
1051            response = JOptionPane.showConfirmDialog(this, "There are " +
1052                unusedAccounts.size() + " unused account records. Do you want to " +
1053                "remove them?", "Confirm", JOptionPane.YES_NO_OPTION, 
1054                JOptionPane.QUESTION_MESSAGE);
1055        else
1056            response = JOptionPane.showConfirmDialog(this, "There is one " +
1057                "unused account record. Do you want to remove it?", "Confirm", 
1058                JOptionPane.YES_NO_OPTION, 
1059                JOptionPane.QUESTION_MESSAGE);
1060        
1061        if(response == JOptionPane.NO_OPTION)
1062          return;
1063        
1064        for(Pair<Integer,String> accountInfo : unusedAccounts)
1065          DataManager.getInstance().removeAccount(accountInfo.first().intValue());
1066      }
1067      
1068      /** Prompts for a new user selection */
1069      private void changeUser()
1070      {
1071        User currentUser = DataManager.getInstance().getCurrentUser();
1072        if (currentUser != User.UNKNOWN)
1073        {
1074          UserPreferences preferences = currentUser.getUserPreferences();
1075          if (preferences == null)
1076          {
1077            preferences = new UserPreferences();
1078            currentUser.setUserPreferences(preferences);
1079          }
1080          
1081          preferences.setTableState(tableState);
1082          preferences.setRenderingState(renderingState);
1083          preferences.setColors(colors);
1084          preferences.setOpenMonths(displayedMonths);
1085          DataManager.getInstance().saveUserPreferences(currentUser);
1086        }
1087        
1088        List<Month> months = new ArrayList<Month>(displayedMonths.size());
1089        months.addAll(displayedMonths);
1090        for (Month month : months)
1091          closeAndSaveMonth(month);
1092        
1093        boolean validUser = false;
1094        
1095        // Switch to the unknown user to make sure that no transactions are 
1096        // shown when we change the user.
1097        DataManager.getInstance().setCurrentUser(User.UNKNOWN, null);
1098        
1099        while (!validUser)
1100        {
1101            LoginDialog dialog = 
1102                    new LoginDialog(MainWindow.this, "Welcome to jBudget!", true);
1103            if (dialog.wasSelectionMade())
1104            {
1105              String userName = dialog.getUserName();
1106              String passwd = dialog.getPasswd();
1107    
1108              if (!DataManager.getInstance().setCurrentUser(userName, passwd))
1109              {
1110                JOptionPane.showMessageDialog(MainWindow.this, 
1111                                            "Wrong user name or password", "Error", 
1112                                             JOptionPane.ERROR_MESSAGE);
1113                continue;
1114              }
1115              
1116              validUser = true;
1117    
1118              boolean flag = 
1119                  DataManager.getInstance().getCurrentUser() == User.SYSTEM;
1120    
1121              newUserBtn.setEnabled(flag);
1122              removeUserBtn.setEnabled(flag);
1123              editAccountBtn.setEnabled(flag);
1124              newAccountBtn.setEnabled(flag);
1125              removeAccountBtn.setEnabled(flag);
1126              removeUnusedAccountsBtn.setEnabled(flag);
1127              dataDirBtn.setEnabled(flag);
1128    
1129              UserPreferences prefs = 
1130                  DataManager.getInstance().getCurrentUser().getUserPreferences();
1131    
1132              DatesInfoTableModel.State newTableState = null;
1133              DatesInfoTable.RenderingState newRenderingState = null;
1134              DatesInfoTable.Colors newColors = null;
1135    
1136              if (prefs != null)
1137              {
1138                newTableState = prefs.getTableState();
1139                newRenderingState = prefs.getRenderingState();
1140                newColors = prefs.getColors();
1141              }
1142    
1143              if (newTableState == null)
1144                newTableState = new DatesInfoTableModel.State();
1145    
1146              if (newRenderingState == null)
1147                newRenderingState = new DatesInfoTable.RenderingState();
1148    
1149              if (newColors == null)
1150                newColors = new DatesInfoTable.Colors();
1151    
1152              changeTableState(newTableState);
1153              changeRenderingState(newRenderingState);
1154              changeColors(newColors);
1155              synchronizeMenu();
1156    
1157              if (prefs != null)
1158              {
1159                List<Pair<Integer,Integer>> monthsList = prefs.getOpenedMonths();
1160                for (Pair<Integer,Integer> monthInfo: monthsList)
1161                  openMonth(monthInfo.first().intValue(), monthInfo.second().intValue());
1162              }
1163            }
1164        }
1165      }
1166      
1167      /** Creates a dialog for a new transaction */
1168      private void showAddTransactionDialog()
1169      {
1170            calendar.setTimeInMillis(System.currentTimeMillis());
1171    
1172            if (displayedMonths.size() > 0)
1173            {
1174                int index = dataPane.getSelectedIndex();
1175                Month month = displayedMonths.get(index);
1176                if (month.getMonth() != calendar.get(Calendar.MONTH) ||
1177                        month.getYear() != calendar.get(Calendar.YEAR))
1178                    calendar.setTime(month.startingDate);
1179    
1180                List<Integer> selectedDays =
1181                        ((MonthPanel) dataPane.getSelectedComponent()).getSelectedDays();
1182                if (selectedDays.size() > 0)
1183                {
1184                    int day = selectedDays.get(0).intValue();
1185                    calendar.set(Calendar.DAY_OF_MONTH, day);
1186                }
1187            }
1188    
1189            TransactionEditorDialog dialog =
1190                    new TransactionEditorDialog(MainWindow.this, calendar.getTime(), false);
1191            dialog.setTitle("New Transaction");
1192      }
1193      
1194      /** Creates a dialog for a new allocation */
1195      private void showAddAllocationDialog()
1196      {
1197        calendar.setTimeInMillis(System.currentTimeMillis());
1198        
1199        if (displayedMonths.size() > 0)
1200        {
1201          int index = dataPane.getSelectedIndex();
1202          Month month = displayedMonths.get(index);
1203          if (month.getMonth() != calendar.get(Calendar.MONTH) || 
1204              month.getYear() != calendar.get(Calendar.YEAR))
1205          {
1206            calendar.setTime(month.startingDate);
1207          }
1208          
1209          List<Integer> selectedDays = 
1210                  ((MonthPanel)dataPane.getSelectedComponent()).getSelectedDays();
1211          
1212          if (selectedDays.size() > 0)
1213          {
1214            int day = selectedDays.get(0).intValue();
1215            calendar.set(Calendar.DAY_OF_MONTH, day);
1216          }
1217        }
1218        
1219        TransactionEditorDialog dialog = 
1220            new TransactionEditorDialog(MainWindow.this, calendar.getTime(), true);
1221        dialog.setTitle("New Allocation");
1222      }
1223      
1224      private void closeAndSaveSelectedMonth()
1225      {
1226        MonthPanel monthPanel = (MonthPanel)dataPane.getSelectedComponent();
1227        if (monthPanel == null)
1228          return;
1229        closeAndSaveMonth(monthPanel.getMonth());
1230      }
1231      
1232      /** Closes the MonthPanel associated with a given month */
1233      private void closeAndSaveMonth(Month month)
1234      {
1235        int index = displayedMonths.indexOf(month);
1236        if (index == -1)
1237          return;
1238        MonthPanel monthPanel = (MonthPanel)dataPane.getComponentAt(index);
1239        DataManager.getInstance().saveMonth(month);
1240        monthPanel.dispose();
1241        dataPane.remove(monthPanel);
1242        displayedMonths.remove(index);
1243      }
1244      
1245      private void changeTableState(DatesInfoTableModel.State tableState)
1246      {
1247        this.tableState = tableState;
1248        int nTabs = dataPane.getTabCount();
1249        for (int i = 0; i < nTabs; i++)
1250          ((MonthPanel)dataPane.getComponentAt(i)).setTableState(tableState);
1251      }
1252      
1253      private void changeRenderingState(DatesInfoTable.RenderingState renderingState)
1254      {
1255        this.renderingState = renderingState;
1256        for (int i = 0, nTabs = dataPane.getTabCount(); i < nTabs; i++)
1257          ((MonthPanel)dataPane.getComponentAt(i)).setRenderingState(renderingState);
1258      }
1259      
1260      private void changeColors(DatesInfoTable.Colors colors)
1261      {
1262        this.colors = colors;
1263        for (int i = 0, nTabs = dataPane.getTabCount(); i < nTabs; i++)
1264          ((MonthPanel)dataPane.getComponentAt(i)).setColumnColors(colors);
1265      }
1266      
1267      /** Synchronizes the View menu with the state of the <b>renderingState</b> and
1268       *<b>tableState</b> objects.
1269       */
1270      private void synchronizeMenu()
1271      {
1272        DatesInfoTable.RenderingType renderingType = renderingState.getRenderingType();
1273        detailedRendererBtn.setSelected(renderingType == DatesInfoTable.RenderingType.DETAILED);
1274        activityRendererBtn.setSelected(renderingType == DatesInfoTable.RenderingType.ACTIVITY);
1275        balanceRendererBtn.setSelected(renderingType == DatesInfoTable.RenderingType.BALANCE);
1276        actAndBalRendererBtn.setSelected(
1277            renderingType == DatesInfoTable.RenderingType.ACTIVITY_BALANCE);
1278        
1279        DatesInfoTable.BackgroundType backgrType = renderingState.getBackgroundType();
1280        plainBackgrBtn.setSelected(backgrType.isPlain());
1281        stripedBackgrBtn.setSelected(backgrType.isStriped());
1282        fullStructureBackgrBtn.setSelected(backgrType.isStructureFull());
1283        simpleStructureBackgrBtn.setSelected(backgrType.isStructureSimple());
1284        noStructureBackgrBtn.setSelected(backgrType.isStructureOFF());
1285        
1286        DatesInfoTable.HighlightingType highltType = renderingState.getHighlightingType();
1287        highltOffBtn.setSelected(highltType == DatesInfoTable.HighlightingType.NO_HIGHLIGHTING);
1288        highltUnderlBtn.setSelected(highltType == DatesInfoTable.HighlightingType.UDERLINE);
1289        
1290        collapseAccountsBtn.setSelected(!tableState.getExpandAccounts());
1291        collapseCategoriesBtn.setSelected(!tableState.getExpandCategories());
1292        hideSubcategoriesBtn.setSelected(tableState.getCollapseSubcategories());
1293        
1294        hideEmptyAccountsBtn.setSelected(tableState.getHideZeroBalanceAccounts());
1295        hideEmptyCategoriesBtn.setSelected(tableState.getHideZeroBalanceCategories());
1296        hideIdleAccountsBtn.setSelected(tableState.getHideInactiveAccounts());
1297        hideIdleCategoriesBtn.setSelected(tableState.getHideInactiveCategories());
1298        hideSubcategoriesBtn.setSelected(tableState.getCollapseSubcategories());
1299        collapseAccountsBtn.setSelected(!tableState.getExpandAccounts());
1300        collapseCategoriesBtn.setSelected(!tableState.getExpandCategories());
1301      }
1302      
1303      public void showGetStartedBox()
1304      {
1305        String message = new String("Error: Resource Not Found.");
1306        java.net.URL url = ClassLoader.getSystemResource("docs/get_started.html");
1307        if (url != null)
1308        {
1309            try
1310            {
1311                StringBuffer buf = new StringBuffer();
1312                BufferedReader reader = 
1313                    new BufferedReader(new InputStreamReader(url.openStream()));
1314                while (reader.ready())
1315                {
1316                    buf.append(reader.readLine());
1317                }
1318                message = buf.toString();
1319            } 
1320            catch (IOException ex)
1321            {
1322                message = new String("IO Error.");
1323            }
1324        }
1325        new HtmlDisplayDialog(this, "Get Started", message);
1326    }
1327      
1328      private void showAboutBox()
1329      {
1330        String message = new String("Error: Resource Not Found.");
1331        java.net.URL url = ClassLoader.getSystemResource("docs/about.html");
1332        if (url != null)
1333        {
1334            try
1335            {
1336                StringBuffer buf = new StringBuffer();
1337                BufferedReader reader = 
1338                    new BufferedReader(new InputStreamReader(url.openStream()));
1339                while (reader.ready())
1340                {
1341                    buf.append(reader.readLine());
1342                }
1343                message = buf.toString();
1344            } 
1345            catch (IOException ex)
1346            {
1347                message = new String("IO Error.");
1348            }
1349        }
1350        JOptionPane.showOptionDialog(this, message, "About jBudget",
1351        JOptionPane.DEFAULT_OPTION, 
1352        JOptionPane.PLAIN_MESSAGE, null, null, null);
1353    }
1354      
1355      /** Returns a reference to the last MainWindow object that was created. In
1356       general, there should be no reason to create more than one instance of 
1357       the MainWindow class, so this method should return a reference to the 
1358       only exiting instance.*/
1359      public static MainWindow getLastInstance()
1360      {
1361        return instance;
1362      }
1363    
1364        public void dataSourceChanged()
1365        {
1366            statusLabel.setText("Data Source:" + 
1367                                DataManager.getInstance().getIdString());
1368        }
1369      
1370    }