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     * DisplayPreferences.java
024     *
025     * Created on April 15, 2006, 2:30 PM
026     */
027    
028    package org.jbudget.gui;
029    
030    import java.awt.Color;
031    import java.awt.Font;
032    import java.util.ArrayList;
033    import java.util.Arrays;
034    import java.util.HashSet;
035    import java.util.List;
036    import java.util.Set;
037    import java.util.prefs.Preferences;
038    import javax.swing.ImageIcon;
039    import javax.swing.UIManager;
040    import javax.swing.plaf.ColorUIResource;
041    import javax.swing.plaf.FontUIResource;
042    import javax.swing.plaf.IconUIResource;
043    import org.jbudget.util.ColorParser;
044    import org.jdesktop.swingx.JXTaskPane;
045    import org.jdesktop.swingx.JXTaskPaneContainer;
046    
047    /** A class that contains the list of all preferences related
048     *  to gui functions.
049     * @author petrov
050     */
051    public class GuiPreferences
052    {
053        /** An instance of Preferences that contains the settings used in the gui
054         * package. */
055        private static final Preferences prefs =
056            Preferences.userNodeForPackage(org.jbudget.gui.GuiPreferences.class);
057        
058        /** An array of text component names. */
059        private static final String[] textComponents = 
060        { 
061            "EditorPane",
062            "FormatedTextField",
063            "List",
064            "PasswordField",
065            "Table",
066            "TextArea",
067            "TextField", 
068            "TextPane" 
069        };
070        
071        /** A list that is used to cache the keys that are set in the
072         * UIManager object when updateUIDefaults() method is called. This list is
073         * used to clear all of these keys when clearUIDefaults() is called. */
074        private static final Set<String> setKeys = new HashSet<String>();
075        
076        //============================================================================
077        //
078        //                         KEYS  AND DEFAULTS
079        //
080        //============================================================================
081        
082        // === GENERAL === //
083        
084        public static final String showEmptyDaysKey = "Show Empty Days";
085        private static final boolean showEmptyDaysDef = true;
086        
087        public static final String uiLFKey = "swing.defaultlf";
088        private static final String uiLFDefault = PreferencesEditorPanel.osDefaultLFKey;
089        
090        // === GENERAL UI COLORS === //
091        
092        public static final String generalUIColorsSelectKey = "UI.colors.select";
093        public static final boolean generalUIColorsSelectDef = false;
094        
095        public static final String generalUIFgKey = "UI.foreground";
096        public static final String generalUIFg = "0 0 0";
097        public static final String generalUIBgKey = "UI.background";
098        public static final String generalUIBg = "193 196 255";
099        public static final String generalUIControlBgKey = "control";
100        public static final String generalUIControlBgDef = "103 168 169";
101        public static final String generalUITextBgKey = "UI.Text.background";
102        public static final String generalTextUIBg = "255 255 255";
103        public static final String generalUIToolTipBgKey = "ToolTip.background";
104        public static final String generalUIToolTipBg = "255 254 167";
105        public static final String generalUIHgKey = "UI.highlight";
106        public static final String generalUIHg = "255 255 255";
107        public static final String generalUISelectionBgKey = "UI.selectionBackground";
108        public static final String generalUISelectionBg = "255 214 133";
109        
110        // === SPECIAL COLORS === //
111        
112        public static final String tableAllocBgKey = "Allocation.background";
113        public static final String tableAllocBgDef = "190 226 188";
114        public static final String tableAllocHgKey = "Allocation.highlight";
115        public static final String tableAllocHgDef = "50 255 50";
116        public static final String tableExpenseBgKey = "Expense.background";
117        public static final String tableExpenseBgDef = "255 224 174";
118        public static final String tableExpenseHgKey = "Expense.highlight";
119        public static final String tableExpenseHgDef = "255 0 100";
120        public static final String tableBgKey = "Table.background";
121        public static final String tableBgDef = "255 255 255";
122        public static final String tableAltBgKey = "Table.altBackground";
123        public static final String tableAltBgDef = "211 224 255";
124        public static final String tableFgKey = "Table.foreground";
125        public static final String tableFgDef = "0 0 0";
126        public static final String tableSelectionBgKey = "Table.selectionBackground";
127        public static final String tableSelectionBgDef = "255 214 133";
128        public static final String tableSelectionFgKey = "Table.selectionForeground";
129        public static final String tableSelectionFgDef = "0 0 0";
130        public static final String budgetAllocationKey = "BudgetEditor.Allocation.foreground";
131        public static final String budgetAllocationDef = "59 156 78";
132        public static final String budgetTransferToKey = "BudgetEditor.TransferTo.foreground";
133        public static final String budgetTransferToDef = "59 156 78";
134        public static final String budgetTransferFromKey = "BudgetEditor.TransferFrom.foreground";
135        public static final String budgetTransferFromDef = "178 26 26";
136        
137        // === ICONS === //
138        
139        public static final String iconBudgetKey = "Budget.icon";
140        private static final String iconBudgetDef = "icons/report.png";
141        public static final String iconAccountKey = "Account.con";
142        private static final String iconAccountDef = "icons/calculator.png";
143        public static final String iconExpenseCategoryKey = "ExpenseCategory.icon";
144        private static final String iconExpenseCategoryDef = "icons/package.png";
145        public static final String iconIncomeSourceKey = "IncomeSource.icon";
146        private static final String iconIncomeSourceDef = "icons/money_dollar.png";
147        public static final String iconUserKey = "User.icon";
148        private static final String iconUserDef = "icons/user.png";
149        public static final String iconUserSysKey = "Administrator.icon";
150        private static final String iconUserSysDef = "icons/user_red.png";
151        
152        public static final String iconBudgetAllocKey = "BudgetEditor.Allocation.icon";
153        private static final String iconBudgetAllocDef = "icons/money_add.png";
154        public static final String iconBudgetToKey = "BudgetEditor.TransferTo.icon";
155        private static final String iconBudgetToDef = "icons/money_add.png";
156        public static final String iconBudgetFromKey = "BudgetEditor.TransferFrom.icon";
157        private static final String iconBudgetFromDef = "icons/money_delete.png";
158        
159        // === FONTS === //
160        
161        public static final String tableFontSelectKey = "Table.font.select";
162        public static final boolean tableFontSelectDef = true;
163        public static final String tableFontKey = "Table.font";
164        public static final String tableFontDef = "Dialog-Plain-13";
165        
166        public static final String generalUIFontSelectKey = "Default.font.select";
167        public static final boolean generalUIFontSelectDef = false;
168        public static final String generalUIFontKey = "Default.font";
169        public static final String generalUIFontDef = "Dialog-Plain-13";
170        
171        public static final String toolTipFontSelectKey = "ToolTip.font.select";
172        public static final boolean toolTipFontSelectDef = false;
173        public static final String toolTipFontKey = "ToolTip.font";
174        public static final String toolTipFontDef = "Dialog-Plain-11";
175        
176        //========================== Constructor =================================//
177        
178        /** No need to create any instances of this class */
179        private GuiPreferences()
180        {}
181        
182        //======================  Interaction with L&F ======================//
183        
184        /** Installs the Look and Feel selected in the preferences. */
185        public static void installLF()
186        {
187            // get the Look and Feel specification
188            String lfSpec = get(uiLFKey, uiLFDefault);
189            String lfClassName = null;
190            
191            // Check if we want one of the installed lood and feels.
192            UIManager.LookAndFeelInfo[] installed =
193                UIManager.getInstalledLookAndFeels();
194            
195            for (UIManager.LookAndFeelInfo lfInfo : installed)
196                if (lfInfo.getName().equalsIgnoreCase(lfSpec))
197                    lfClassName = lfInfo.getClassName();
198            
199            if (lfClassName == null)
200            {
201                // Check if we want the OS default LF
202                if (PreferencesEditorPanel.osDefaultLFKey.equalsIgnoreCase(lfSpec))
203                    lfClassName = UIManager.getSystemLookAndFeelClassName();
204                else  // Use the Java default LF.
205                    lfClassName = UIManager.getCrossPlatformLookAndFeelClassName();
206            }
207            
208            try
209            {
210                if (!UIManager.getLookAndFeel().getClass().getName().equals(lfClassName))
211                    UIManager.setLookAndFeel(lfClassName);
212            }
213            catch(Exception ex)
214            {
215                System.out.println("Could not install " + lfClassName + " Look and Feel");
216            }
217            
218            // Create some SingX components to add keys to the L&F defaults.
219            new JXTaskPane();
220            new JXTaskPaneContainer();
221        }
222        
223        /** Updates the UI defaults using the values recorded in the
224         * preferences. */
225        public static void updateUIDefaults()
226        {
227            // Clear all previously set values.
228            clearUIDefaults();
229            
230            Set<Object> keys = UIManager.getLookAndFeelDefaults().keySet();
231        
232    //        for (Object key : keys)
233    //        {
234    //           if (!key.equals("Button.select"))
235    //                continue;
236    //           if (!(key instanceof String))
237    //                continue;
238    //            String keyString = (String)key;
239    //            if (!keyString.contains("Foreground"))
240    //                continue;
241    //            System.out.println("Key: " + key.toString());
242    //            Object v = UIManager.getLookAndFeelDefaults().get(key);
243    //            if (v != null)
244    //               System.out.println("Value: " + v.toString() );
245    //        }
246            
247            // Setting general colors.
248            
249            if (getBoolean(generalUIColorsSelectKey, generalUIColorsSelectDef))
250            {
251                ColorUIResource foreground =
252                    new ColorUIResource(getColor(generalUIFgKey, generalUIFg));
253                ColorUIResource disabledForeground =
254                    new ColorUIResource(new Color(foreground.getRed(),
255                    foreground.getGreen(),
256                    foreground.getBlue(),
257                    150));
258                
259                ColorUIResource background = new ColorUIResource(
260                                            getColor(generalUIBgKey, generalUIBg));
261                ColorUIResource textBg = new ColorUIResource(
262                                    getColor(generalUITextBgKey, generalTextUIBg));
263                ColorUIResource toolTipBg = new ColorUIResource(
264                              getColor(generalUIToolTipBgKey, generalUIToolTipBg));
265                ColorUIResource highlight = new ColorUIResource(
266                                            getColor(generalUIHgKey, generalUIHg));
267                ColorUIResource selectionBg = new ColorUIResource(
268                          getColor(generalUISelectionBgKey, generalUISelectionBg));
269                ColorUIResource controlBg = new ColorUIResource(
270                           getColor(generalUIControlBgKey, generalUIControlBgDef));
271                
272                ColorUIResource borderColor = 
273                    new ColorUIResource(background.darker());
274                
275                // iterate through all keys and modify colors
276                
277                for (Object key : keys)
278                {
279                    if (key instanceof String)
280                    {
281                        String stringKey = (String)key;
282                        int dotIndex = stringKey.indexOf('.');
283                        if (dotIndex < 0)
284                            continue;
285                        String componentName = stringKey.substring(0, dotIndex);
286                        if (Arrays.binarySearch(textComponents, componentName) >= 0)
287                        {
288                            if (stringKey.endsWith("foreground"))
289                                UIManager_put(stringKey, foreground);
290                            else if (stringKey.endsWith("background"))
291                                UIManager_put(stringKey, textBg);
292                            else if (stringKey.endsWith("selectionForeground"))
293                                UIManager_put(stringKey, foreground);
294                            else if (stringKey.endsWith("selectionBackground"))
295                                UIManager_put(stringKey, selectionBg);
296                        }
297                        else
298                        {
299                            if (stringKey.endsWith("foreground"))
300                                UIManager_put(stringKey, foreground);
301                            else if (stringKey.endsWith("background"))
302                                UIManager_put(stringKey, background);
303                            else if (stringKey.endsWith("highlight"))
304                                UIManager_put(stringKey, highlight);
305                            else if (stringKey.endsWith("disabledForeground"))
306                                UIManager_put(stringKey, disabledForeground);
307                            else if (stringKey.endsWith("disabledBackground"))
308                                UIManager_put(stringKey, background);
309                            else if (stringKey.endsWith("selected"))
310                                UIManager_put(stringKey, controlBg);
311                            else if (stringKey.endsWith("selectHighlight"))
312                                UIManager_put(stringKey, highlight);
313                            else if (stringKey.endsWith("unselectedBackground"))
314                                UIManager_put(stringKey, background);
315                        } 
316                        if (stringKey.endsWith("borderColor"))
317                                UIManager_put(stringKey, borderColor);
318                        if (stringKey.endsWith("contentAreaColor"))
319                                UIManager_put(stringKey, background);
320                    }
321                }
322                
323                // Set up the tooltip color.
324                Color opaqueToolTipColor =
325                    getColor(generalUIToolTipBgKey, generalUIToolTipBg);
326                UIManager_put(generalUIToolTipBgKey,
327                    new Color(opaqueToolTipColor.getRed(),
328                    opaqueToolTipColor.getGreen(),
329                    opaqueToolTipColor.getBlue(), 200));
330                setKeys.add(generalUIToolTipBgKey);
331                
332                // Setup the control elemet colors.
333                UIManager_put(generalUIControlBgKey, controlBg);
334                setKeys.add(generalUIControlBgKey);
335                
336                List<Object> gradientSpec = new ArrayList<Object>();
337                gradientSpec.add(new Float(0.3));
338                gradientSpec.add(new Float(0.0));
339                gradientSpec.add(controlBg);
340                gradientSpec.add(highlight);
341                gradientSpec.add(controlBg);
342                
343                for (Object key : keys)
344                {
345                    if (key instanceof String)
346                    {
347                        String strKey = (String)key;
348                        if (strKey.endsWith("gradient"))
349                        {
350                            UIManager_put(strKey, gradientSpec);
351                            setKeys.add(strKey);
352                        }
353                    }
354                }
355            }
356            
357            // Setting specialized colors.
358            
359            UIManager_put(tableAllocBgKey,
360                new ColorUIResource(getColor(tableAllocBgKey, tableAllocBgDef)));
361            UIManager_put(tableAllocHgKey,
362                new ColorUIResource(getColor(tableAllocHgKey, tableAllocHgDef)));
363            UIManager_put(tableExpenseBgKey,
364                new ColorUIResource(getColor(tableExpenseBgKey, tableExpenseBgDef)));
365            UIManager_put(tableExpenseHgKey,
366                new ColorUIResource(getColor(tableExpenseHgKey, tableExpenseHgDef)));
367            UIManager_put(tableBgKey,
368                new ColorUIResource(getColor(tableBgKey, tableBgDef)));
369            UIManager_put(tableAltBgKey,
370                new ColorUIResource(getColor(tableAltBgKey, tableAltBgDef)));
371            UIManager_put(tableFgKey,
372                new ColorUIResource(getColor(tableFgKey, tableFgDef)));
373            UIManager_put(tableSelectionBgKey,
374                new ColorUIResource(getColor(tableSelectionBgKey, tableSelectionBgDef)));
375            UIManager_put(tableSelectionFgKey,
376                new ColorUIResource(getColor(tableSelectionFgKey, tableSelectionFgDef)));
377            UIManager_put(budgetAllocationKey,
378                new ColorUIResource(getColor(budgetAllocationKey, budgetAllocationDef)));
379            UIManager_put(budgetTransferToKey,
380                new ColorUIResource(getColor(budgetTransferToKey, budgetTransferToDef)));
381            UIManager_put(budgetTransferFromKey,
382                new ColorUIResource(getColor(budgetTransferFromKey, budgetTransferFromDef)));
383            
384            
385            // setting Icons
386            
387            UIManager_put(iconBudgetKey,
388                new IconUIResource(getIcon(iconBudgetKey, iconBudgetDef)));
389            UIManager_put(iconAccountKey,
390                new IconUIResource(getIcon(iconAccountKey, iconAccountDef)));
391            UIManager_put(iconExpenseCategoryKey,
392                new IconUIResource(getIcon(iconExpenseCategoryKey, iconExpenseCategoryDef)));
393            UIManager_put(iconIncomeSourceKey,
394                new IconUIResource(getIcon(iconIncomeSourceKey, iconIncomeSourceDef)));
395            UIManager_put(iconUserKey,
396                new IconUIResource(getIcon(iconUserKey, iconUserDef)));
397            UIManager_put(iconUserSysKey,
398                new IconUIResource(getIcon(iconUserSysKey, iconUserSysDef)));
399            UIManager_put(iconBudgetAllocKey,
400                new IconUIResource(getIcon(iconBudgetAllocKey, iconBudgetAllocDef)));
401            UIManager_put(iconBudgetToKey,
402                new IconUIResource(getIcon(iconBudgetToKey, iconBudgetToDef)));
403            UIManager_put(iconBudgetFromKey,
404                new IconUIResource(getIcon(iconBudgetFromKey, iconBudgetFromDef)));
405            
406            // Set General GUI fonts
407            if (getBoolean(generalUIFontSelectKey, generalUIFontSelectDef))
408            {
409                // Change all fonts except the table fonts that are
410                // handled separately.
411                FontUIResource font =
412                    new FontUIResource(getFont(generalUIFontKey, generalUIFontDef));
413                for (Object key : keys)
414                    if (key instanceof String)
415                    {
416                        String stringKey = (String)key;
417                        if (stringKey.equals(tableFontKey))
418                            continue;
419                        if (stringKey.endsWith("font"))
420                            UIManager_put(stringKey, font);
421                    }
422            }
423            
424            // Set Table Fonts
425            if (getBoolean(tableFontSelectKey, tableFontSelectDef))
426            {
427                UIManager_put(tableFontKey,
428                    new FontUIResource(getFont(tableFontKey, tableFontDef)));
429            }
430        }
431        
432        /** Sets all values associated with keys known by the GuiPreferences
433         * ot null values. */
434        private static void clearUIDefaults()
435        {
436            for(String key : setKeys)
437                UIManager.put(key, null);
438            setKeys.clear();
439        }
440        
441        /** Wrapper for the UIManager_put method. */
442        private static void UIManager_put(String key, Object value)
443        {
444            UIManager.put(key, value);
445            setKeys.add(key);
446        }
447        
448        //====================== Accessors ==================================//
449        
450        /** Shall we show empty days in the table. An empty day has no transactions*/
451        public static boolean getShowEmptyDays()
452        {
453            return prefs.getBoolean(showEmptyDaysKey, showEmptyDaysDef);
454        }
455        
456        /** Sets the empty days flag. @see getShowEmptyDays */
457        public static void setShowEmptyDays(boolean showEmptyDays)
458        {
459            prefs.putBoolean(showEmptyDaysKey,showEmptyDays);
460        }
461        
462        /** Stores a string key/value pair in the preferences. */
463        public static void put(String key, String value)
464        {
465            prefs.put(key, value);
466        }
467        
468        /** Returns a string value stored in the preferences. */
469        public static String get(String key, String def)
470        {
471            return prefs.get(key, def);
472        }
473        
474        //=========================================================================//
475        //                                                                         //
476        //                        COLORS                                           //
477        //                                                                         //
478        //=========================================================================//
479        
480        /** Returns a color for a given key. If the color is not available or if it is
481         *  can not be parsed, the default value is returned.
482         */
483        public static Color getColor(String key, String def)
484        {
485            Color color;
486            try
487            {
488                color = ColorParser.parse(prefs.get(key,def));
489            }
490            catch (IllegalArgumentException ex)
491            {
492                color = ColorParser.parse(def);
493                set(key, ColorParser.colorToString(color));
494            }
495            return color;
496        }
497        
498        /** Records the color associated with a given string key. */
499        public static void setColor(String key, Color color)
500        {
501            set(key, ColorParser.colorToString(color));
502        }
503        
504        /** puts a given value into preferences table. */
505        private static void set(String key, String value)
506        {
507            prefs.put(key, value);
508        }
509        
510        //=========================================================================//
511        //                                                                         //
512        //                        FONTS                                            //
513        //                                                                         //
514        //=========================================================================//
515        
516        public static Font getFont(String fontKey, String fontDef)
517        {
518            return Font.decode(prefs.get(fontKey, fontDef));
519        }
520        
521        /** Changes the value of the base font */
522        public static void setFont(String fontKey, Font font)
523        {
524            String fontValue = font.getFamily() + "-";
525            if (font.isPlain())
526                fontValue += "Plain-";
527            else if (font.isBold())
528                fontValue += "Bold-";
529            else
530                fontValue += "Italic-";
531            fontValue += Integer.toString(font.getSize());
532            prefs.put(fontKey, fontValue);
533        }
534        
535        
536        //=========================================================================//
537        //                                                                         //
538        //                        ICONS                                            //
539        //                                                                         //
540        //=========================================================================//
541        
542        /** Returns a color for a given key. If the color is not available or if it is
543         *  can not be parsed, the default value is returned.
544         */
545        private static ImageIcon getIcon(String key, String def)
546        {
547            return createImageIcon(prefs.get(key,def), key);
548        }
549        
550        //=========================================================================//
551        //                                                                         //
552        //                        Boolean                                          //
553        //                                                                         //
554        //=========================================================================//
555        
556        /** Returns a boolean value for a given key. */
557        public static boolean getBoolean(String key, boolean def)
558        {
559            return prefs.getBoolean(key, def);
560        }
561        
562        /** Sets a boolean value for a given key. */
563        public static void setBoolean(String key, boolean value)
564        {
565            prefs.putBoolean(key, value);
566        }
567        
568        //=========================================================================//
569        //                                                                         //
570        //                        UTILITIES                                        //
571        //                                                                         //
572        //=========================================================================//
573        
574        /** Returns an ImageIcon, or null if the path was invalid. */
575        protected static ImageIcon createImageIcon(String path,
576                                                   String description)
577        {
578            java.net.URL imgURL = ClassLoader.getSystemResource(path);
579            if (imgURL == null)
580            {
581                System.err.println("Couldn't find file: " + path);
582                return new ImageIcon();
583            }
584            return new ImageIcon(imgURL, description);
585        }
586        
587    }