8a527793a3d47ade95684c5e73d092dc996e6919
[gpl/argeo-suite.git] / publishing / org.argeo.publishing.ui / src / org / argeo / docbook / ui / AbstractDbkViewer.java
1 package org.argeo.docbook.ui;
2
3 import static org.argeo.cms.ui.util.CmsUiUtils.fillWidth;
4
5 import java.util.ArrayList;
6 import java.util.Iterator;
7 import java.util.Map;
8 import java.util.Observer;
9
10 import javax.jcr.Item;
11 import javax.jcr.Node;
12 import javax.jcr.NodeIterator;
13 import javax.jcr.RepositoryException;
14 import javax.jcr.Session;
15 import javax.jcr.nodetype.NodeType;
16
17 import org.apache.commons.logging.Log;
18 import org.apache.commons.logging.LogFactory;
19 import org.argeo.cms.CmsException;
20 import org.argeo.cms.text.Paragraph;
21 import org.argeo.cms.text.SectionTitle;
22 import org.argeo.cms.text.TextInterpreter;
23 import org.argeo.cms.text.TextSection;
24 import org.argeo.cms.ui.CmsEditable;
25 import org.argeo.cms.ui.CmsImageManager;
26 import org.argeo.cms.ui.CmsView;
27 import org.argeo.cms.ui.util.CmsUiUtils;
28 import org.argeo.cms.ui.viewers.AbstractPageViewer;
29 import org.argeo.cms.ui.viewers.EditablePart;
30 import org.argeo.cms.ui.viewers.NodePart;
31 import org.argeo.cms.ui.viewers.PropertyPart;
32 import org.argeo.cms.ui.viewers.Section;
33 import org.argeo.cms.ui.viewers.SectionPart;
34 import org.argeo.cms.ui.widgets.EditableImage;
35 import org.argeo.cms.ui.widgets.EditableText;
36 import org.argeo.cms.ui.widgets.Img;
37 import org.argeo.cms.ui.widgets.StyledControl;
38 import org.argeo.jcr.JcrUtils;
39 import org.eclipse.rap.fileupload.FileDetails;
40 import org.eclipse.rap.fileupload.FileUploadEvent;
41 import org.eclipse.rap.fileupload.FileUploadHandler;
42 import org.eclipse.rap.fileupload.FileUploadListener;
43 import org.eclipse.rap.rwt.RWT;
44 import org.eclipse.swt.SWT;
45 import org.eclipse.swt.events.KeyEvent;
46 import org.eclipse.swt.events.KeyListener;
47 import org.eclipse.swt.events.MouseAdapter;
48 import org.eclipse.swt.events.MouseEvent;
49 import org.eclipse.swt.events.MouseListener;
50 import org.eclipse.swt.graphics.Point;
51 import org.eclipse.swt.widgets.Composite;
52 import org.eclipse.swt.widgets.Control;
53 import org.eclipse.swt.widgets.Text;
54
55 /** Base class for text viewers and editors. */
56 public abstract class AbstractDbkViewer extends AbstractPageViewer implements KeyListener, Observer {
57         private static final long serialVersionUID = -2401274679492339668L;
58         private final static Log log = LogFactory.getLog(AbstractDbkViewer.class);
59
60         private final Section mainSection;
61
62         private TextInterpreter textInterpreter = new DbkTextInterpreter();
63         private CmsImageManager imageManager;
64
65         private FileUploadListener fileUploadListener;
66         private DbkContextMenu styledTools;
67
68         private final boolean flat;
69
70         protected AbstractDbkViewer(Section parent, int style, CmsEditable cmsEditable) {
71                 super(parent, style, cmsEditable);
72                 CmsView cmsView = CmsView.getCmsView(parent);
73                 imageManager = cmsView.getImageManager();
74                 flat = SWT.FLAT == (style & SWT.FLAT);
75
76                 if (getCmsEditable().canEdit()) {
77                         fileUploadListener = new FUL();
78                         styledTools = new DbkContextMenu(this, parent.getDisplay());
79                 }
80                 this.mainSection = parent;
81                 initModelIfNeeded(mainSection.getNode());
82                 // layout(this.mainSection);
83         }
84
85         @Override
86         public Control getControl() {
87                 return mainSection;
88         }
89
90         protected void refresh(Control control) throws RepositoryException {
91                 if (!(control instanceof Section))
92                         return;
93                 Section section = (Section) control;
94                 if (section instanceof TextSection) {
95                         CmsUiUtils.clear(section);
96                         Node node = section.getNode();
97                         TextSection textSection = (TextSection) section;
98                         if (node.hasNode(DocBookTypes.TITLE)) {
99                                 if (section.getHeader() == null)
100                                         section.createHeader();
101                                 Node titleNode = node.getNode(DocBookTypes.TITLE);
102                                 DocBookSectionTitle title = newSectionTitle(textSection, titleNode);
103                                 title.setLayoutData(CmsUiUtils.fillWidth());
104                                 updateContent(title);
105                         }
106
107                         for (NodeIterator ni = node.getNodes(DocBookNames.DBK_PARA); ni.hasNext();) {
108                                 Node child = ni.nextNode();
109                                 final SectionPart sectionPart;
110                                 if (child.isNodeType(DocBookTypes.IMAGEDATA) || child.isNodeType(NodeType.NT_FILE)) {
111                                         // FIXME adapt to DocBook
112                                         sectionPart = newImg(textSection, child);
113                                 } else if (child.isNodeType(DocBookTypes.PARA)) {
114                                         sectionPart = newParagraph(textSection, child);
115                                 } else {
116                                         sectionPart = newSectionPart(textSection, child);
117                                         if (sectionPart == null)
118                                                 throw new CmsException("Unsupported node " + child);
119                                         // TODO list node types in exception
120                                 }
121                                 if (sectionPart instanceof Control)
122                                         ((Control) sectionPart).setLayoutData(CmsUiUtils.fillWidth());
123                         }
124
125 //                      if (!flat)
126                         for (NodeIterator ni = section.getNode().getNodes(DocBookNames.DBK_SECTION); ni.hasNext();) {
127                                 Node child = ni.nextNode();
128                                 if (child.isNodeType(DocBookTypes.SECTION)) {
129                                         TextSection newSection = new TextSection(section, SWT.NONE, child);
130                                         newSection.setLayoutData(CmsUiUtils.fillWidth());
131                                         refresh(newSection);
132                                 }
133                         }
134                 } else {
135                         for (Section s : section.getSubSections().values())
136                                 refresh(s);
137                 }
138                 // section.layout();
139         }
140
141         /** To be overridden in order to provide additional SectionPart types */
142         protected SectionPart newSectionPart(TextSection textSection, Node node) {
143                 return null;
144         }
145
146         // CRUD
147         protected Paragraph newParagraph(TextSection parent, Node node) throws RepositoryException {
148                 Paragraph paragraph = new Paragraph(parent, parent.getStyle(), node);
149                 updateContent(paragraph);
150                 paragraph.setLayoutData(fillWidth());
151                 paragraph.setMouseListener(getMouseListener());
152                 return paragraph;
153         }
154
155         protected Img newImg(TextSection parent, Node node) throws RepositoryException {
156                 Img img = new Img(parent, parent.getStyle(), node) {
157                         private static final long serialVersionUID = 1297900641952417540L;
158
159                         @Override
160                         protected void setContainerLayoutData(Composite composite) {
161                                 composite.setLayoutData(CmsUiUtils.grabWidth(SWT.CENTER, SWT.DEFAULT));
162                         }
163
164                         @Override
165                         protected void setControlLayoutData(Control control) {
166                                 control.setLayoutData(CmsUiUtils.grabWidth(SWT.CENTER, SWT.DEFAULT));
167                         }
168                 };
169                 img.setLayoutData(CmsUiUtils.grabWidth(SWT.CENTER, SWT.DEFAULT));
170                 updateContent(img);
171                 img.setMouseListener(getMouseListener());
172                 return img;
173         }
174
175         protected DocBookSectionTitle newSectionTitle(TextSection parent, Node titleNode) throws RepositoryException {
176                 int style = parent.getStyle();
177                 if (parent.isTitleReadOnly())
178                         style = style | SWT.READ_ONLY;
179                 DocBookSectionTitle title = new DocBookSectionTitle(parent.getHeader(), style, titleNode);
180                 updateContent(title);
181                 title.setMouseListener(getMouseListener());
182                 return title;
183         }
184
185         protected DocBookSectionTitle prepareSectionTitle(Section newSection, String titleText) throws RepositoryException {
186                 Node sectionNode = newSection.getNode();
187                 Node titleNode;
188                 if (!sectionNode.hasNode(DocBookTypes.TITLE)) {
189                         titleNode = sectionNode.addNode(DocBookTypes.TITLE, DocBookTypes.TITLE);
190                 } else {
191                         titleNode = sectionNode.getNode(DocBookTypes.TITLE);
192                 }
193                 getTextInterpreter().write(titleNode, titleText);
194                 if (newSection.getHeader() == null)
195                         newSection.createHeader();
196                 DocBookSectionTitle sectionTitle = newSectionTitle((TextSection) newSection, sectionNode);
197                 return sectionTitle;
198         }
199
200         protected void updateContent(EditablePart part) throws RepositoryException {
201                 if (part instanceof SectionPart) {
202                         SectionPart sectionPart = (SectionPart) part;
203                         Node partNode = sectionPart.getNode();
204
205                         if (part instanceof StyledControl && (sectionPart.getSection() instanceof TextSection)) {
206                                 TextSection section = (TextSection) sectionPart.getSection();
207                                 StyledControl styledControl = (StyledControl) part;
208                                 if (partNode.isNodeType(DocBookTypes.PARA)) {
209                                         String style = partNode.hasProperty(DocBookNames.DBK_ROLE)
210                                                         ? partNode.getProperty(DocBookNames.DBK_ROLE).getString()
211                                                         : section.getDefaultTextStyle();
212                                         styledControl.setStyle(style);
213                                 }
214                         }
215                         // use control AFTER setting style, since it may have been reset
216
217                         if (part instanceof EditableText) {
218                                 EditableText paragraph = (EditableText) part;
219                                 if (paragraph == getEdited())
220                                         paragraph.setText(textInterpreter.read(partNode));
221                                 else
222                                         paragraph.setText(textInterpreter.raw(partNode));
223                         } else if (part instanceof EditableImage) {
224                                 EditableImage editableImage = (EditableImage) part;
225                                 imageManager.load(partNode, part.getControl(), editableImage.getPreferredImageSize());
226                         }
227                 } else if (part instanceof DocBookSectionTitle) {
228                         DocBookSectionTitle title = (DocBookSectionTitle) part;
229                         title.setStyle(title.getSection().getTitleStyle());
230                         // use control AFTER setting style
231                         if (title == getEdited())
232                                 title.setText(textInterpreter.read(title.getNode()));
233                         else
234                                 title.setText(textInterpreter.raw(title.getNode()));
235                 }
236         }
237
238         // OVERRIDDEN FROM PARENT VIEWER
239         @Override
240         protected void save(EditablePart part) throws RepositoryException {
241                 if (part instanceof EditableText) {
242                         EditableText et = (EditableText) part;
243                         if (!et.getEditable())
244                                 return;
245                         String text = ((Text) et.getControl()).getText();
246
247                         String[] lines = text.split("[\r\n]+");
248                         assert lines.length != 0;
249                         saveLine(part, lines[0]);
250                         if (lines.length > 1) {
251                                 ArrayList<Control> toLayout = new ArrayList<Control>();
252                                 if (part instanceof Paragraph) {
253                                         Paragraph currentParagraph = (Paragraph) et;
254                                         Section section = currentParagraph.getSection();
255                                         Node sectionNode = section.getNode();
256                                         Node currentParagraphN = currentParagraph.getNode();
257                                         for (int i = 1; i < lines.length; i++) {
258                                                 Node newNode = sectionNode.addNode(DocBookNames.DBK_PARA, DocBookTypes.PARA);
259                                                 // newNode.addMixin(CmsTypes.CMS_STYLED);
260                                                 saveLine(newNode, lines[i]);
261                                                 // second node was create as last, if it is not the next
262                                                 // one, it
263                                                 // means there are some in between and we can take the
264                                                 // one at
265                                                 // index+1 for the re-order
266                                                 if (newNode.getIndex() > currentParagraphN.getIndex() + 1) {
267                                                         sectionNode.orderBefore(p(newNode.getIndex()), p(currentParagraphN.getIndex() + 1));
268                                                 }
269                                                 Paragraph newParagraph = newParagraph((TextSection) section, newNode);
270                                                 newParagraph.moveBelow(currentParagraph);
271                                                 toLayout.add(newParagraph);
272
273                                                 currentParagraph = newParagraph;
274                                                 currentParagraphN = newNode;
275                                         }
276                                 }
277                                 // TODO or rather return the created paragarphs?
278                                 layout(toLayout.toArray(new Control[toLayout.size()]));
279                         }
280                         persistChanges(et.getNode());
281                 }
282         }
283
284         protected void saveLine(EditablePart part, String line) {
285                 if (part instanceof NodePart) {
286                         saveLine(((NodePart) part).getNode(), line);
287                 } else if (part instanceof PropertyPart) {
288                         saveLine(((PropertyPart) part).getProperty(), line);
289                 } else {
290                         throw new CmsException("Unsupported part " + part);
291                 }
292         }
293
294         protected void saveLine(Item item, String line) {
295                 line = line.trim();
296                 textInterpreter.write(item, line);
297         }
298
299         @Override
300         protected void prepare(EditablePart part, Object caretPosition) {
301                 Control control = part.getControl();
302                 if (control instanceof Text) {
303                         Text text = (Text) control;
304                         if (caretPosition != null)
305                                 if (caretPosition instanceof Integer)
306                                         text.setSelection((Integer) caretPosition);
307                                 else if (caretPosition instanceof Point) {
308                                         // TODO find a way to position the caret at the right place
309                                 }
310                         text.setData(RWT.ACTIVE_KEYS, new String[] { "BACKSPACE", "ESC", "TAB", "SHIFT+TAB", "ALT+ARROW_LEFT",
311                                         "ALT+ARROW_RIGHT", "ALT+ARROW_UP", "ALT+ARROW_DOWN", "RETURN", "CTRL+RETURN", "ENTER", "DELETE" });
312                         text.setData(RWT.CANCEL_KEYS, new String[] { "RETURN", "ALT+ARROW_LEFT", "ALT+ARROW_RIGHT" });
313                         text.addKeyListener(this);
314                 } else if (part instanceof Img) {
315                         ((Img) part).setFileUploadListener(fileUploadListener);
316                 }
317         }
318
319         // REQUIRED BY CONTEXT MENU
320         void setParagraphStyle(Paragraph paragraph, String style) {
321                 try {
322                         Node paragraphNode = paragraph.getNode();
323                         paragraphNode.setProperty(DocBookNames.DBK_ROLE, style);
324                         persistChanges(paragraphNode);
325                         updateContent(paragraph);
326                         layout(paragraph);
327                 } catch (RepositoryException e1) {
328                         throw new CmsException("Cannot set style " + style + " on " + paragraph, e1);
329                 }
330         }
331
332         void deletePart(SectionPart paragraph) {
333                 try {
334                         Node paragraphNode = paragraph.getNode();
335                         Section section = paragraph.getSection();
336                         Session session = paragraphNode.getSession();
337                         paragraphNode.remove();
338                         session.save();
339                         if (paragraph instanceof Control)
340                                 ((Control) paragraph).dispose();
341                         layout(section);
342                 } catch (RepositoryException e1) {
343                         throw new CmsException("Cannot delete " + paragraph, e1);
344                 }
345         }
346
347         String getRawParagraphText(Paragraph paragraph) {
348                 return textInterpreter.raw(paragraph.getNode());
349         }
350
351         // COMMANDS
352         protected void splitEdit() {
353                 checkEdited();
354                 try {
355                         if (getEdited() instanceof Paragraph) {
356                                 Paragraph paragraph = (Paragraph) getEdited();
357                                 Text text = (Text) paragraph.getControl();
358                                 int caretPosition = text.getCaretPosition();
359                                 String txt = text.getText();
360                                 String first = txt.substring(0, caretPosition);
361                                 String second = txt.substring(caretPosition);
362                                 Node firstNode = paragraph.getNode();
363                                 Node sectionNode = firstNode.getParent();
364
365                                 // FIXME set content the DocBook way
366                                 // firstNode.setProperty(CMS_CONTENT, first);
367                                 Node secondNode = sectionNode.addNode(DocBookNames.DBK_PARA, DocBookTypes.PARA);
368                                 // secondNode.addMixin(CmsTypes.CMS_STYLED);
369
370                                 // second node was create as last, if it is not the next one, it
371                                 // means there are some in between and we can take the one at
372                                 // index+1 for the re-order
373                                 if (secondNode.getIndex() > firstNode.getIndex() + 1) {
374                                         sectionNode.orderBefore(p(secondNode.getIndex()), p(firstNode.getIndex() + 1));
375                                 }
376
377                                 // if we die in between, at least we still have the whole text
378                                 // in the first node
379                                 try {
380                                         textInterpreter.write(secondNode, second);
381                                         textInterpreter.write(firstNode, first);
382                                 } catch (Exception e) {
383                                         // so that no additional nodes are created:
384                                         JcrUtils.discardUnderlyingSessionQuietly(firstNode);
385                                         throw e;
386                                 }
387
388                                 persistChanges(firstNode);
389
390                                 Paragraph secondParagraph = paragraphSplitted(paragraph, secondNode);
391                                 edit(secondParagraph, 0);
392                         } else if (getEdited() instanceof DocBookSectionTitle) {
393                                 DocBookSectionTitle sectionTitle = (DocBookSectionTitle) getEdited();
394                                 Text text = (Text) sectionTitle.getControl();
395                                 String txt = text.getText();
396                                 int caretPosition = text.getCaretPosition();
397                                 Section section = sectionTitle.getSection();
398                                 Node sectionNode = section.getNode();
399                                 Node paragraphNode = sectionNode.addNode(DocBookNames.DBK_PARA, DocBookTypes.PARA);
400                                 // paragraphNode.addMixin(CmsTypes.CMS_STYLED);
401
402                                 textInterpreter.write(paragraphNode, txt.substring(caretPosition));
403                                 textInterpreter.write(sectionNode.getNode(DocBookTypes.TITLE), txt.substring(0, caretPosition));
404                                 sectionNode.orderBefore(p(paragraphNode.getIndex()), p(1));
405                                 persistChanges(sectionNode);
406
407                                 Paragraph paragraph = sectionTitleSplitted(sectionTitle, paragraphNode);
408                                 // section.layout();
409                                 edit(paragraph, 0);
410                         }
411                 } catch (RepositoryException e) {
412                         throw new CmsException("Cannot split " + getEdited(), e);
413                 }
414         }
415
416         protected void mergeWithPrevious() {
417                 checkEdited();
418                 try {
419                         Paragraph paragraph = (Paragraph) getEdited();
420                         Text text = (Text) paragraph.getControl();
421                         String txt = text.getText();
422                         Node paragraphNode = paragraph.getNode();
423                         if (paragraphNode.getIndex() == 1)
424                                 return;// do nothing
425                         Node sectionNode = paragraphNode.getParent();
426                         Node previousNode = sectionNode.getNode(p(paragraphNode.getIndex() - 1));
427                         String previousTxt = textInterpreter.read(previousNode);
428                         textInterpreter.write(previousNode, previousTxt + txt);
429                         paragraphNode.remove();
430                         persistChanges(sectionNode);
431
432                         Paragraph previousParagraph = paragraphMergedWithPrevious(paragraph, previousNode);
433                         edit(previousParagraph, previousTxt.length());
434                 } catch (RepositoryException e) {
435                         throw new CmsException("Cannot stop editing", e);
436                 }
437         }
438
439         protected void mergeWithNext() {
440                 checkEdited();
441                 try {
442                         Paragraph paragraph = (Paragraph) getEdited();
443                         Text text = (Text) paragraph.getControl();
444                         String txt = text.getText();
445                         Node paragraphNode = paragraph.getNode();
446                         Node sectionNode = paragraphNode.getParent();
447                         NodeIterator paragraphNodes = sectionNode.getNodes(DocBookNames.DBK_PARA);
448                         long size = paragraphNodes.getSize();
449                         if (paragraphNode.getIndex() == size)
450                                 return;// do nothing
451                         Node nextNode = sectionNode.getNode(p(paragraphNode.getIndex() + 1));
452                         String nextTxt = textInterpreter.read(nextNode);
453                         textInterpreter.write(paragraphNode, txt + nextTxt);
454
455                         Section section = paragraph.getSection();
456                         Paragraph removed = (Paragraph) section.getSectionPart(nextNode.getIdentifier());
457
458                         nextNode.remove();
459                         persistChanges(sectionNode);
460
461                         paragraphMergedWithNext(paragraph, removed);
462                         edit(paragraph, txt.length());
463                 } catch (RepositoryException e) {
464                         throw new CmsException("Cannot stop editing", e);
465                 }
466         }
467
468         protected synchronized void upload(EditablePart part) {
469                 try {
470                         if (part instanceof SectionPart) {
471                                 SectionPart sectionPart = (SectionPart) part;
472                                 Node partNode = sectionPart.getNode();
473                                 int partIndex = partNode.getIndex();
474                                 Section section = sectionPart.getSection();
475                                 Node sectionNode = section.getNode();
476
477                                 if (part instanceof Paragraph) {
478                                         // FIXME adapt to DocBook
479                                         Node newNode = sectionNode.addNode(DocBookNames.DBK_MEDIAOBJECT, NodeType.NT_FILE);
480                                         newNode.addNode(Node.JCR_CONTENT, NodeType.NT_RESOURCE);
481                                         JcrUtils.copyBytesAsFile(sectionNode, p(newNode.getIndex()), new byte[0]);
482                                         if (partIndex < newNode.getIndex() - 1) {
483                                                 // was not last
484                                                 sectionNode.orderBefore(p(newNode.getIndex()), p(partIndex - 1));
485                                         }
486                                         // sectionNode.orderBefore(p(partNode.getIndex()),
487                                         // p(newNode.getIndex()));
488                                         persistChanges(sectionNode);
489                                         Img img = newImg((TextSection) section, newNode);
490                                         edit(img, null);
491                                         layout(img.getControl());
492                                 } else if (part instanceof Img) {
493                                         if (getEdited() == part)
494                                                 return;
495                                         edit(part, null);
496                                         layout(part.getControl());
497                                 }
498                         }
499                 } catch (RepositoryException e) {
500                         throw new CmsException("Cannot upload", e);
501                 }
502         }
503
504         protected void deepen() {
505                 if (flat)
506                         return;
507                 checkEdited();
508                 try {
509                         if (getEdited() instanceof Paragraph) {
510                                 Paragraph paragraph = (Paragraph) getEdited();
511                                 Text text = (Text) paragraph.getControl();
512                                 String txt = text.getText();
513                                 Node paragraphNode = paragraph.getNode();
514                                 Section section = paragraph.getSection();
515                                 Node sectionNode = section.getNode();
516                                 // main title
517                                 if (section == mainSection && section instanceof TextSection && paragraphNode.getIndex() == 1
518                                                 && !sectionNode.hasNode(DocBookTypes.TITLE)) {
519                                         DocBookSectionTitle sectionTitle = prepareSectionTitle(section, txt);
520                                         edit(sectionTitle, 0);
521                                         return;
522                                 }
523                                 Node newSectionNode = sectionNode.addNode(DocBookNames.DBK_SECTION, DocBookTypes.SECTION);
524                                 // newSectionNode.addMixin(NodeType.MIX_TITLE);
525                                 sectionNode.orderBefore(h(newSectionNode.getIndex()), h(1));
526
527                                 int paragraphIndex = paragraphNode.getIndex();
528                                 String sectionPath = sectionNode.getPath();
529                                 String newSectionPath = newSectionNode.getPath();
530                                 while (sectionNode.hasNode(p(paragraphIndex + 1))) {
531                                         Node parag = sectionNode.getNode(p(paragraphIndex + 1));
532                                         sectionNode.getSession().move(sectionPath + '/' + p(paragraphIndex + 1),
533                                                         newSectionPath + '/' + DocBookNames.DBK_PARA);
534                                         SectionPart sp = section.getSectionPart(parag.getIdentifier());
535                                         if (sp instanceof Control)
536                                                 ((Control) sp).dispose();
537                                 }
538                                 // create title
539                                 Node titleNode = newSectionNode.addNode(DocBookTypes.TITLE, DocBookTypes.TITLE);
540                                 getTextInterpreter().write(titleNode, txt);
541
542                                 TextSection newSection = new TextSection(section, section.getStyle(), newSectionNode);
543                                 newSection.setLayoutData(CmsUiUtils.fillWidth());
544                                 newSection.moveBelow(paragraph);
545
546                                 // dispose
547                                 paragraphNode.remove();
548                                 paragraph.dispose();
549
550                                 refresh(newSection);
551                                 newSection.getParent().layout();
552                                 layout(newSection);
553                                 persistChanges(sectionNode);
554                         } else if (getEdited() instanceof DocBookSectionTitle) {
555                                 DocBookSectionTitle sectionTitle = (DocBookSectionTitle) getEdited();
556                                 Section section = sectionTitle.getSection();
557                                 Section parentSection = section.getParentSection();
558                                 if (parentSection == null)
559                                         return;// cannot deepen main section
560                                 Node sectionN = section.getNode();
561                                 Node parentSectionN = parentSection.getNode();
562                                 if (sectionN.getIndex() == 1)
563                                         return;// cannot deepen first section
564                                 Node previousSectionN = parentSectionN.getNode(h(sectionN.getIndex() - 1));
565                                 NodeIterator subSections = previousSectionN.getNodes(DocBookNames.DBK_SECTION);
566                                 int subsectionsCount = (int) subSections.getSize();
567                                 previousSectionN.getSession().move(sectionN.getPath(),
568                                                 previousSectionN.getPath() + "/" + h(subsectionsCount + 1));
569                                 section.dispose();
570                                 TextSection newSection = new TextSection(section, section.getStyle(), sectionN);
571                                 refresh(newSection);
572                                 persistChanges(previousSectionN);
573                         }
574                 } catch (RepositoryException e) {
575                         throw new CmsException("Cannot deepen " + getEdited(), e);
576                 }
577         }
578
579         protected void undeepen() {
580                 if (flat)
581                         return;
582                 checkEdited();
583                 try {
584                         if (getEdited() instanceof Paragraph) {
585                                 upload(getEdited());
586                         } else if (getEdited() instanceof SectionTitle) {
587                                 SectionTitle sectionTitle = (SectionTitle) getEdited();
588                                 Section section = sectionTitle.getSection();
589                                 Node sectionNode = section.getNode();
590                                 Section parentSection = section.getParentSection();
591                                 if (parentSection == null)
592                                         return;// cannot undeepen main section
593
594                                 // choose in which section to merge
595                                 Section mergedSection;
596                                 if (sectionNode.getIndex() == 1)
597                                         mergedSection = section.getParentSection();
598                                 else {
599                                         Map<String, Section> parentSubsections = parentSection.getSubSections();
600                                         ArrayList<Section> lst = new ArrayList<Section>(parentSubsections.values());
601                                         mergedSection = lst.get(sectionNode.getIndex() - 1);
602                                 }
603                                 Node mergedNode = mergedSection.getNode();
604                                 boolean mergedHasSubSections = mergedNode.hasNode(DocBookNames.DBK_SECTION);
605
606                                 // title as paragraph
607                                 Node newParagrapheNode = mergedNode.addNode(DocBookNames.DBK_PARA, DocBookTypes.PARA);
608                                 // newParagrapheNode.addMixin(CmsTypes.CMS_STYLED);
609                                 if (mergedHasSubSections)
610                                         mergedNode.orderBefore(p(newParagrapheNode.getIndex()), h(1));
611                                 String txt = getTextInterpreter().read(sectionNode.getNode(DocBookTypes.TITLE));
612                                 getTextInterpreter().write(newParagrapheNode, txt);
613                                 // move
614                                 NodeIterator paragraphs = sectionNode.getNodes(DocBookNames.DBK_PARA);
615                                 while (paragraphs.hasNext()) {
616                                         Node p = paragraphs.nextNode();
617                                         SectionPart sp = section.getSectionPart(p.getIdentifier());
618                                         if (sp instanceof Control)
619                                                 ((Control) sp).dispose();
620                                         mergedNode.getSession().move(p.getPath(), mergedNode.getPath() + '/' + DocBookNames.DBK_PARA);
621                                         if (mergedHasSubSections)
622                                                 mergedNode.orderBefore(p(p.getIndex()), h(1));
623                                 }
624
625                                 Iterator<Section> subsections = section.getSubSections().values().iterator();
626                                 // NodeIterator sections = sectionNode.getNodes(CMS_H);
627                                 while (subsections.hasNext()) {
628                                         Section subsection = subsections.next();
629                                         Node s = subsection.getNode();
630                                         mergedNode.getSession().move(s.getPath(), mergedNode.getPath() + '/' + DocBookNames.DBK_SECTION);
631                                         subsection.dispose();
632                                 }
633
634                                 // remove section
635                                 section.getNode().remove();
636                                 section.dispose();
637
638                                 refresh(mergedSection);
639                                 mergedSection.getParent().layout();
640                                 layout(mergedSection);
641                                 persistChanges(mergedNode);
642                         }
643                 } catch (RepositoryException e) {
644                         throw new CmsException("Cannot undeepen " + getEdited(), e);
645                 }
646         }
647
648         // UI CHANGES
649         protected Paragraph paragraphSplitted(Paragraph paragraph, Node newNode) throws RepositoryException {
650                 Section section = paragraph.getSection();
651                 updateContent(paragraph);
652                 Paragraph newParagraph = newParagraph((TextSection) section, newNode);
653                 newParagraph.setLayoutData(CmsUiUtils.fillWidth());
654                 newParagraph.moveBelow(paragraph);
655                 layout(paragraph.getControl(), newParagraph.getControl());
656                 return newParagraph;
657         }
658
659         protected Paragraph sectionTitleSplitted(DocBookSectionTitle sectionTitle, Node newNode)
660                         throws RepositoryException {
661                 updateContent(sectionTitle);
662                 Paragraph newParagraph = newParagraph(sectionTitle.getSection(), newNode);
663                 // we assume beforeFirst is not null since there was a sectionTitle
664                 newParagraph.moveBelow(sectionTitle.getSection().getHeader());
665                 layout(sectionTitle.getControl(), newParagraph.getControl());
666                 return newParagraph;
667         }
668
669         protected Paragraph paragraphMergedWithPrevious(Paragraph removed, Node remaining) throws RepositoryException {
670                 Section section = removed.getSection();
671                 removed.dispose();
672
673                 Paragraph paragraph = (Paragraph) section.getSectionPart(remaining.getIdentifier());
674                 updateContent(paragraph);
675                 layout(paragraph.getControl());
676                 return paragraph;
677         }
678
679         protected void paragraphMergedWithNext(Paragraph remaining, Paragraph removed) throws RepositoryException {
680                 removed.dispose();
681                 updateContent(remaining);
682                 layout(remaining.getControl());
683         }
684
685         // UTILITIES
686         protected String p(Integer index) {
687                 StringBuilder sb = new StringBuilder(6);
688                 sb.append(DocBookNames.DBK_PARA).append('[').append(index).append(']');
689                 return sb.toString();
690         }
691
692         protected String h(Integer index) {
693                 StringBuilder sb = new StringBuilder(5);
694                 sb.append(DocBookNames.DBK_SECTION).append('[').append(index).append(']');
695                 return sb.toString();
696         }
697
698         // GETTERS / SETTERS
699         public Section getMainSection() {
700                 return mainSection;
701         }
702
703         public boolean isFlat() {
704                 return flat;
705         }
706
707         public TextInterpreter getTextInterpreter() {
708                 return textInterpreter;
709         }
710
711         // KEY LISTENER
712         @Override
713         public void keyPressed(KeyEvent ke) {
714                 if (log.isTraceEnabled())
715                         log.trace(ke);
716
717                 if (getEdited() == null)
718                         return;
719                 boolean altPressed = (ke.stateMask & SWT.ALT) != 0;
720                 boolean shiftPressed = (ke.stateMask & SWT.SHIFT) != 0;
721                 boolean ctrlPressed = (ke.stateMask & SWT.CTRL) != 0;
722
723                 try {
724                         // Common
725                         if (ke.keyCode == SWT.ESC) {
726                                 cancelEdit();
727                         } else if (ke.character == '\r') {
728                                 splitEdit();
729                         } else if (ke.character == 'S') {
730                                 if (ctrlPressed)
731                                         saveEdit();
732                         } else if (ke.character == '\t') {
733                                 if (!shiftPressed) {
734                                         deepen();
735                                 } else if (shiftPressed) {
736                                         undeepen();
737                                 }
738                         } else {
739                                 if (getEdited() instanceof Paragraph) {
740                                         Paragraph paragraph = (Paragraph) getEdited();
741                                         Section section = paragraph.getSection();
742                                         if (altPressed && ke.keyCode == SWT.ARROW_RIGHT) {
743                                                 edit(section.nextSectionPart(paragraph), 0);
744                                         } else if (altPressed && ke.keyCode == SWT.ARROW_LEFT) {
745                                                 edit(section.previousSectionPart(paragraph), 0);
746                                         } else if (ke.character == SWT.BS) {
747                                                 Text text = (Text) paragraph.getControl();
748                                                 int caretPosition = text.getCaretPosition();
749                                                 if (caretPosition == 0) {
750                                                         mergeWithPrevious();
751                                                 }
752                                         } else if (ke.character == SWT.DEL) {
753                                                 Text text = (Text) paragraph.getControl();
754                                                 int caretPosition = text.getCaretPosition();
755                                                 int charcount = text.getCharCount();
756                                                 if (caretPosition == charcount) {
757                                                         mergeWithNext();
758                                                 }
759                                         }
760                                 }
761                         }
762                 } catch (Exception e) {
763                         ke.doit = false;
764                         notifyEditionException(e);
765                 }
766         }
767
768         @Override
769         public void keyReleased(KeyEvent e) {
770         }
771
772         // MOUSE LISTENER
773         @Override
774         protected MouseListener createMouseListener() {
775                 return new ML();
776         }
777
778         private class ML extends MouseAdapter {
779                 private static final long serialVersionUID = 8526890859876770905L;
780
781                 @Override
782                 public void mouseDoubleClick(MouseEvent e) {
783                         if (e.button == 1) {
784                                 Control source = (Control) e.getSource();
785                                 if (getCmsEditable().canEdit()) {
786                                         if (getCmsEditable().isEditing() && !(getEdited() instanceof Img)) {
787                                                 if (source == mainSection)
788                                                         return;
789                                                 EditablePart part = findDataParent(source);
790                                                 upload(part);
791                                         } else {
792                                                 getCmsEditable().startEditing();
793                                         }
794                                 }
795                         }
796                 }
797
798                 @Override
799                 public void mouseDown(MouseEvent e) {
800                         if (getCmsEditable().isEditing()) {
801                                 if (e.button == 1) {
802                                         Control source = (Control) e.getSource();
803                                         EditablePart composite = findDataParent(source);
804                                         Point point = new Point(e.x, e.y);
805                                         if (!(composite instanceof Img))
806                                                 edit(composite, source.toDisplay(point));
807                                 } else if (e.button == 3) {
808                                         EditablePart composite = findDataParent((Control) e.getSource());
809                                         if (styledTools != null)
810                                                 styledTools.show(composite, new Point(e.x, e.y));
811                                 }
812                         }
813                 }
814
815                 @Override
816                 public void mouseUp(MouseEvent e) {
817                 }
818         }
819
820         // FILE UPLOAD LISTENER
821         private class FUL implements FileUploadListener {
822                 public void uploadProgress(FileUploadEvent event) {
823                         // TODO Monitor upload progress
824                 }
825
826                 public void uploadFailed(FileUploadEvent event) {
827                         throw new CmsException("Upload failed " + event, event.getException());
828                 }
829
830                 public void uploadFinished(FileUploadEvent event) {
831                         for (FileDetails file : event.getFileDetails()) {
832                                 if (log.isDebugEnabled())
833                                         log.debug("Received: " + file.getFileName());
834                         }
835                         mainSection.getDisplay().syncExec(new Runnable() {
836                                 @Override
837                                 public void run() {
838                                         saveEdit();
839                                 }
840                         });
841                         FileUploadHandler uploadHandler = (FileUploadHandler) event.getSource();
842                         uploadHandler.dispose();
843                 }
844         }
845 }