View Javadoc
1   /**
2    * This file Copyright (c) 2013-2015 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.ui.form.field.factory;
35  
36  import static com.google.common.base.Enums.getIfPresent;
37  import static org.apache.commons.io.FilenameUtils.getExtension;
38  import static org.apache.commons.lang3.StringUtils.isNotBlank;
39  import static org.vaadin.aceeditor.AceMode.forFileEnding;
40  
41  import info.magnolia.context.MgnlContext;
42  import info.magnolia.ui.form.field.definition.CodeFieldDefinition;
43  
44  import org.vaadin.aceeditor.AceEditor;
45  import org.vaadin.aceeditor.AceMode;
46  
47  import com.google.common.base.Optional;
48  import com.vaadin.data.Item;
49  import com.vaadin.data.Property;
50  import com.vaadin.event.FieldEvents.TextChangeEvent;
51  import com.vaadin.event.FieldEvents.TextChangeListener;
52  import com.vaadin.server.Sizeable.Unit;
53  import com.vaadin.ui.Field;
54  
55  /**
56   * Creates and initializes a code field, based on the {@link AceEditor} add-on for Vaadin.
57   */
58  public class CodeFieldFactory extends AbstractFieldFactory<CodeFieldDefinition, String> {
59  
60      private static final String FREEMARKER_LANGUAGE = "freemarker";
61      private static final String ACE_EDITOR_FTL_ID = "ftl";
62      private static final String ACE_EDITOR_RESOURCES = "/.resources/ace/";
63  
64      private AceEditor field;
65  
66      public CodeFieldFactory(CodeFieldDefinition definition, Item relatedFieldItem) {
67          super(definition, relatedFieldItem);
68      }
69  
70      @Override
71      protected Field<String> createFieldComponent() {
72          field = newAceEditor();
73          // Add a TextChange Listener. This is needed as the current AceEditor implementation do not update the
74          // linked datasource in case of text change.
75          field.addTextChangeListener(createTextChangeListener(field));
76          // Set style
77          field.setStyleName("textcodefield");
78          field.setUseWorker(false);
79  
80          return field;
81      }
82  
83      /**
84       * @return newly constructed {@link AceEditor}.
85       */
86      protected AceEditor newAceEditor() {
87          AceEditor aceEditor = new AceEditor();
88          if (MgnlContext.isWebContext()) {
89              String aceEditorResourcePath = MgnlContext.getContextPath() + ACE_EDITOR_RESOURCES;
90              aceEditor.setModePath(aceEditorResourcePath);
91              aceEditor.setWorkerPath(aceEditorResourcePath);
92              aceEditor.setThemePath(aceEditorResourcePath);
93          }
94          // If language is set, then we don't want to conflict with it.
95          if (isNotBlank(definition.getLanguage())) {
96              aceEditor.setMode(getModeType(definition.getLanguage()));
97          } else if (isNotBlank(definition.getFileNameProperty())) {
98              Property<?> fileNameProperty = item.getItemProperty(definition.getFileNameProperty());
99              if (fileNameProperty != null) {
100                 String fileName = String.valueOf(fileNameProperty.getValue());
101                 String extension = getExtension(fileName);
102                 AceMode mode = getAceModeByFileExtension(extension);
103                 if (mode != null) {
104                     aceEditor.setMode(mode);
105                 }
106             }
107         }
108         if (definition.getHeight() > 0) {
109             aceEditor.setHeight(definition.getHeight(), Unit.PIXELS);
110         }
111         return aceEditor;
112     }
113 
114     /**
115      * Create a {@link TextChangeListener} in order to populate the typed text in the
116      * related property datasource.
117      */
118     private TextChangeListener createTextChangeListener(final AceEditor field) {
119         return new TextChangeListener() {
120 
121             @SuppressWarnings("unchecked")
122             @Override
123             public void textChange(TextChangeEvent event) {
124                 field.getPropertyDataSource().setValue(event.getText());
125             }
126         };
127     }
128 
129     /**
130      * Get Ace-editor compliant mode type name for a language.
131      *
132      * TODO: currently only 'freemarker' -> 'ftl' case is handled, otherwise the method returns the string from definition.
133      * If needed we could craft our own mapping from human-readable language names into the Ace editor mode identifiers.
134      */
135     private String getModeType(String language) {
136         return FREEMARKER_LANGUAGE.equals(language) ? ACE_EDITOR_FTL_ID : language;
137     }
138 
139     /**
140      * Get the {@link AceMode} by file extension.
141      * <p>
142      * First tries to match the given extension against an AceMode value, otherwise looks into AceMode's additional mappings (<code>endingModeMap</code>).
143      */
144     private AceMode getAceModeByFileExtension(String extension) {
145         // Trying the get AceMode from the Enum
146         Optional<AceMode> aceModeValue = getIfPresent(AceMode.class, extension);
147         if (aceModeValue.isPresent()) {
148             return aceModeValue.get();
149         } else {
150             // Trying to get AceMode from the AceMode.endingModeMap
151             AceMode aceMode = forFileEnding(extension);
152             return aceMode != null ? aceMode : null;
153         }
154     }
155 
156 }