View Javadoc

1   /**
2    * This file Copyright (c) 2011 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.templating.editor.client.jsni;
35  
36  
37  import info.magnolia.templating.editor.client.PageEditor;
38  import info.magnolia.templating.editor.client.dom.MgnlElement;
39  
40  import com.google.gwt.core.client.GWT;
41  import com.google.gwt.dom.client.Document;
42  import com.google.gwt.dom.client.Element;
43  import com.google.gwt.dom.client.MetaElement;
44  import com.google.gwt.dom.client.NodeList;
45  import com.google.gwt.http.client.UrlBuilder;
46  import com.google.gwt.i18n.client.Dictionary;
47  import com.google.gwt.user.client.Cookies;
48  import com.google.gwt.user.client.Window;
49  
50  /**
51   * A JSNI wrapper around native javascript functions found in general.js, inline.js and others plus some utilities.
52   * @version $Id$
53   *
54   */
55  public final class JavascriptUtils {
56  
57      private static Dictionary dictionary;
58  
59      private static String windowLocation;
60  
61      public static String getWindowLocation() {
62          return windowLocation;
63      }
64  
65      public static void setWindowLocation(String windowLocation) {
66          JavascriptUtils.windowLocation = windowLocation;
67      }
68  
69      private final static String EDITOR_COOKIE_PATH = "/";
70      private final static String EDITOR_COOKIE_NAMESPACE = "editor-";
71      private final static String editorPositionCookieName = EDITOR_COOKIE_NAMESPACE + "position-";
72      private final static String editorContentIdCookieName = EDITOR_COOKIE_NAMESPACE + "content-id-";
73  
74      static {
75          //TODO move messages we need to this module?
76          JavascriptUtils.exposeMgnlMessagesToGwtDictionary("info.magnolia.module.admininterface.messages");
77          dictionary = Dictionary.getDictionary("mgnlGwtMessages");
78      }
79  
80      private JavascriptUtils() {
81          //do not instantiate it.
82      }
83  
84      public static native void mgnlOpenDialog(String path, String collectionName, String nodeName, String paragraph, String workspace, String dialogPage, String width, String height, String locale) /*-{
85          $wnd.mgnlOpenDialog(path, collectionName, nodeName, paragraph, workspace, dialogPage, width, height, locale);
86      }-*/;
87  
88      public static native void mgnlMoveNodeStart(String id) /*-{
89          $wnd.mgnlMoveNodeStart('',id,'__'+id);
90      }-*/;
91  
92      public static native void mgnlMoveNodeHigh(Object source) /*-{
93          $wnd.mgnlMoveNodeHigh(source);
94      }-*/;
95  
96      public static native void mgnlMoveNodeEnd(Object source, String path) /*-{
97          $wnd.mgnlMoveNodeEnd(source, path);
98      }-*/;
99  
100     public static native void mgnlMoveNodeReset(Object source) /*-{
101         $wnd.mgnlMoveNodeReset(source);
102     }-*/;
103 
104     public static native void mgnlDeleteNode(String path) /*-{
105         $wnd.mgnlDeleteNode(path,'', '');
106     }-*/;
107 
108     /**
109      * Exposes the messages object corresponding to the passed in basename as a global (thus accessible by GWT Dictionary) variable named <em>mgnlGwtMessages</em>.
110      */
111     public static native void exposeMgnlMessagesToGwtDictionary(String basename) /*-{
112         $wnd.mgnlGwtMessages = $wnd.mgnlMessages.messages[basename];
113     }-*/;
114 
115     public static native void showTree(String workspace, String path) /*-{
116         $wnd.MgnlAdminCentral.showTree(workspace, path)
117     }-*/;
118 
119     public static native String getContextPath() /*-{
120         return $wnd.location.protocol + "//"+ $wnd.location.host + $wnd.contextPath + "/"
121     }-*/;
122 
123     public static boolean isNotEmpty(final String string) {
124         return !isEmpty(string);
125     }
126 
127     public static boolean isEmpty(final String string) {
128         return string == null || string.length() == 0;
129     }
130 
131     /**
132      * This method will look for the specified key inside a GWT {@link Dictionary} named <code>mgnlGwtMessages</code>. If the key does not exist it will return a string
133      * in the form <code>???missing.key???</code>. The keys looked for must reside in <code>info.magnolia.module.admininterface.messages</code> and
134      * MUST end with the special suffix <code>.js</code> (i.e. <code>my.cool.i18nkey.js</code>).
135      * <p><strong>WARNING: this way of exposing i18n messages to GWT is very likely to change in 5.0</strong>
136      */
137     public static String getI18nMessage(final String key) {
138         try {
139             return dictionary.get(key);
140         } catch(RuntimeException e) {
141             GWT.log("key ["+ key +"] was not found in dictionary", e);
142             return "???" + key + "???";
143         }
144     }
145 
146     /**
147      * A String representing the value for the GWT meta property whose content is <em>locale</em>.
148      * See also <a href='http://code.google.com/webtoolkit/doc/latest/DevGuideI18nLocale.html#LocaleSpecifying'>GWT Dev Guide to i18n</a>
149      */
150     public static String detectCurrentLocale() {
151         String locale = "en";
152         final NodeList<Element> meta = Document.get().getDocumentElement().getElementsByTagName("meta");
153         for (int i = 0; i < meta.getLength(); i++) {
154             MetaElement metaTag = MetaElement.as(meta.getItem(i));
155             if ("gwt:property".equals(metaTag.getName()) && metaTag.getContent().contains("locale")) {
156                 String[] split = metaTag.getContent().split("=");
157                 locale = split.length == 2 ? split[1] : "en";
158                 GWT.log("Detected Locale " + locale);
159                 break;
160             }
161         }
162         return locale;
163     }
164 
165     public static void moveComponent(String idTarget, String idSource, String path, String order) {
166         if(isEmpty(idTarget) || isEmpty(idSource) || isEmpty(path) || idTarget.equals(idSource)) {
167             return;
168         }
169         String pathSource = path+"//"+idSource;
170         String pathTarget = path+"//"+idTarget;
171 
172         UrlBuilder urlBuilder = Window.Location.createUrlBuilder();
173         urlBuilder.removeParameter("mgnlIntercept");
174         urlBuilder.removeParameter("mgnlPathSelected");
175         urlBuilder.removeParameter("mgnlPathTarget");
176         urlBuilder.removeParameter("order");
177 
178         urlBuilder.setParameter("mgnlIntercept", "NODE_SORT");
179         urlBuilder.setParameter("mgnlPathSelected", pathSource);
180         urlBuilder.setParameter("mgnlPathTarget", pathTarget);
181         urlBuilder.setParameter("order", order);
182 
183         Window.Location.replace(urlBuilder.buildString());
184 
185     }
186 
187 
188     /**
189      * Removes all editor cookies not belonging to this page/module. Each time we navigate to a different link within the webapp
190      * the GWT module is unloaded and then reloaded, we need a clean slate when accessing cookies on a given page to avoid weird
191      * behaviour, i.e. page scrolling to last saved position when you come back to it after having been on a different page.
192      */
193     public static void resetEditorCookies() {
194         for(String cookie : Cookies.getCookieNames()) {
195             if(cookie.startsWith(EDITOR_COOKIE_NAMESPACE) && !(getEditorContentIdUniqueCookieName().equals(cookie)
196                     || getEditorPositionUniqueCookieName().equals(cookie))) {
197                 Cookies.removeCookie(cookie, EDITOR_COOKIE_PATH);
198             }
199         }
200     }
201 
202     public static void setEditorPositionCookie(String value) {
203         Cookies.setCookie(getEditorPositionUniqueCookieName(), value, null, null, EDITOR_COOKIE_PATH, false);
204     }
205 
206     private static String getEditorPositionUniqueCookieName() {
207         return editorPositionCookieName + getWindowLocation();
208     }
209 
210     public static void setEditorContentIdCookie(String value) {
211         Cookies.setCookie(getEditorContentIdUniqueCookieName(), value, null, null, EDITOR_COOKIE_PATH, false);
212     }
213 
214     private static String getEditorContentIdUniqueCookieName() {
215         return editorContentIdCookieName + getWindowLocation();
216     }
217 
218     public static void getCookiePosition() {
219         String position = Cookies.getCookie(getEditorPositionUniqueCookieName());
220         if(position!=null){
221             String[] tokens = position.split(":");
222             int left = Integer.parseInt(tokens[0]);
223             int top = Integer.parseInt(tokens[1]);
224             GWT.log("Scrolling to position left:" + left +", top: "+ top);
225             Window.scrollTo(left, top);
226         }
227     }
228 
229     public static void getCookieContentId() {
230         String contentId = Cookies.getCookie(getEditorContentIdUniqueCookieName());
231         MgnlElement selectedMgnlElement = null;
232         if(contentId != null) {
233             selectedMgnlElement = PageEditor.model.findMgnlElementByContentId(contentId);
234         }
235         if(selectedMgnlElement != null) {
236             PageEditor.model.getFocusModel().onLoadSelect(selectedMgnlElement);
237         }
238         else {
239             PageEditor.model.getFocusModel().reset();
240         }
241     }
242 
243     public static void removeEditorContentIdCookie() {
244         Cookies.removeCookie(getEditorContentIdUniqueCookieName(), EDITOR_COOKIE_PATH);
245     }
246 
247     public static void removeEditorPositionCookie() {
248         Cookies.removeCookie(getEditorPositionUniqueCookieName(), EDITOR_COOKIE_PATH);
249     }
250 }