329050090760b5518227f879f35a9fafcd2f52b7
[jalview.git] / src / jalview / gui / UserDefinedColours.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.bin.Cache;
24 import jalview.io.JalviewFileChooser;
25 import jalview.io.JalviewFileView;
26 import jalview.jbgui.GUserDefinedColours;
27 import jalview.schemabinding.version2.Colour;
28 import jalview.schemabinding.version2.JalviewUserColours;
29 import jalview.schemes.ColourSchemeI;
30 import jalview.schemes.ColourSchemeLoader;
31 import jalview.schemes.ColourSchemes;
32 import jalview.schemes.ResidueProperties;
33 import jalview.schemes.UserColourScheme;
34 import jalview.util.ColorUtils;
35 import jalview.util.Format;
36 import jalview.util.MessageManager;
37
38 import java.awt.Color;
39 import java.awt.Font;
40 import java.awt.Insets;
41 import java.awt.event.MouseAdapter;
42 import java.awt.event.MouseEvent;
43 import java.io.File;
44 import java.io.FileOutputStream;
45 import java.io.OutputStreamWriter;
46 import java.io.PrintWriter;
47 import java.util.ArrayList;
48 import java.util.List;
49
50 import javax.swing.JButton;
51 import javax.swing.JInternalFrame;
52 import javax.swing.event.ChangeEvent;
53 import javax.swing.event.ChangeListener;
54
55 /**
56  * This panel allows the user to assign colours to Amino Acid residue codes, and
57  * save the colour scheme.
58  * 
59  * @author Andrew Waterhouse
60  * @author Mungo Carstairs
61  */
62 public class UserDefinedColours extends GUserDefinedColours
63         implements ChangeListener
64 {
65   private static final Font VERDANA_BOLD_10 = new Font("Verdana", Font.BOLD,
66           10);
67
68   public static final String USER_DEFINED_COLOURS = "USER_DEFINED_COLOURS";
69
70   private static final String LAST_DIRECTORY = "LAST_DIRECTORY";
71
72   private static final int MY_FRAME_HEIGHT = 440;
73
74   private static final int MY_FRAME_WIDTH = 810;
75
76   private static final int MY_FRAME_WIDTH_CASE_SENSITIVE = 970;
77
78   AlignmentPanel ap;
79
80   /*
81    * the colour scheme when the dialog was opened, or
82    * the scheme last saved to file
83    */
84   ColourSchemeI oldColourScheme;
85
86   /*
87    * flag is true if the colour scheme has been changed since the
88    * dialog was opened, or the changes last saved to file
89    */
90   boolean changed;
91
92   JInternalFrame frame;
93
94   List<JButton> upperCaseButtons;
95
96   List<JButton> lowerCaseButtons;
97
98   /**
99    * Creates and displays a new UserDefinedColours panel
100    * 
101    * @param alignPanel
102    */
103   public UserDefinedColours(AlignmentPanel alignPanel)
104   {
105     this();
106
107     lcaseColour.setEnabled(false);
108
109     this.ap = alignPanel;
110
111     oldColourScheme = alignPanel.av.getGlobalColourScheme();
112
113     if (oldColourScheme instanceof UserColourScheme)
114     {
115       schemeName.setText(oldColourScheme.getSchemeName());
116       if (((UserColourScheme) oldColourScheme)
117               .getLowerCaseColours() != null)
118       {
119         caseSensitive.setSelected(true);
120         lcaseColour.setEnabled(true);
121         resetButtonPanel(true);
122       }
123       else
124       {
125         resetButtonPanel(false);
126       }
127     }
128     else
129     {
130       resetButtonPanel(false);
131     }
132
133     showFrame();
134   }
135
136   UserDefinedColours()
137   {
138     super();
139     selectedButtons = new ArrayList<>();
140   }
141
142   void showFrame()
143   {
144     colorChooser.getSelectionModel().addChangeListener(this);
145     frame = new JInternalFrame();
146     frame.setContentPane(this);
147     Desktop.addInternalFrame(frame,
148             MessageManager.getString("label.user_defined_colours"),
149             MY_FRAME_WIDTH, MY_FRAME_HEIGHT, true);
150   }
151
152   /**
153    * Rebuilds the panel with coloured buttons for residues. If not case
154    * sensitive colours, show 3-letter amino acid code as button text. If case
155    * sensitive, just show the single letter code, in order to make space for the
156    * additional buttons.
157    * 
158    * @param isCaseSensitive
159    */
160   void resetButtonPanel(boolean isCaseSensitive)
161   {
162     buttonPanel.removeAll();
163
164     if (upperCaseButtons == null)
165     {
166       upperCaseButtons = new ArrayList<>();
167     }
168
169     for (int i = 0; i < 20; i++)
170     {
171       String label = isCaseSensitive ? ResidueProperties.aa[i]
172               : ResidueProperties.aa2Triplet.get(ResidueProperties.aa[i])
173                       .toString();
174       JButton button = makeButton(label, ResidueProperties.aa[i],
175               upperCaseButtons, i);
176       buttonPanel.add(button);
177     }
178
179     buttonPanel.add(makeButton("B", "B", upperCaseButtons, 20));
180     buttonPanel.add(makeButton("Z", "Z", upperCaseButtons, 21));
181     buttonPanel.add(makeButton("X", "X", upperCaseButtons, 22));
182     buttonPanel.add(makeButton("Gap", "-", upperCaseButtons, 23));
183
184     if (!isCaseSensitive)
185     {
186       gridLayout.setRows(6);
187       gridLayout.setColumns(4);
188     }
189     else
190     {
191       gridLayout.setRows(7);
192       int cols = 7;
193       gridLayout.setColumns(cols + 1);
194
195       if (lowerCaseButtons == null)
196       {
197         lowerCaseButtons = new ArrayList<>();
198       }
199
200       for (int i = 0; i < 20; i++)
201       {
202         int row = i / cols + 1;
203         int index = (row * cols) + i;
204         JButton button = makeButton(ResidueProperties.aa[i].toLowerCase(),
205                 ResidueProperties.aa[i].toLowerCase(), lowerCaseButtons, i);
206
207         buttonPanel.add(button, index);
208       }
209     }
210
211     if (isCaseSensitive)
212     {
213       buttonPanel.add(makeButton("b", "b", lowerCaseButtons, 20));
214       buttonPanel.add(makeButton("z", "z", lowerCaseButtons, 21));
215       buttonPanel.add(makeButton("x", "x", lowerCaseButtons, 22));
216     }
217
218     // JAL-1360 widen the frame dynamically to accommodate case-sensitive AA
219     // codes
220     if (this.frame != null)
221     {
222       int newWidth = isCaseSensitive ? MY_FRAME_WIDTH_CASE_SENSITIVE
223               : MY_FRAME_WIDTH;
224       this.frame.setSize(newWidth, this.frame.getHeight());
225     }
226
227     buttonPanel.validate();
228     validate();
229   }
230
231   /**
232    * ChangeListener handler for when a colour is picked in the colour chooser.
233    * The action is to apply the colour to all selected buttons as their
234    * background colour. Foreground colour (text) is set to a lighter shade in
235    * order to highlight which buttons are selected. If 'Lower Case Colour' is
236    * active, then the colour is applied to all lower case buttons (as well as
237    * the Lower Case Colour button itself).
238    * 
239    * @param evt
240    */
241   @Override
242   public void stateChanged(ChangeEvent evt)
243   {
244     JButton button = null;
245     final Color newColour = colorChooser.getColor();
246     if (lcaseColour.isSelected())
247     {
248       selectedButtons.clear();
249       for (int i = 0; i < lowerCaseButtons.size(); i++)
250       {
251         button = lowerCaseButtons.get(i);
252         button.setBackground(newColour);
253         button.setForeground(
254                 ColorUtils.brighterThan(button.getBackground()));
255       }
256     }
257     for (int i = 0; i < selectedButtons.size(); i++)
258     {
259       button = selectedButtons.get(i);
260       button.setBackground(newColour);
261       button.setForeground(ColorUtils.brighterThan(newColour));
262     }
263
264     changed = true;
265   }
266
267   /**
268    * Performs actions when a residue button is clicked. This manages the button
269    * selection set (highlighted by brighter foreground text).
270    * <p>
271    * On select button(s) with Ctrl/click or Shift/click: set button foreground
272    * text to brighter than background.
273    * <p>
274    * On unselect button(s) with Ctrl/click on selected, or click to release
275    * current selection: reset foreground text to darker than background.
276    * <p>
277    * Simple click: clear selection (resetting foreground to darker); set clicked
278    * button foreground to brighter
279    * <p>
280    * Finally, synchronize the colour chooser to the colour of the first button
281    * in the selected set.
282    * 
283    * @param e
284    */
285   public void colourButtonPressed(MouseEvent e)
286   {
287     JButton pressed = (JButton) e.getSource();
288
289     if (e.isShiftDown())
290     {
291       JButton start, end = (JButton) e.getSource();
292       if (selectedButtons.size() > 0)
293       {
294         start = selectedButtons.get(selectedButtons.size() - 1);
295       }
296       else
297       {
298         start = (JButton) e.getSource();
299       }
300
301       int startIndex = 0, endIndex = 0;
302       for (int b = 0; b < buttonPanel.getComponentCount(); b++)
303       {
304         if (buttonPanel.getComponent(b) == start)
305         {
306           startIndex = b;
307         }
308         if (buttonPanel.getComponent(b) == end)
309         {
310           endIndex = b;
311         }
312       }
313
314       if (startIndex > endIndex)
315       {
316         int temp = startIndex;
317         startIndex = endIndex;
318         endIndex = temp;
319       }
320
321       for (int b = startIndex; b <= endIndex; b++)
322       {
323         JButton button = (JButton) buttonPanel.getComponent(b);
324         if (!selectedButtons.contains(button))
325         {
326           button.setForeground(
327                   ColorUtils.brighterThan(button.getBackground()));
328           selectedButtons.add(button);
329         }
330       }
331     }
332     else if (!e.isControlDown())
333     {
334       for (int b = 0; b < selectedButtons.size(); b++)
335       {
336         JButton button = selectedButtons.get(b);
337         button.setForeground(ColorUtils.darkerThan(button.getBackground()));
338       }
339       selectedButtons.clear();
340       pressed.setForeground(
341               ColorUtils.brighterThan(pressed.getBackground()));
342       selectedButtons.add(pressed);
343
344     }
345     else if (e.isControlDown())
346     {
347       if (selectedButtons.contains(pressed))
348       {
349         pressed.setForeground(
350                 ColorUtils.darkerThan(pressed.getBackground()));
351         selectedButtons.remove(pressed);
352       }
353       else
354       {
355         pressed.setForeground(
356                 ColorUtils.brighterThan(pressed.getBackground()));
357         selectedButtons.add(pressed);
358       }
359     }
360
361     if (selectedButtons.size() > 0)
362     {
363       colorChooser.setColor((selectedButtons.get(0)).getBackground());
364     }
365   }
366
367   /**
368    * A helper method to update or make a colour button, whose background colour
369    * is the associated colour, and text colour a darker shade of the same. If
370    * the button is already in the list, then its text and margins are updated,
371    * if not then it is created and added. This method supports toggling between
372    * case-sensitive and case-insensitive button panels. The case-sensitive
373    * version has abbreviated button text in order to fit in more buttons.
374    * 
375    * @param label
376    * @param residue
377    * @param the
378    *          list of buttons
379    * @param buttonIndex
380    *          the button's position in the list
381    */
382   JButton makeButton(String label, String residue, List<JButton> buttons,
383           int buttonIndex)
384   {
385     final JButton button;
386     Color col;
387
388     if (buttonIndex < buttons.size())
389     {
390       button = buttons.get(buttonIndex);
391       col = button.getBackground();
392     }
393     else
394     {
395       button = new JButton();
396       button.addMouseListener(new MouseAdapter()
397       {
398         @Override
399         public void mouseClicked(MouseEvent e)
400         {
401           colourButtonPressed(e);
402         }
403       });
404
405       buttons.add(button);
406
407       /*
408        * make initial button colour that of the current colour scheme,
409        * if it is a simple per-residue colouring, else white
410        */
411       col = Color.white;
412       if (oldColourScheme != null && oldColourScheme.isSimple())
413       {
414         col = oldColourScheme.findColour(residue.charAt(0), 0, null, null,
415                 0f);
416       }
417     }
418
419     if (caseSensitive.isSelected())
420     {
421       button.setMargin(new Insets(2, 2, 2, 2));
422     }
423     else
424     {
425       button.setMargin(new Insets(2, 14, 2, 14));
426     }
427
428     button.setOpaque(true); // required for the next line to have effect
429     button.setBackground(col);
430     button.setText(label);
431     button.setForeground(ColorUtils.darkerThan(col));
432     button.setFont(VERDANA_BOLD_10);
433
434     return button;
435   }
436
437   /**
438    * On 'OK', check that at least one colour has been assigned to a residue (and
439    * if not issue a warning), and apply the chosen colour scheme and close the
440    * panel.
441    */
442   @Override
443   protected void okButton_actionPerformed()
444   {
445     if (isNoSelectionMade())
446     {
447       JvOptionPane.showMessageDialog(Desktop.desktop,
448               MessageManager
449                       .getString("label.no_colour_selection_in_scheme"),
450               MessageManager.getString("label.no_colour_selection_warn"),
451               JvOptionPane.WARNING_MESSAGE);
452     }
453     else
454     {
455       /*
456        * OK is treated as 'apply colours and close'
457        */
458       applyButton_actionPerformed();
459
460       /*
461        * If editing a named colour scheme, warn if changes
462        * have not been saved
463        */
464       warnIfUnsavedChanges();
465
466       try
467       {
468         frame.setClosed(true);
469       } catch (Exception ex)
470       {
471       }
472     }
473   }
474
475   /**
476    * If we have made changes to an existing user defined colour scheme but not
477    * saved them, show a dialog with the option to save. If the user chooses to
478    * save, do so, else clear the colour scheme name to indicate a new colour
479    * scheme.
480    */
481   protected void warnIfUnsavedChanges()
482   {
483     if (!changed)
484     {
485       return;
486     }
487
488     String name = schemeName.getText().trim();
489     if (oldColourScheme != null && !"".equals(name)
490             && name.equals(oldColourScheme.getSchemeName()))
491     {
492       String message = MessageManager.formatMessage("label.scheme_changed",
493               name);
494       String title = MessageManager.getString("label.save_changes");
495       String[] options = new String[] { title,
496           MessageManager.getString("label.dont_save_changes"), };
497       final String question = JvSwingUtils.wrapTooltip(true, message);
498       int response = JvOptionPane.showOptionDialog(Desktop.desktop,
499               question, title, JvOptionPane.DEFAULT_OPTION,
500               JvOptionPane.PLAIN_MESSAGE, null, options, options[0]);
501
502       boolean saved = false;
503       if (response == 0)
504       {
505         /*
506          * prompt to save changes to file
507          */
508         saved = savebutton_actionPerformed();
509       }
510
511       /*
512        * if user chooses not to save (either in this dialog or in the
513        * save as dialogs), treat this as a new user defined colour scheme
514        */
515       if (!saved)
516       {
517         /*
518          * clear scheme name and re-apply as an anonymous scheme
519          */
520         schemeName.setText("");
521         applyButton_actionPerformed();
522       }
523     }
524   }
525
526   /**
527    * Returns true if the user has not made any colour selection (including if
528    * 'case-sensitive' selected and no lower-case colour chosen).
529    * 
530    * @return
531    */
532   protected boolean isNoSelectionMade()
533   {
534     final boolean noUpperCaseSelected = upperCaseButtons == null
535             || upperCaseButtons.isEmpty();
536     final boolean noLowerCaseSelected = caseSensitive.isSelected()
537             && (lowerCaseButtons == null || lowerCaseButtons.isEmpty());
538     final boolean noSelectionMade = noUpperCaseSelected
539             || noLowerCaseSelected;
540     return noSelectionMade;
541   }
542
543   /**
544    * Applies the current colour scheme to the alignment or sequence group
545    */
546   @Override
547   protected void applyButton_actionPerformed()
548   {
549     if (isNoSelectionMade())
550     {
551       JvOptionPane.showMessageDialog(Desktop.desktop,
552               MessageManager
553                       .getString("label.no_colour_selection_in_scheme"),
554               MessageManager.getString("label.no_colour_selection_warn"),
555               JvOptionPane.WARNING_MESSAGE);
556
557     }
558     UserColourScheme ucs = getSchemeFromButtons();
559
560     ap.alignFrame.changeColour(ucs);
561   }
562
563   /**
564    * Constructs an instance of UserColourScheme with the residue colours
565    * currently set on the buttons on the panel
566    * 
567    * @return
568    */
569   UserColourScheme getSchemeFromButtons()
570   {
571
572     Color[] newColours = new Color[24];
573
574     int length = upperCaseButtons.size();
575     if (length < 24)
576     {
577       int i = 0;
578       for (JButton btn : upperCaseButtons)
579       {
580         newColours[i] = btn.getBackground();
581         i++;
582       }
583     }
584     else
585     {
586       for (int i = 0; i < 24; i++)
587       {
588         JButton button = upperCaseButtons.get(i);
589         newColours[i] = button.getBackground();
590       }
591     }
592
593     UserColourScheme ucs = new UserColourScheme(newColours);
594     ucs.setName(schemeName.getText());
595
596     if (caseSensitive.isSelected())
597     {
598       newColours = new Color[23];
599       length = lowerCaseButtons.size();
600       if (length < 23)
601       {
602         int i = 0;
603         for (JButton btn : lowerCaseButtons)
604         {
605           newColours[i] = btn.getBackground();
606           i++;
607         }
608       }
609       else
610       {
611         for (int i = 0; i < 23; i++)
612         {
613           JButton button = lowerCaseButtons.get(i);
614           newColours[i] = button.getBackground();
615         }
616       }
617       ucs.setLowerCaseColours(newColours);
618     }
619
620     return ucs;
621   }
622
623   /**
624    * Action on clicking Load scheme button.
625    * <ul>
626    * <li>Open a file chooser to browse for files with extension .jc</li>
627    * <li>Load in the colour scheme and transfer it to this panel's buttons</li>
628    * <li>Register the loaded colour scheme</li>
629    * </ul>
630    */
631   @Override
632   protected void loadbutton_actionPerformed()
633   {
634     upperCaseButtons = new ArrayList<>();
635     lowerCaseButtons = new ArrayList<>();
636
637     JalviewFileChooser chooser = new JalviewFileChooser("jc",
638             "Jalview User Colours");
639     chooser.setFileView(new JalviewFileView());
640     chooser.setDialogTitle(
641             MessageManager.getString("label.load_colour_scheme"));
642     chooser.setToolTipText(MessageManager.getString("action.load"));
643
644     int value = chooser.showOpenDialog(this);
645
646     if (value != JalviewFileChooser.APPROVE_OPTION)
647     {
648       return;
649     }
650     File choice = chooser.getSelectedFile();
651     Cache.setProperty(LAST_DIRECTORY, choice.getParent());
652
653     UserColourScheme ucs = ColourSchemeLoader
654             .loadColourScheme(choice.getAbsolutePath());
655     Color[] colors = ucs.getColours();
656     schemeName.setText(ucs.getSchemeName());
657
658     if (ucs.getLowerCaseColours() != null)
659     {
660       caseSensitive.setSelected(true);
661       lcaseColour.setEnabled(true);
662       resetButtonPanel(true);
663       for (int i = 0; i < lowerCaseButtons.size(); i++)
664       {
665         JButton button = lowerCaseButtons.get(i);
666         button.setBackground(ucs.getLowerCaseColours()[i]);
667       }
668     }
669     else
670     {
671       caseSensitive.setSelected(false);
672       lcaseColour.setEnabled(false);
673       resetButtonPanel(false);
674     }
675
676     for (int i = 0; i < upperCaseButtons.size(); i++)
677     {
678       JButton button = upperCaseButtons.get(i);
679       button.setBackground(colors[i]);
680     }
681
682     addNewColourScheme(choice.getPath());
683   }
684
685   /**
686    * Loads the user-defined colour scheme from the first file listed in property
687    * "USER_DEFINED_COLOURS". If this fails, returns an all-white colour scheme.
688    * 
689    * @return
690    */
691   public static UserColourScheme loadDefaultColours()
692   {
693     UserColourScheme ret = null;
694
695     String colours = Cache.getProperty(USER_DEFINED_COLOURS);
696     if (colours != null)
697     {
698       if (colours.indexOf("|") > -1)
699       {
700         colours = colours.substring(0, colours.indexOf("|"));
701       }
702       ret = ColourSchemeLoader.loadColourScheme(colours);
703     }
704
705     if (ret == null)
706     {
707       ret = new UserColourScheme("white");
708     }
709
710     return ret;
711   }
712
713   /**
714    * Action on pressing the Save button.
715    * <ul>
716    * <li>Check a name has been entered</li>
717    * <li>Warn if the name already exists, remove any existing scheme of the same
718    * name if overwriting</li>
719    * <li>Do the standard file chooser thing to write with extension .jc</li>
720    * <li>If saving changes (possibly not yet applied) to the currently selected
721    * colour scheme, then apply the changes, as it is too late to back out
722    * now</li>
723    * <li>Don't apply the changes if the currently selected scheme is different,
724    * to allow a new scheme to be configured and saved but not applied</li>
725    * </ul>
726    * Returns true if the scheme is saved to file, false if it is not
727    * 
728    * @return
729    */
730   @Override
731   protected boolean savebutton_actionPerformed()
732   {
733     String name = schemeName.getText().trim();
734     if (name.length() < 1)
735     {
736       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
737               MessageManager
738                       .getString("label.user_colour_scheme_must_have_name"),
739               MessageManager.getString("label.no_name_colour_scheme"),
740               JvOptionPane.WARNING_MESSAGE);
741       return false;
742     }
743
744     if (ColourSchemes.getInstance().nameExists(name))
745     {
746       int reply = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
747               MessageManager.formatMessage(
748                       "label.colour_scheme_exists_overwrite", new Object[]
749                       { name, name }),
750               MessageManager.getString("label.duplicate_scheme_name"),
751               JvOptionPane.YES_NO_OPTION);
752       if (reply != JvOptionPane.YES_OPTION)
753       {
754         return false;
755       }
756     }
757     JalviewFileChooser chooser = new JalviewFileChooser("jc",
758             "Jalview User Colours");
759
760     JalviewFileView fileView = new JalviewFileView();
761     chooser.setFileView(fileView);
762     chooser.setDialogTitle(
763             MessageManager.getString("label.save_colour_scheme"));
764     chooser.setToolTipText(MessageManager.getString("action.save"));
765
766     int value = chooser.showSaveDialog(this);
767
768     if (value != JalviewFileChooser.APPROVE_OPTION)
769     {
770       return false;
771     }
772
773     File file = chooser.getSelectedFile();
774     UserColourScheme updatedScheme = addNewColourScheme(file.getPath());
775     saveToFile(file);
776     changed = false;
777
778     /*
779      * changes saved - apply to alignment if we are changing 
780      * the currently selected colour scheme; also make the updated
781      * colours the 'backout' scheme on Cancel
782      */
783     if (oldColourScheme != null
784             && name.equals(oldColourScheme.getSchemeName()))
785     {
786       oldColourScheme = updatedScheme;
787       applyButton_actionPerformed();
788     }
789     return true;
790   }
791
792   /**
793    * Adds the current colour scheme to the Jalview properties file so it is
794    * loaded on next startup, and updates the Colour menu in the parent
795    * AlignFrame (if there is one). Note this action does not including applying
796    * the colour scheme.
797    * 
798    * @param filePath
799    * @return
800    */
801   protected UserColourScheme addNewColourScheme(String filePath)
802   {
803     /*
804      * update the delimited list of user defined colour files in
805      * Jalview property USER_DEFINED_COLOURS
806      */
807     String defaultColours = Cache.getDefault(USER_DEFINED_COLOURS,
808             filePath);
809     if (defaultColours.indexOf(filePath) == -1)
810     {
811       if (defaultColours.length() > 0)
812       {
813         defaultColours = defaultColours.concat("|");
814       }
815       defaultColours = defaultColours.concat(filePath);
816     }
817     Cache.setProperty(USER_DEFINED_COLOURS, defaultColours);
818
819     /*
820      * construct and register the colour scheme
821      */
822     UserColourScheme ucs = getSchemeFromButtons();
823     ColourSchemes.getInstance().registerColourScheme(ucs);
824
825     /*
826      * update the Colour menu items
827      */
828     if (ap != null)
829     {
830       ap.alignFrame.buildColourMenu();
831     }
832
833     return ucs;
834   }
835
836   /**
837    * Saves the colour scheme to file in XML format
838    * 
839    * @param path
840    */
841   protected void saveToFile(File toFile)
842   {
843     /*
844      * build a Java model of colour scheme as XML, and 
845      * marshal to file
846      */
847     JalviewUserColours ucs = new JalviewUserColours();
848     String name = schemeName.getText();
849     ucs.setSchemeName(name);
850     try
851     {
852       PrintWriter out = new PrintWriter(new OutputStreamWriter(
853               new FileOutputStream(toFile), "UTF-8"));
854
855       for (int i = 0; i < buttonPanel.getComponentCount(); i++)
856       {
857         JButton button = (JButton) buttonPanel.getComponent(i);
858         Colour col = new Colour();
859         col.setName(button.getText());
860         col.setRGB(Format.getHexString(button.getBackground()));
861         ucs.addColour(col);
862       }
863       ucs.marshal(out);
864       out.close();
865     } catch (Exception ex)
866     {
867       ex.printStackTrace();
868     }
869   }
870
871   /**
872    * On cancel, restores the colour scheme that was selected before the dialogue
873    * was opened
874    */
875   @Override
876   protected void cancelButton_actionPerformed()
877   {
878     ap.alignFrame.changeColour(oldColourScheme);
879     ap.paintAlignment(true, true);
880
881     try
882     {
883       frame.setClosed(true);
884     } catch (Exception ex)
885     {
886     }
887   }
888
889   /**
890    * Action on selecting or deselecting the Case Sensitive option. When
891    * selected, separate buttons are shown for lower case residues, and the panel
892    * is resized to accommodate them. Also, the checkbox for 'apply colour to all
893    * lower case' is enabled.
894    */
895   @Override
896   public void caseSensitive_actionPerformed()
897   {
898     boolean selected = caseSensitive.isSelected();
899     resetButtonPanel(selected);
900     lcaseColour.setEnabled(selected);
901   }
902 }