Debian Codegraph @

laf-widget/src/main/java/org/pushingpixels/lafwidget/LAFAdapter.java

raw
1 package org.pushingpixels.lafwidget;
2
3 import java.awt.EventQueue;
4 import java.util.Set;
5 import javax.swing.*;
6 import java.beans.*;
7 import javax.swing.plaf.ComponentUI;
8
9 import org.pushingpixels.lafwidget.*;
10
11 public class LAFAdapter {
12 /**The listener for global LAF changes.*/
13 private static ReinitListener reinitListener;
14 /**The listener for component LAF updates.*/
15 private static InternalUIListener internalListener;
16 /**Have we already initialised?*/
17 private static boolean initialised=false;
18 /**The table of delegate classes for the current LAF.*/
19 private static UIDefaults uiDelegates;
20 /**The list of all UI classes.
21 *Taken from https://laf-widget.dev.java.net/docs/all-component-ui-ids.txt
22 */
23 private final static String[] UI_CLASSNAMES={
24 "ButtonUI","CheckBoxUI","CheckBoxMenuItemUI","ColorChooserUI","ComboBoxUI","DesktopIconUI",
25 "DesktopPaneUI","EditorPaneUI","FormattedTextFieldUI","InternalFrameUI","LabelUI","ListUI","MenuUI",
26 "MenuBarUI","MenuItemUI","OptionPaneUI","PanelUI","PasswordFieldUI","PopupMenuUI","PopupMenuSeparatorUI",
27 "ProgressBarUI","RadioButtonUI","RadioButtonMenuItemUI","RootPaneUI","ScrollBarUI","ScrollPaneUI",
28 "SeparatorUI","SliderUI","SpinnerUI","SplitPaneUI","TabbedPaneUI","TableUI","TableHeaderUI","TextAreaUI",
29 "TextFieldUI","TextPaneUI","ToggleButtonUI","ToolBarUI","ToolBarSeparatorUI","ToolTipUI","TreeUI","ViewportUI"};
30 private final static String LAF_PROPERTY = "Widgeted_LAFS";
31
32 /**Returns the UI as normal, but intercepts the call, so a
33 * listener can be attached. This is called internally from Swing code
34 * to create the UI delegate for a component.
35 *<b>THIS METHOD SHOULDN'T BE CALLED FROM USER CODE!</b>
36 */
37 public static ComponentUI createUI(JComponent c) {
38 if (c == null || initialised == false) //something isn't right -> bail
39 return null;
40 //Now we use the same discovery mechanism to find the real createUI method
41 ComponentUI uiObject = uiDelegates.getUI(c);
42 //System.out.println("Creating UI: "+c.getClass()+" "+Integer.toHexString(System.identityHashCode(c)));
43 uninstallLafWidgets(c);
44 //here we need to check we don't add a second listener. This happens
45 //if createUI gets called a second time, as when creating JDesktopIcons
46 if (!isPropertyListening(c))
47 c.addPropertyChangeListener("UI",internalListener);
48 return uiObject; //return the actual UI delegate
49 }
50
51 /**Tests if the property listener has already been attached to a component
52 *@param c the component to check
53 *@return true if the listener is already present
54 */
55 private static boolean isPropertyListening(JComponent c) {
56 PropertyChangeListener[] pc=c.getPropertyChangeListeners();
57 if (pc.length==0) //common-case
58 return false;
59 for (int i=0,ilen=pc.length;i<ilen;i++) {
60 //Property listeners are usually proxied but test explicitly just in case
61 if (pc[i] instanceof PropertyChangeListenerProxy &&
62 ((PropertyChangeListenerProxy)pc[i]).getListener()==internalListener)
63 return true;
64 else if (pc[i]==internalListener)
65 return true;
66 }
67 return false;
68 }
69
70 private static class InternalUIListener implements PropertyChangeListener {
71 /**UI can change at any point, so we need to listen for these
72 * events. This property fires AFTER the UI change.
73 */
74 @Override
75 public void propertyChange(PropertyChangeEvent evt) {
76 JComponent c=(JComponent)evt.getSource();
77 // Remove old listeners that was installed when createUI was called
78 c.removePropertyChangeListener("UI",internalListener);
79 installLafWidgets(c); //here we do the install on the LAF
80 }
81 }
82
83 /**Installs the available LAF-Widgets onto the given JComponent
84 *and adds a mapping to the set of widgeted components if any were found.
85 *If the LAF indicates it is self-widgeting then nothing is done.
86 *@param c the component to widgetise
87 */
88 private static void installLafWidgets(JComponent c) {
89 //test if this LAF uses needs LAFWidget integration
90 if (LafWidgetRepository.getRepository().getLafSupport()
91 .getClass().equals(LafWidgetSupport.class)) {
92 Set<LafWidget> lafWidgets=LafWidgetRepository.getRepository().getMatchingWidgets(c);
93 if (lafWidgets.size()>0) {//if a new UI has been set
94 for (LafWidget lw : lafWidgets) {
95 lw.installUI();
96 lw.installComponents();
97 lw.installDefaults();
98 lw.installListeners();
99 }
100 c.putClientProperty(LAF_PROPERTY,lafWidgets); //stash the list of installed widgets
101 }
102 }
103 }
104
105 /**Removes any installed widgets from the component shown. If a mapping
106 *exists which indicates this component had widgets installed then they
107 *are removed here and the mapping also removed.
108 *@param c the component to uninstall widgets from
109 */
110 private static void uninstallLafWidgets(JComponent c) {
111 //if there were previously widgets installed, then uninstall them
112 Set<LafWidget> lafWidgets=(Set<LafWidget>)c.getClientProperty(LAF_PROPERTY);
113 if (lafWidgets!=null) {
114 for (LafWidget lw : lafWidgets) {
115 lw.uninstallListeners();
116 lw.uninstallDefaults();
117 lw.uninstallComponents();
118 lw.uninstallUI();
119 }
120 c.putClientProperty(LAF_PROPERTY,null); //remove widget set
121 }
122 }
123
124 /**This initialises the Widgeting system. All future components created will
125 *be widgeted. This code maybe called from any thread and ensures that the
126 *actual initialisation is done on the Event Thread. If called from another thread,
127 *this method will block until the initialisation is complete.
128 */
129 public static void startWidget() {
130 widget(true);
131 }
132
133 /**This tears-down the widgeting system. Calling this method prevents any
134 *further components being widgetised. Any existing components with widgets
135 *will continue to have them. All system hooks will be removed and the widgeting
136 *system will stop attaching to new components. This method is safe to call
137 *from any thread, as the work will be done on the Event Thread. If called from
138 *another thread, this method will block until the initialisation is complete.
139 */
140 public static void stopWidget() {
141 widget(false);
142 }
143
144 /**Private helper to start or stop the widgeting. EDT checks present here.
145 *@param enable whether to start or stop the widgeting
146 */
147 private static void widget(boolean enable) {
148 Init init = new Init(enable);
149 if (EventQueue.isDispatchThread()) {
150 init.run();
151 } else {// This code must run on the EDT for data visibility reasons
152 try {
153 EventQueue.invokeAndWait(init);
154 } catch (Exception e) {
155 throw new RuntimeException(e);
156 }
157 }
158 }
159
160 /**Inserts all the substitute LAF pairs into the UIDefaults table. This also
161 *places a LAF change listener on the UIManager. This is to cause a re-initialisation
162 *when the LAF changes so new components created after a global LAF change will
163 *still get widgets.
164 */
165 private static class Init implements Runnable {
166 /**Sets whether we should be setting up or tearing down the widgeting.*/
167 private final boolean enable; //final so it doesn't matter where this initialises from (JSR-133)
168
169 private Init(final boolean enable) {
170 this.enable=enable;
171 }
172
173 @Override
174 public void run() {
175 if (!EventQueue.isDispatchThread())
176 throw new IllegalStateException("This must be run on the EDT");
177 try { //do the setup process or removal process
178 if (enable)
179 setup();
180 else
181 tearDown();
182 } catch (Exception e) {
183 initialised=false;
184 uiDelegates=null;
185 internalListener=null;
186 reinitListener=null;
187 throw new RuntimeException(e);
188 }
189 }
190
191 public static void setup() throws Exception {
192 //check we don't initialise twice
193 if (initialised)
194 return;
195 //We use the LAF defaults table so we don't mess with the developer
196 //table
197 reinitListener = new ReinitListener();
198 internalListener = new InternalUIListener();
199 uiDelegates=new UIDefaults(); //stores the actual UI delegates
200 UIDefaults defaults = UIManager.getLookAndFeelDefaults();
201 //Store the class for each delegate locally and replace the Swing delegate
202 for (String uiClassID : UI_CLASSNAMES) {
203 uiDelegates.put(uiClassID,defaults.getString(uiClassID));
204 defaults.put(uiClassID,LAFAdapter.class.getName());
205 }
206 //listen for global LAF changes
207 UIManager.addPropertyChangeListener(reinitListener);
208 initialised=true;
209 }
210
211 public static void tearDown() throws Exception {
212 if (!initialised)
213 return;
214 UIManager.removePropertyChangeListener(reinitListener);
215 //reset the current UI which will overwrite all our values
216 UIManager.setLookAndFeel(UIManager.getLookAndFeel());
217 uiDelegates=null;
218 reinitListener=null;
219 internalListener=null;
220 initialised=false;
221 }
222 }
223
224 /**
225 * Listens for Look and Feel changes and re-initialises the
226 * class. This fires from UIManager after a LAF change.
227 */
228 private static class ReinitListener implements PropertyChangeListener {
229 @Override
230 public void propertyChange(PropertyChangeEvent evt) {
231 if ("lookAndFeel".equals(evt.getPropertyName())) {
232 // The look and feel was changed so we need to re-insert
233 // our hook into the new UIDefaults map, first de-initialise
234 // Don't want to call tearDown() as we're already in a LAF change.
235 UIManager.removePropertyChangeListener(reinitListener);
236 initialised=false;
237 uiDelegates=null;
238 reinitListener=null;
239 internalListener=null;
240 startWidget();
241 }
242 }
243 }
244 }