You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InputAction.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*
  2. * Copyright (c) 2006-2013 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.addons.ui_swing.cinch;
  23. import com.dmdirc.addons.ui_swing.dialogs.StandardInputDialog;
  24. import com.dmdirc.util.validators.PermissiveValidator;
  25. import com.dmdirc.util.validators.Validator;
  26. import com.google.common.collect.ImmutableList;
  27. import com.palantir.ptoss.cinch.core.Bindable;
  28. import com.palantir.ptoss.cinch.core.BindableModel;
  29. import com.palantir.ptoss.cinch.core.Binding;
  30. import com.palantir.ptoss.cinch.core.BindingContext;
  31. import com.palantir.ptoss.cinch.core.BindingException;
  32. import com.palantir.ptoss.cinch.core.BindingWiring;
  33. import com.palantir.ptoss.cinch.core.Bindings;
  34. import com.palantir.ptoss.cinch.core.ObjectFieldMethod;
  35. import com.palantir.ptoss.cinch.swing.Action;
  36. import com.palantir.ptoss.util.Throwables;
  37. import java.awt.Dialog.ModalityType;
  38. import java.awt.Window;
  39. import java.awt.event.ActionEvent;
  40. import java.awt.event.ActionListener;
  41. import java.lang.annotation.ElementType;
  42. import java.lang.annotation.Retention;
  43. import java.lang.annotation.RetentionPolicy;
  44. import java.lang.annotation.Target;
  45. import java.lang.reflect.Constructor;
  46. import java.lang.reflect.Field;
  47. import java.lang.reflect.InvocationTargetException;
  48. import java.lang.reflect.Method;
  49. import java.util.Collection;
  50. import java.util.List;
  51. import javax.swing.AbstractButton;
  52. import org.apache.log4j.Logger;
  53. /**
  54. * This action is essentially copied from
  55. * {@link com.palantir.ptoss.cinch.swing.Action} except it asks the user for
  56. * a information before performing the action.
  57. */
  58. @Retention(RetentionPolicy.RUNTIME)
  59. @Target({ElementType.FIELD})
  60. public @interface InputAction {
  61. /**
  62. * The name of the method to call when the action occurs. Must be accessible
  63. * in the
  64. * {@link BindingContext}.
  65. *
  66. * @return Method to call when action occurs.
  67. */
  68. String call();
  69. /**
  70. * Message to be displayed in the confirmation dialog.
  71. *
  72. * @return Message
  73. */
  74. String message() default "Fill in the following:";
  75. /**
  76. * Class name of the validator to use in the input dialog.
  77. *
  78. * @return Validator class name
  79. */
  80. Class<?> validator() default PermissiveValidator.class;
  81. /**
  82. * The name of the method to call to get the display text.
  83. *
  84. * @return method to call to get display text
  85. */
  86. String content() default "";
  87. /**
  88. * Inner utility class used to wire {@link Action} bindings.
  89. */
  90. static class Wiring implements BindingWiring {
  91. private static final Logger LOGGER = Logger.getLogger(InputAction.class);
  92. /**
  93. * Wires all {@link Action} bindings in the passed context.
  94. * Called by {@link Bindings#createBindings(BindingContext)} as part of
  95. * runtime wiring process.
  96. *
  97. * @param context Binding context
  98. *
  99. * @return Collection of bindings for this wiring
  100. */
  101. @Override
  102. public Collection<Binding> wire(final BindingContext context) {
  103. final List<Field> actions = context.getAnnotatedFields(InputAction.class);
  104. for (final Field field : actions) {
  105. final InputAction action = field.getAnnotation(InputAction.class);
  106. try {
  107. wire(action.call(), action.message(), action.content(),
  108. action.validator(), field, context);
  109. } catch (final Exception e) {
  110. Throwables.throwUncheckedException(e);
  111. throw new BindingException("could not wire up "
  112. + "@InputAction on " + field.getName(), e);
  113. }
  114. }
  115. return ImmutableList.of();
  116. }
  117. /**
  118. * Wires up to any object with an addActionListener method.
  119. * Automatically called by {@link #wire(BindingContext)}.
  120. *
  121. * @param call name of an {@link ObjectFieldMethod} in the passed {@link BindingContext}.
  122. * @param message Message to be displayed to the user
  123. * @param field field to bind the call to.
  124. * @param context the {@link BindingContext}
  125. */
  126. @SuppressWarnings("unchecked")
  127. private static void wire(final String call, final String message,
  128. final String existing, final Class<?> validator,
  129. final Field field, final BindingContext context)
  130. throws SecurityException, NoSuchMethodException,
  131. IllegalArgumentException, IllegalAccessException,
  132. InvocationTargetException, ClassNotFoundException,
  133. InstantiationException {
  134. final Method aalMethod = field.getType().getMethod(
  135. "addActionListener", ActionListener.class);
  136. final Object actionObject = context.getFieldObject(
  137. field, Object.class);
  138. final List<Field> fields = context.getAnnotatedFields(
  139. Bindable.class);
  140. final Object object = context.getFieldObject(fields.get(0),
  141. Object.class);
  142. final Method method = fields.get(0).getType().getMethod(call,
  143. String.class);
  144. final ObjectFieldMethod existingMethod;
  145. if (!existing.isEmpty()) {
  146. existingMethod = context.getBindableMethod(existing);
  147. if (existingMethod == null) {
  148. throw new BindingException("could not find bindable "
  149. + "method: " + existing);
  150. }
  151. } else {
  152. existingMethod = null;
  153. }
  154. final ObjectFieldMethod ofm = new ObjectFieldMethod(object,
  155. fields.get(0), method);
  156. if (ofm == null) {
  157. throw new BindingException("could not find bindable method: "
  158. + call);
  159. }
  160. final Validator<String> validatorInstance;
  161. final Constructor<?> ctor = validator.getConstructor(
  162. BindableModel.class);
  163. validatorInstance = (Validator<String>) ctor.newInstance(
  164. context.getBindableModels().toArray()[0]);
  165. aalMethod.invoke(actionObject, new ActionListener() {
  166. /** {@inheritDoc} */
  167. @Override
  168. public void actionPerformed(final ActionEvent e) {
  169. new StandardInputDialog(null,
  170. (Window) ((AbstractButton) actionObject)
  171. .getTopLevelAncestor(), ModalityType.DOCUMENT_MODAL,
  172. "Input", message, validatorInstance) {
  173. /**
  174. * Serial Version UID.
  175. */
  176. private static final long serialVersionUID = 1;
  177. /**
  178. * {@inheritDoc}
  179. */
  180. @Override
  181. public boolean save() {
  182. try {
  183. final boolean accessible = ofm.getMethod()
  184. .isAccessible();
  185. ofm.getMethod().setAccessible(true);
  186. ofm.getMethod().invoke(ofm.getObject(), getText());
  187. ofm.getMethod().setAccessible(accessible);
  188. } catch (final InvocationTargetException itex) {
  189. LOGGER.error("exception during action firing",
  190. itex.getCause());
  191. } catch (final Exception ex) {
  192. LOGGER.error("exception during action firing", ex);
  193. }
  194. return true;
  195. }
  196. /**
  197. * {@inheritDoc}
  198. */
  199. @Override
  200. public void display() {
  201. String content;
  202. if (existingMethod != null) {
  203. try {
  204. final boolean accessible = existingMethod
  205. .getMethod().isAccessible();
  206. existingMethod.getMethod().setAccessible(true);
  207. content = (String) existingMethod.getMethod()
  208. .invoke(existingMethod.getObject());
  209. existingMethod.getMethod()
  210. .setAccessible(accessible);
  211. } catch (final Exception e) {
  212. content = "";
  213. }
  214. } else {
  215. content = "";
  216. }
  217. setText(content);
  218. super.display();
  219. }
  220. /**
  221. * {@inheritDoc}
  222. */
  223. @Override
  224. public void cancelled() {
  225. //Ignore
  226. }
  227. }.display();
  228. }
  229. });
  230. }
  231. }
  232. }