View Javadoc

1   /**
2    * This file Copyright (c) 2011-2013 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;
35  
36  
37  import info.magnolia.templating.editor.client.dom.Comment;
38  import info.magnolia.templating.editor.client.dom.MgnlElement;
39  import info.magnolia.templating.editor.client.dom.processor.CommentProcessor;
40  import info.magnolia.templating.editor.client.dom.processor.ElementProcessor;
41  import info.magnolia.templating.editor.client.dom.processor.MgnlElementProcessor;
42  import info.magnolia.templating.editor.client.dom.processor.MgnlElementProcessorFactory;
43  import info.magnolia.templating.editor.client.jsni.JavascriptUtils;
44  import info.magnolia.templating.editor.client.model.ModelStorage;
45  import info.magnolia.templating.editor.client.widget.PreviewChannel;
46  import info.magnolia.templating.editor.client.widget.PreviewChannel.Orientation;
47  import info.magnolia.templating.editor.client.widget.dnd.LegacyDragAndDrop;
48  
49  import java.util.LinkedList;
50  import java.util.List;
51  
52  import com.google.gwt.core.client.EntryPoint;
53  import com.google.gwt.core.client.GWT;
54  import com.google.gwt.dom.client.AnchorElement;
55  import com.google.gwt.dom.client.Document;
56  import com.google.gwt.dom.client.Element;
57  import com.google.gwt.dom.client.FormElement;
58  import com.google.gwt.dom.client.Node;
59  import com.google.gwt.dom.client.NodeList;
60  import com.google.gwt.dom.client.Style.Unit;
61  import com.google.gwt.event.dom.client.ClickEvent;
62  import com.google.gwt.event.dom.client.ClickHandler;
63  import com.google.gwt.event.dom.client.KeyCodes;
64  import com.google.gwt.event.dom.client.KeyDownEvent;
65  import com.google.gwt.event.dom.client.KeyDownHandler;
66  import com.google.gwt.event.dom.client.MouseMoveEvent;
67  import com.google.gwt.event.dom.client.MouseMoveHandler;
68  import com.google.gwt.http.client.Request;
69  import com.google.gwt.http.client.RequestBuilder;
70  import com.google.gwt.http.client.RequestCallback;
71  import com.google.gwt.http.client.RequestException;
72  import com.google.gwt.http.client.Response;
73  import com.google.gwt.http.client.URL;
74  import com.google.gwt.http.client.UrlBuilder;
75  import com.google.gwt.user.client.Window;
76  import com.google.gwt.user.client.Window.ScrollEvent;
77  import com.google.gwt.user.client.Window.ScrollHandler;
78  import com.google.gwt.user.client.ui.HTML;
79  import com.google.gwt.user.client.ui.RootPanel;
80  
81  /**
82   * Client side implementation of the page editor. Outputs ui widgets inside document element (typically the {@code <html>} element).
83   * Since the DOM manipulations performed by the PageEditor (i.e. dynamic creation of edit bars) happen when all other javascripts have already been loaded
84   * (see <a href=http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideBootstrap>GWT bootstrap FAQ</a>),
85   * if you have some custom javascript which needs to operate on elements added by the PageEditor, you will have to use the utility javascript method <code>mgnl.PageEditor.onReady(callback)</code>.
86   * This will ensure that your handler functions are executed when the PageEditor is actually done.
87   * <p>For example:
88   * <pre>
89   * mgnl.PageEditor.onReady( function() {
90   *    alert('hello, page editor is ready.')
91   * });
92   * </pre>
93   * Modules can register multiple callbacks this way. The order in which callbacks are fired is the same in which they were registered.
94   *<p>
95   * @version $Id$
96   *
97   * TODO clean up/refactoring.
98   */
99  public class PageEditor extends HTML implements EntryPoint {
100 
101     private static final String MGNL_CHANNEL_PARAMETER = "mgnlChannel";
102     private static final String MGNL_PREVIEW_PARAMETER = "mgnlPreview";
103     private static final String MGNL_INTERCEPT_PARAMETER = "mgnlIntercept";
104     private static final String MGNL_VERSION_PARAMETER = "mgnlVersion";
105 
106     private static String locale;
107     public final static ModelStorage model = ModelStorage.getInstance();
108     private final LinkedList<MgnlElement> mgnlElements = new LinkedList<MgnlElement>();
109 
110     // In case we're in preview mode, we will stop processing the document, after the pagebar has been injected.
111     public static boolean process = true;
112     private static boolean isPreview = false;
113 
114 
115     @Override
116     public void onModuleLoad() {
117 
118         String mgnlVersion = Window.Location.getParameter(MGNL_VERSION_PARAMETER);
119         if(mgnlVersion != null) {
120             return;
121         }
122 
123         String mgnlChannel = Window.Location.getParameter(MGNL_CHANNEL_PARAMETER);
124         boolean isMobile = "smartphone".equals(mgnlChannel) || "tablet".equals(mgnlChannel);
125 
126         if(isMobile) {
127             GWT.log("Found " + mgnlChannel + " in request, post processing links...");
128             postProcessLinksOnMobilePreview(Document.get().getDocumentElement(), mgnlChannel);
129             return;
130         }
131 
132         JavascriptUtils.setWindowLocation(Window.Location.getPath());
133         // save x/y positon
134         Window.addWindowScrollHandler(new ScrollHandler() {
135 
136             @Override
137             public void onWindowScroll(ScrollEvent event) {
138                 String value = event.getScrollLeft() + ":" + event.getScrollTop();
139                 JavascriptUtils.setEditorPositionCookie(value);
140             }
141         });
142 
143         JavascriptUtils.getCookiePosition();
144 
145         locale = JavascriptUtils.detectCurrentLocale();
146 
147         long startTime = System.currentTimeMillis();
148         processDocument(Document.get().getDocumentElement(), null);
149         processMgnlElements();
150 
151         GWT.log("Time spent to process cms comments: " + (System.currentTimeMillis() - startTime) + "ms");
152 
153         JavascriptUtils.getCookieContentId();
154 
155         RootPanel.get().addDomHandler(new ClickHandler() {
156             @Override
157             public void onClick(ClickEvent event) {
158 
159                 model.getFocusModel().onMouseUp((Element) event.getNativeEvent().getEventTarget().cast());
160                 event.stopPropagation();
161             }
162         }, ClickEvent.getType());
163 
164 
165         RootPanel.get().addDomHandler(new KeyDownHandler() {
166             @Override
167             public void onKeyDown(KeyDownEvent event) {
168                 if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
169                     //if we're moving an element abort move
170                     if(LegacyDragAndDrop.isMoving()) {
171                         LegacyDragAndDrop.moveComponentReset();
172                     } else {
173                         PageEditor.enablePreview(!isPreview);
174                     }
175                     event.preventDefault();
176                 }
177             }
178         }, KeyDownEvent.getType());
179 
180 
181 
182         RootPanel.get().addDomHandler(new MouseMoveHandler() {
183 
184             @Override
185             public void onMouseMove(MouseMoveEvent event) {
186 
187                 Element moveElement = Document.get().getElementById("mgnlEditorMoveDiv");
188 
189                 if (moveElement != null) {
190                     int x = event.getClientX() + Window.getScrollLeft();
191                     int y = event.getClientY() + 15 + Window.getScrollTop();
192                     moveElement.getStyle().setTop(y, Unit.PX);
193                     moveElement.getStyle().setLeft(x, Unit.PX);
194                 }
195             }
196         }, MouseMoveEvent.getType());
197 
198         JavascriptUtils.resetEditorCookies();
199 
200         GWT.log("Running onPageEditorReady callbacks...");
201         onPageEditorReady();
202     }
203 
204     public static void openDialog(String dialog, String workspace, String path) {
205         JavascriptUtils.mgnlOpenDialog(path, "", "", dialog, workspace, "", "", "", locale);
206     }
207 
208     public static void deleteComponent(String path) {
209         JavascriptUtils.mgnlDeleteNode(path);
210     }
211 
212     public static void addComponent(String workspace, String path, String nodeName, String availableComponents) {
213         // Not used anymore. The node is passed together with the path
214         String collectionName = null;
215 
216         if (nodeName == null) {
217             nodeName = "mgnlNew";
218         }
219         if (availableComponents == null) {
220             availableComponents = "";
221         }
222         if (availableComponents.contains(",")) {
223             JavascriptUtils.mgnlOpenDialog(path, collectionName, nodeName, availableComponents, workspace, ".magnolia/dialogs/selectParagraph.html", "", "", locale);
224         } else if (!availableComponents.isEmpty()) {
225             JavascriptUtils.mgnlOpenDialog(path, collectionName, nodeName, availableComponents, workspace, ".magnolia/dialogs/editParagraph.html", "", "", locale);
226         }
227     }
228 
229     public static void showTree(String workspace, String path) {
230         JavascriptUtils.showTree(workspace, path);
231 
232     }
233 
234     public static void createComponent(String workspace, String path, String itemType) {
235         GWT.log("Creating [" + itemType + "] in workspace [" + workspace + "] at path [" + path + "]");
236 
237         final StringBuilder url = new StringBuilder();
238         url.append(JavascriptUtils.getContextPath() + ".magnolia/pageeditor/PageEditorServlet");
239         url.append("?action=create");
240         url.append("&workspace=" + workspace);
241         url.append("&path=" + path);
242         url.append("&itemType=" + itemType);
243 
244         RequestBuilder req = new RequestBuilder(RequestBuilder.GET, URL.encode(url.toString()));
245         req.setCallback(new RequestCallback() {
246 
247             @Override
248             public void onResponseReceived(Request request, Response response) {
249                 int status = response.getStatusCode();
250                 String responseText = "";
251                 boolean reload = false;
252 
253                 switch (status) {
254                 case Response.SC_OK:
255                     reload = true;
256                     break;
257                 case Response.SC_UNAUTHORIZED:
258                     responseText = "Is your session expired? Please, try to login again.";
259                     break;
260                 default:
261                     responseText = "See logs for more details.";
262                 }
263 
264                 if (reload) {
265                     UrlBuilder urlBuilder = Window.Location.createUrlBuilder();
266 
267                     urlBuilder.removeParameter("mgnlIntercept");
268                     urlBuilder.removeParameter("mgnlPath");
269 
270                     Window.Location.replace(urlBuilder.buildString());
271                 } else {
272                     Window.alert("An error occurred on the server: response status code is " + status + "\n" + responseText);
273                 }
274             }
275 
276             @Override
277             public void onError(Request request, Throwable exception) {
278                 Window.alert(exception.getMessage());
279             }
280         });
281         try {
282             req.send();
283         } catch (RequestException e) {
284             Window.alert("An error occurred while trying to send a request to the server: " + e.getMessage());
285         }
286 
287     }
288 
289     public static void createChannelPreview(final String channelName, final Orientation orientation) {
290         setPreview(true);
291         GWT.log("Creating preview for channel type [" + channelName + "] ");
292 
293         final UrlBuilder urlBuilder = Window.Location.createUrlBuilder();
294 
295         //always cleanup the url from preview params
296         urlBuilder.removeParameter(MGNL_PREVIEW_PARAMETER);
297         urlBuilder.removeParameter(MGNL_INTERCEPT_PARAMETER);
298         urlBuilder.removeParameter(MGNL_CHANNEL_PARAMETER);
299 
300         urlBuilder.setParameter(MGNL_PREVIEW_PARAMETER, String.valueOf(isPreview()));
301         urlBuilder.setParameter(MGNL_CHANNEL_PARAMETER, channelName);
302         final PreviewChannel previewChannelWidget = new PreviewChannel(urlBuilder.buildString(), orientation, channelName);
303         //this causes the pop up to show
304         previewChannelWidget.center();
305     }
306 
307     private void processDocument(Node node, MgnlElement mgnlElement) {
308         if(!process) {
309             return;
310         }
311         boolean proceed = true;
312         for (int i = 0; i < node.getChildCount(); i++) {
313             Node childNode = node.getChild(i);
314             if (childNode.getNodeType() == Comment.COMMENT_NODE) {
315                 try {
316                     mgnlElement = CommentProcessor.process(childNode, mgnlElement);
317                 }
318                 catch (IllegalArgumentException e) {
319                     GWT.log("Not CMSComment element, skipping: " + e.toString());
320                 }
321                 catch (Exception e) {
322                     GWT.log("Caught undefined exception: " + e.toString());
323                     consoleLog(e.getMessage()); // log also into browser console
324                 }
325             }
326             else if (childNode.getNodeType() == Node.ELEMENT_NODE && mgnlElement != null) {
327                 proceed = ElementProcessor.process(childNode, mgnlElement);
328             }
329             if (proceed) {
330                 processDocument(childNode, mgnlElement);
331             }
332         }
333     }
334 
335     private void processMgnlElements() {
336         List<MgnlElement> rootElements = new LinkedList<MgnlElement>(model.getRootElements());
337         for (MgnlElement root : rootElements) {
338             LinkedList<MgnlElement> elements = new LinkedList<MgnlElement>();
339             elements.add(root);
340             elements.addAll(root.getDescendants());
341 
342             for (MgnlElement mgnlElement : elements) {
343                 try {
344                     MgnlElementProcessor processor = MgnlElementProcessorFactory.getProcessor(mgnlElement);
345                     processor.process();
346                 } catch (IllegalArgumentException e) {
347                     GWT.log("MgnlFactory could not instantiate class. The element is neither an area nor component.");
348                 } catch (IllegalStateException e) {
349                     GWT.log(e.getMessage());
350                     consoleLog(e.getMessage()); // log also into browser console
351                 } catch (Exception e) {
352                     GWT.log("Caught undefined exception: " + e.toString());
353                     consoleLog("Caught undefined exception: " + e.toString()); // log also into browser console
354                 }
355             }
356         }
357 
358     }
359 
360     //FIXME submitting forms still renders website channel and edit bars
361     private void postProcessLinksOnMobilePreview(Element root, String channel) {
362         NodeList<Element> anchors = root.getElementsByTagName("a");
363 
364         final String mobilePreviewParams = MGNL_CHANNEL_PARAMETER+"="+channel+"&"+ MGNL_PREVIEW_PARAMETER+"=true";
365 
366         for (int i = 0; i < anchors.getLength(); i++) {
367             AnchorElement anchor = AnchorElement.as(anchors.getItem(i));
368 
369             GWT.log("Starting to process link " + anchor.getHref());
370 
371             if(JavascriptUtils.isEmpty(anchor.getHref())) {
372                 continue;
373             }
374             String manipulatedHref = anchor.getHref().replaceFirst(Window.Location.getProtocol() + "//" + Window.Location.getHost(), "");
375             String queryString = Window.Location.getQueryString() != null ? Window.Location.getQueryString() : "";
376 
377             GWT.log("query string is " + queryString);
378 
379             String queryStringRegex =  queryString.replaceFirst("\\?", "\\\\?");
380             manipulatedHref = manipulatedHref.replaceFirst(queryStringRegex, "");
381             int indexOfHash = manipulatedHref.indexOf("#");
382 
383             if(indexOfHash != -1) {
384                 manipulatedHref = manipulatedHref.substring(indexOfHash);
385             } else {
386                 if(!queryString.contains(mobilePreviewParams)) {
387                     if(queryString.startsWith("?")) {
388                         queryString += "&" + mobilePreviewParams;
389                     } else {
390                         queryString = "?" + mobilePreviewParams;
391                     }
392                 }
393                 manipulatedHref += queryString;
394             }
395             GWT.log("Resulting link is " + manipulatedHref);
396             anchor.setHref(manipulatedHref);
397         }
398         NodeList<Element> forms = root.getElementsByTagName("form");
399 
400         for (int i = 0; i < forms.getLength(); i++) {
401             FormElement form = FormElement.as(forms.getItem(i));
402             form.setAction(form.getAction().concat("?"+ mobilePreviewParams));
403         }
404     }
405 
406 
407     private native void onPageEditorReady() /*-{
408         var callbacks = $wnd.mgnl.PageEditor.onPageEditorReadyCallbacks
409         if(typeof callbacks != 'undefined') {
410              for(var i=0; i < callbacks.length; i++) {
411                 callbacks[i].apply()
412              }
413          }
414     }-*/;
415 
416     /**
417      * Enables/disables default (desktop) preview.
418      */
419     public static void enablePreview(boolean preview) {
420         setPreview(preview);
421         final UrlBuilder urlBuilder = Window.Location.createUrlBuilder();
422         GWT.log("Current url is [" + urlBuilder.buildString() + "], setting preview to " + isPreview());
423 
424         //always cleanup the url
425         urlBuilder.removeParameter(MGNL_PREVIEW_PARAMETER);
426         urlBuilder.removeParameter(MGNL_INTERCEPT_PARAMETER);
427         urlBuilder.removeParameter(MGNL_CHANNEL_PARAMETER);
428 
429         urlBuilder.setParameter(MGNL_INTERCEPT_PARAMETER, "PREVIEW");
430         urlBuilder.setParameter(MGNL_PREVIEW_PARAMETER, String.valueOf(isPreview()));
431 
432         if(isPreview()) {
433             urlBuilder.setParameter(MGNL_CHANNEL_PARAMETER, "desktop");
434         } else {
435             urlBuilder.setParameter(MGNL_CHANNEL_PARAMETER, "all");
436         }
437 
438         // if url was encoded before it would be double encoded now, if it wasn't encoded before, we should not force encoding either
439         final String newUrl = URL.decode(urlBuilder.buildString());
440         GWT.log("New url is [" + newUrl + "]");
441 
442         Window.Location.replace(newUrl);
443     }
444 
445     /**
446      * @return <code>true</code> if the current page is in the default (desktop) preview mode, <code>false</code> otherwise.
447      */
448     public static boolean isPreview() {
449         return isPreview;
450     }
451 
452     public static void setPreview(boolean preview) {
453         isPreview = preview;
454     }
455 
456     native void consoleLog(String message) /*-{
457                                             if (typeof console == "object") {
458                                                 console.log( "PageEditor: " + message );
459                                             }
460                                            }-*/;
461 }