Project

General

Profile

Download (34.9 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2017 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.vaadin.mvp;
10

    
11
import java.util.ArrayList;
12
import java.util.Arrays;
13
import java.util.HashSet;
14
import java.util.List;
15
import java.util.Map;
16
import java.util.Optional;
17
import java.util.Set;
18
import java.util.Stack;
19

    
20
import org.apache.log4j.Level;
21
import org.apache.log4j.Logger;
22
import org.vaadin.spring.events.EventScope;
23

    
24
import com.vaadin.data.Validator.InvalidValueException;
25
import com.vaadin.data.fieldgroup.BeanFieldGroup;
26
import com.vaadin.data.fieldgroup.FieldGroup;
27
import com.vaadin.data.fieldgroup.FieldGroup.CommitEvent;
28
import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
29
import com.vaadin.data.fieldgroup.FieldGroup.CommitHandler;
30
import com.vaadin.data.fieldgroup.FieldGroup.FieldGroupInvalidValueException;
31
import com.vaadin.server.AbstractErrorMessage.ContentMode;
32
import com.vaadin.server.ErrorMessage.ErrorLevel;
33
import com.vaadin.server.FontAwesome;
34
import com.vaadin.server.UserError;
35
import com.vaadin.shared.ui.MarginInfo;
36
import com.vaadin.ui.AbstractComponentContainer;
37
import com.vaadin.ui.AbstractField;
38
import com.vaadin.ui.AbstractLayout;
39
import com.vaadin.ui.AbstractOrderedLayout;
40
import com.vaadin.ui.Alignment;
41
import com.vaadin.ui.Button;
42
import com.vaadin.ui.Button.ClickListener;
43
import com.vaadin.ui.CheckBox;
44
import com.vaadin.ui.Component;
45
import com.vaadin.ui.CssLayout;
46
import com.vaadin.ui.Field;
47
import com.vaadin.ui.GridLayout;
48
import com.vaadin.ui.GridLayout.OutOfBoundsException;
49
import com.vaadin.ui.GridLayout.OverlapsException;
50
import com.vaadin.ui.HasComponents;
51
import com.vaadin.ui.HorizontalLayout;
52
import com.vaadin.ui.Label;
53
import com.vaadin.ui.Layout;
54
import com.vaadin.ui.Layout.MarginHandler;
55
import com.vaadin.ui.Notification;
56
import com.vaadin.ui.Notification.Type;
57
import com.vaadin.ui.PopupDateField;
58
import com.vaadin.ui.TextField;
59
import com.vaadin.ui.UI;
60
import com.vaadin.ui.VerticalLayout;
61
import com.vaadin.ui.themes.ValoTheme;
62

    
63
import eu.etaxonomy.cdm.database.PermissionDeniedException;
64
import eu.etaxonomy.cdm.vaadin.component.TextFieldNFix;
65
import eu.etaxonomy.cdm.vaadin.component.dialog.ContinueAlternativeCancelDialog;
66
import eu.etaxonomy.cdm.vaadin.event.EditorActionContext;
67
import eu.etaxonomy.cdm.vaadin.event.EditorActionContextFormat;
68
import eu.etaxonomy.cdm.vaadin.event.EditorActionContextFormatter;
69
import eu.etaxonomy.vaadin.component.NestedFieldGroup;
70
import eu.etaxonomy.vaadin.component.SwitchableTextField;
71
import eu.etaxonomy.vaadin.event.FieldReplaceEvent;
72
import eu.etaxonomy.vaadin.mvp.event.EditorDeleteEvent;
73
import eu.etaxonomy.vaadin.mvp.event.EditorPreSaveEvent;
74
import eu.etaxonomy.vaadin.mvp.event.EditorSaveEvent;
75
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent;
76
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent.Reason;
77
import eu.etaxonomy.vaadin.util.PropertyIdPath;
78

    
79
/**
80
 *
81
 * Optional with a delete button which can be enabled with {@link #withDeleteButton(boolean)}
82
 *
83
 * @author a.kohlbecker
84
 * @since Apr 5, 2017
85
 *
86
 */
87
public abstract class AbstractPopupEditor<DTO extends Object, P extends AbstractEditorPresenter<DTO, ? extends ApplicationView>>
88
    extends AbstractPopupView<P> {
89

    
90
    /**
91
     *
92
     */
93
    private static final String READ_ONLY_MESSAGE_TEXT = "The editor is in read-only mode. Your authorities are not sufficient to edit this data.";
94

    
95
    public static final Logger logger = Logger.getLogger(AbstractPopupEditor.class);
96

    
97
    private BeanFieldGroup<DTO> fieldGroup;
98

    
99
    private VerticalLayout mainLayout;
100

    
101
    private Layout fieldLayout;
102

    
103
    private HorizontalLayout buttonLayout;
104

    
105
    private Button save;
106

    
107
    private Button cancel;
108

    
109
    private Button delete;
110

    
111
    private CssLayout toolBar = new CssLayout();
112

    
113
    private CssLayout toolBarButtonGroup = new CssLayout();
114

    
115
    private Label contextBreadcrumbsLabel = new Label();
116

    
117
    private Label statusMessageLabel = new Label();
118

    
119
    Set<String> statusMessages = new HashSet<>();
120

    
121
    private GridLayout _gridLayoutCache;
122

    
123
    private boolean isBeanLoaded;
124

    
125
    private Stack<EditorActionContext> context = new Stack<EditorActionContext>();
126

    
127
    private boolean isContextUpdated;
128

    
129
    private boolean isAdvancedMode = false;
130

    
131
    protected List<Component> advancedModeComponents = new ArrayList<>();
132

    
133
    private Button advancedModeButton;
134

    
135
    private EditorFormConfigurator<? extends AbstractPopupEditor<DTO, P>> editorComponentsConfigurator;
136

    
137
    public AbstractPopupEditor(Layout layout, Class<DTO> dtoType) {
138

    
139
        mainLayout = new VerticalLayout();
140
        // IMPORTANT: mainLayout must be set to full size otherwise the
141
        // popup window may have problems with automatic resizing of its
142
        // content.
143
        mainLayout.setSizeFull();
144

    
145
        setCompositionRoot(mainLayout);
146

    
147
        fieldGroup = new BeanFieldGroup<>(dtoType);
148
        fieldGroup.addCommitHandler(new SaveHandler());
149

    
150
        toolBar.addStyleName(ValoTheme.WINDOW_TOP_TOOLBAR);
151
        toolBar.setWidth(100, Unit.PERCENTAGE);
152
        contextBreadcrumbsLabel.setId("context-breadcrumbs");
153
        contextBreadcrumbsLabel.setWidthUndefined();
154
        contextBreadcrumbsLabel.setContentMode(com.vaadin.shared.ui.label.ContentMode.HTML);
155
        toolBar.addComponent(contextBreadcrumbsLabel);
156
        toolBarButtonGroup.addStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
157
        toolBarButtonGroup.setWidthUndefined();
158
        toolBar.addComponent(toolBarButtonGroup);
159
        toolBar.setVisible(false);
160

    
161
        fieldLayout = layout;
162
        fieldLayout.setWidthUndefined();
163
        if(fieldLayout instanceof AbstractOrderedLayout){
164
            ((AbstractOrderedLayout)fieldLayout).setSpacing(true);
165
        }
166
        if(MarginHandler.class.isAssignableFrom(fieldLayout.getClass())){
167
            ((MarginHandler)fieldLayout).setMargin(new MarginInfo(false, true, true, true));
168
        }
169

    
170
        buttonLayout = new HorizontalLayout();
171
        buttonLayout.setStyleName(ValoTheme.WINDOW_BOTTOM_TOOLBAR);
172
        buttonLayout.setWidth(100, Unit.PERCENTAGE);
173
        buttonLayout.setSpacing(true);
174

    
175
        save = new Button("Save", FontAwesome.SAVE);
176
        save.setStyleName(ValoTheme.BUTTON_PRIMARY);
177
        save.addClickListener(e -> save());
178

    
179
        cancel = new Button("Cancel", FontAwesome.REMOVE);
180
        cancel.addClickListener(e -> cancelEditorDialog());
181

    
182
        delete = new Button("Delete", FontAwesome.TRASH);
183
        delete.setStyleName(ValoTheme.BUTTON_DANGER);
184
        delete.addClickListener(e -> delete());
185
        delete.setVisible(false);
186

    
187
        buttonLayout.addComponents(delete, save, cancel);
188
        // delete is initially invisible, let save take all space
189
        buttonLayout.setExpandRatio(save, 1);
190
        buttonLayout.setComponentAlignment(delete, Alignment.TOP_RIGHT);
191
        buttonLayout.setComponentAlignment(save, Alignment.TOP_RIGHT);
192
        buttonLayout.setComponentAlignment(cancel, Alignment.TOP_RIGHT);
193

    
194
        statusMessageLabel.setWidthUndefined();
195

    
196
        mainLayout.addComponents(toolBar, fieldLayout, statusMessageLabel, buttonLayout);
197
        mainLayout.setComponentAlignment(statusMessageLabel, Alignment.BOTTOM_RIGHT);
198
        mainLayout.setComponentAlignment(toolBar, Alignment.TOP_RIGHT);
199

    
200
        updateToolBarVisibility();
201
    }
202

    
203
    protected VerticalLayout getMainLayout() {
204
        return mainLayout;
205
    }
206

    
207
    protected Layout getFieldLayout() {
208
        return fieldLayout;
209
    }
210

    
211
    /**
212
     * @return
213
     */
214
    private GridLayout gridLayout() {
215
        if(_gridLayoutCache == null){
216
            if(fieldLayout instanceof GridLayout){
217
                _gridLayoutCache = (GridLayout)fieldLayout;
218
            } else {
219
                throw new RuntimeException("The fieldlayout of this editor is not a GridLayout");
220
            }
221
        }
222
        return _gridLayoutCache;
223
    }
224

    
225
    @Override
226
    public void setReadOnly(boolean readOnly) {
227
        super.setReadOnly(readOnly);
228
        if(readOnly){
229
            statusMessageLabel.setValue(READ_ONLY_MESSAGE_TEXT);
230
            statusMessageLabel.addStyleName(ValoTheme.LABEL_COLORED);
231
        } else {
232
            statusMessageLabel.setValue(null);
233
        }
234
        statusMessageLabel.setVisible(readOnly);
235
        save.setVisible(!readOnly);
236
        delete.setVisible(!readOnly);
237
        cancel.setCaption(readOnly ? "Close" : "Cancel");
238
        recursiveReadonly(readOnly, (AbstractComponentContainer)getFieldLayout());
239
    }
240

    
241
    /**
242
     * @param readOnly
243
     * @param layout
244
     */
245
    protected void recursiveReadonly(boolean readOnly, AbstractComponentContainer layout) {
246
        for(Component c : layout){
247
            c.setReadOnly(readOnly);
248
            if(c instanceof AbstractComponentContainer){
249
                recursiveReadonly(readOnly, (AbstractComponentContainer)c);
250
            }
251
        }
252
    }
253

    
254
    /**
255
     * @return
256
     * @return
257
     */
258
    protected AbstractLayout getToolBar() {
259
        return toolBar;
260
    }
261

    
262
    /**
263
     * @return
264
     * @return
265
     */
266
    protected void toolBarAdd(Component c) {
267
        toolBar.addComponent(c, toolBar.getComponentIndex(toolBarButtonGroup) - 1);
268
        updateToolBarVisibility();
269
    }
270

    
271
    /**
272
     * @return
273
     * @return
274
     */
275
    protected void toolBarButtonGroupAdd(Component c) {
276
        toolBarButtonGroup.addComponent(c);
277
        updateToolBarVisibility();
278
    }
279

    
280
    /**
281
     * @return
282
     * @return
283
     */
284
    protected void toolBarButtonGroupRemove(Component c) {
285
        toolBarButtonGroup.removeComponent(c);
286
        updateToolBarVisibility();
287
    }
288

    
289
    /**
290
     *
291
     */
292
    private void updateToolBarVisibility() {
293
        boolean showToolbar = toolBarButtonGroup.getComponentCount() + toolBar.getComponentCount() > 1;
294
        toolBar.setVisible(toolBarButtonGroup.getComponentCount() + toolBar.getComponentCount() > 1);
295
        if(!showToolbar){
296
            mainLayout.setMargin(new MarginInfo(true, false, false, false));
297
        } else {
298
            mainLayout.setMargin(false);
299
        }
300

    
301
    }
302

    
303
    /**
304
     * The top tool-bar is initially invisible.
305
     *
306
     * @param visible
307
     */
308
    protected void setToolBarVisible(boolean visible){
309
        toolBar.setVisible(true);
310
    }
311

    
312
    /**
313
     * @return the isAdvancedMode
314
     */
315
    public boolean isAdvancedMode() {
316
        return isAdvancedMode;
317
    }
318

    
319
    /**
320
     * @param isAdvancedMode the isAdvancedMode to set
321
     */
322
    public void setAdvancedMode(boolean isAdvancedMode) {
323
        this.isAdvancedMode = isAdvancedMode;
324
        advancedModeComponents.forEach(c -> c.setVisible(isAdvancedMode));
325
    }
326

    
327
    public void setAdvancedModeEnabled(boolean activate){
328
        if(activate && advancedModeButton == null){
329
            advancedModeButton = new Button(FontAwesome.WRENCH); // FontAwesome.FLASK
330
            advancedModeButton.setIconAlternateText("Advanced mode");
331
            advancedModeButton.addStyleName(ValoTheme.BUTTON_TINY);
332
            toolBarButtonGroupAdd(advancedModeButton);
333
            advancedModeButton.addClickListener(e -> {
334
                setAdvancedMode(!isAdvancedMode);
335
                }
336
            );
337

    
338
        } else if(advancedModeButton != null) {
339
            toolBarButtonGroupRemove(advancedModeButton);
340
            advancedModeButton = null;
341
        }
342
    }
343

    
344
    public void registerAdvancedModeComponents(Component ... c){
345
        advancedModeComponents.addAll(Arrays.asList(c));
346
    }
347

    
348

    
349
    // ------------------------ event handler ------------------------ //
350

    
351
    private class SaveHandler implements CommitHandler {
352

    
353
        private static final long serialVersionUID = 2047223089707080659L;
354

    
355
        @Override
356
        public void preCommit(CommitEvent commitEvent) throws CommitException {
357
            logger.debug("preCommit(), publishing EditorPreSaveEvent");
358
            // notify the presenter to start a transaction
359
            viewEventBus.publish(this, new EditorPreSaveEvent<DTO>(AbstractPopupEditor.this, getBean()));
360
        }
361

    
362
        @Override
363
        public void postCommit(CommitEvent commitEvent) throws CommitException {
364
            try {
365
                if(logger.isTraceEnabled()){
366
                    logger.trace("postCommit() publishing EditorSaveEvent for " + getBean().toString());
367
                }
368
                // notify the presenter to persist the bean and to commit the transaction
369
                viewEventBus.publish(this, new EditorSaveEvent<DTO>(AbstractPopupEditor.this, getBean()));
370
                if(logger.isTraceEnabled()){
371
                    logger.trace("postCommit() publishing DoneWithPopupEvent");
372
                }
373
                // notify the NavigationManagerBean to close the window and to dispose the view
374
                viewEventBus.publish(EventScope.UI, this, new DoneWithPopupEvent(AbstractPopupEditor.this, Reason.SAVE));
375
            } catch (Exception e) {
376
                logger.error(e);
377
                throw new CommitException("Failed to store data to backend", e);
378
            }
379
        }
380
    }
381

    
382
    protected void addCommitHandler(CommitHandler commitHandler) {
383
        fieldGroup.addCommitHandler(commitHandler);
384
    }
385

    
386
    protected void cancelEditorDialog(){
387

    
388
        if(fieldGroup.isModified()){
389

    
390
            ContinueAlternativeCancelDialog editorModifiedDialog = new ContinueAlternativeCancelDialog(
391
                    "Cancel editor",
392
                    "<p>The editor has been modified.<br>Do you want to save your changes or discard them?<p>",
393
                    "Discard",
394
                    "Save");
395
            ClickListener saveListener = e -> {editorModifiedDialog.close(); save();};
396
            ClickListener discardListener = e -> {editorModifiedDialog.close(); cancel();};
397
            ClickListener cancelListener = e -> editorModifiedDialog.close();
398
            editorModifiedDialog.addAlternativeClickListener(saveListener);
399
            editorModifiedDialog.addContinueClickListener(discardListener);
400
            editorModifiedDialog.addCancelClickListener(cancelListener);
401

    
402
            UI.getCurrent().addWindow(editorModifiedDialog);
403
        } else {
404
            cancel();
405
        }
406
    }
407

    
408

    
409
    /**
410
     * Cancel editing and discard all modifications.
411
     */
412
    @Override
413
    public void cancel() {
414
        fieldGroup.discard();
415
        viewEventBus.publish(EventScope.UI, this, new DoneWithPopupEvent(this, Reason.CANCEL));
416
    }
417

    
418
    /**
419
     * @return
420
     */
421
    private void delete() {
422
        viewEventBus.publish(this, new EditorDeleteEvent<DTO>(this, fieldGroup.getItemDataSource().getBean()));
423
        viewEventBus.publish(EventScope.UI, this, new DoneWithPopupEvent(this, Reason.DELETE));
424
    }
425

    
426
    /**
427
     * Save the changes made in the editor.
428
     */
429
    private void save() {
430
        try {
431
            fieldGroup.commit();
432
        } catch (CommitException e) {
433
            fieldGroup.getFields().forEach(f -> ((AbstractField<?>)f).setValidationVisible(true));
434
            Throwable cause = e.getCause();
435
            while(cause != null) {
436
                if(cause instanceof FieldGroupInvalidValueException){
437
                    FieldGroupInvalidValueException invalidValueException = (FieldGroupInvalidValueException)cause;
438
                    updateFieldNotifications(invalidValueException.getInvalidFields());
439
                    int invalidFieldsCount = invalidValueException.getInvalidFields().size();
440
                    Notification.show("The entered data in " + invalidFieldsCount + " field" + (invalidFieldsCount > 1 ? "s": "") + " is incomplete or invalid.");
441
                    break;
442
                } else if(cause instanceof PermissionDeniedException){
443
                    PermissionDeniedException permissionDeniedException = (PermissionDeniedException)cause;
444
                    Notification.show("Permission denied", permissionDeniedException.getMessage(), Type.ERROR_MESSAGE);
445
                    break;
446
                }
447
                cause = cause.getCause();
448
            }
449
            if(cause == null){
450
                // no known exception type found
451
                logger.error("Unhandled exception", e);
452
                throw new PopupEditorException("Error saving popup editor", this, e);
453
            }
454

    
455
        }
456
    }
457

    
458
    /**
459
     * @param invalidFields
460
     */
461
    private void updateFieldNotifications(Map<Field<?>, InvalidValueException> invalidFields) {
462
        for(Field<?> f : invalidFields.keySet()){
463
            if(f instanceof AbstractField){
464
                String message = invalidFields.get(f).getHtmlMessage();
465
                ((AbstractField)f).setComponentError(new UserError(message, ContentMode.HTML, ErrorLevel.ERROR));
466
            }
467
        }
468

    
469
    }
470

    
471
    // ------------------------ field adding methods ------------------------ //
472

    
473

    
474
    protected TextField addTextField(String caption, String propertyId) {
475
        return addField(new TextFieldNFix(caption), propertyId);
476
    }
477

    
478
    protected TextField addTextField(String caption, String propertyId, int column1, int row1,
479
            int column2, int row2)
480
            throws OverlapsException, OutOfBoundsException {
481
        return addField(new TextFieldNFix(caption), propertyId, column1, row1, column2, row2);
482
    }
483

    
484
    protected TextField addTextField(String caption, String propertyId, int column, int row)
485
            throws OverlapsException, OutOfBoundsException {
486
        return addField(new TextFieldNFix(caption), propertyId, column, row);
487
    }
488

    
489
    protected SwitchableTextField addSwitchableTextField(String caption, String textPropertyId, String switchPropertyId, int column1, int row1,
490
            int column2, int row2)
491
            throws OverlapsException, OutOfBoundsException {
492

    
493
        SwitchableTextField field = new SwitchableTextField(caption);
494
        field.bindTo(fieldGroup, textPropertyId, switchPropertyId);
495
        addComponent(field, column1, row1, column2, row2);
496
        return field;
497
    }
498

    
499
    protected SwitchableTextField addSwitchableTextField(String caption, String textPropertyId, String switchPropertyId, int column, int row)
500
            throws OverlapsException, OutOfBoundsException {
501

    
502
        SwitchableTextField field = new SwitchableTextField(caption);
503
        field.bindTo(fieldGroup, textPropertyId, switchPropertyId);
504
        addComponent(field, column, row);
505
        return field;
506
    }
507

    
508
    protected PopupDateField addDateField(String caption, String propertyId) {
509
        return addField(new PopupDateField(caption), propertyId);
510
    }
511

    
512
    protected CheckBox addCheckBox(String caption, String propertyId) {
513
        return addField(new CheckBox(caption), propertyId);
514
    }
515

    
516
    protected CheckBox addCheckBox(String caption, String propertyId, int column, int row){
517
        return addField(new CheckBox(caption), propertyId, column, row);
518
    }
519

    
520
    protected <T extends Field> T addField(T field, String propertyId) {
521
        fieldGroup.bind(field, propertyId);
522
        if(NestedFieldGroup.class.isAssignableFrom(field.getClass())){
523
            ((NestedFieldGroup)field).registerParentFieldGroup(fieldGroup);
524
        }
525
        addComponent(field);
526
        return field;
527
    }
528

    
529
    /**
530
     * Can only be used if the <code>fieldlayout</code> is a GridLayout.
531
     *
532
     * @param field
533
     *            the field to be added, not <code>null</code>.
534
     * @param propertyId
535
     * @param column
536
     *            the column index, starting from 0.
537
     * @param row
538
     *            the row index, starting from 0.
539
     * @throws OverlapsException
540
     *             if the new component overlaps with any of the components
541
     *             already in the grid.
542
     * @throws OutOfBoundsException
543
     *             if the cell is outside the grid area.
544
     */
545
    protected <T extends Field> T addField(T field, String propertyId, int column, int row)
546
            throws OverlapsException, OutOfBoundsException {
547
        fieldGroup.bind(field, propertyId);
548
        if(NestedFieldGroup.class.isAssignableFrom(field.getClass())){
549
            ((NestedFieldGroup)field).registerParentFieldGroup(fieldGroup);
550
        }
551
        addComponent(field, column, row);
552
        return field;
553
    }
554

    
555
    /**
556
     * Can only be used if the <code>fieldlayout</code> is a GridLayout.
557
     *
558
     * @param field
559
     * @param propertyId
560
     * @param column1
561
     * @param row1
562
     * @param column2
563
     * @param row2
564
     * @return
565
     * @throws OverlapsException
566
     * @throws OutOfBoundsException
567
     */
568
    protected <T extends Field> T addField(T field, String propertyId, int column1, int row1,
569
            int column2, int row2)
570
            throws OverlapsException, OutOfBoundsException {
571
        if(propertyId != null){
572
            fieldGroup.bind(field, propertyId);
573
            if(NestedFieldGroup.class.isAssignableFrom(field.getClass())){
574
                ((NestedFieldGroup)field).registerParentFieldGroup(fieldGroup);
575
            }
576
        }
577
        addComponent(field, column1, row1, column2, row2);
578
        return field;
579
    }
580

    
581
    protected Field<?> getField(Object propertyId){
582
        return fieldGroup.getField(propertyId);
583
    }
584

    
585
    public PropertyIdPath boundPropertyIdPath(Field<?> field){
586

    
587
        PropertyIdPath propertyIdPath = null;
588
        Object propertyId = fieldGroup.getPropertyId(field);
589

    
590
        if(propertyId == null){
591
            // not found in the editor field group. Maybe the field is bound to a nested fieldgroup?
592
            // 1. find the NestedFieldGroup implementations from the field up to the editor
593
            logger.setLevel(Level.DEBUG);
594
            PropertyIdPath nestedPropertyIds = new PropertyIdPath();
595
            Field parentField = field;
596
            HasComponents parentComponent = parentField.getParent();
597
            logger.debug("field: " + parentField.getClass().getSimpleName());
598
            while(parentComponent != null){
599
                logger.debug("parentComponent: " + parentComponent.getClass().getSimpleName());
600
                if(NestedFieldGroup.class.isAssignableFrom(parentComponent.getClass()) && AbstractField.class.isAssignableFrom(parentComponent.getClass())){
601
                    Optional<FieldGroup> parentFieldGroup = ((NestedFieldGroup)parentComponent).getFieldGroup();
602
                    if(parentFieldGroup.isPresent()){
603
                        Object propId = parentFieldGroup.get().getPropertyId(parentField);
604
                        if(propId != null){
605
                            logger.debug("propId: " + propId.toString());
606
                            nestedPropertyIds.addParent(propId);
607
                        }
608
                        logger.debug("parentField: " + parentField.getClass().getSimpleName());
609
                        parentField = (Field)parentComponent;
610
                    } else {
611
                        logger.debug("parentFieldGroup is null, continuing ...");
612
                    }
613
                } else if(parentComponent == this) {
614
                    // we reached the editor itself
615
                    Object propId = fieldGroup.getPropertyId(parentField);
616
                    if(propId != null){
617
                        logger.debug("propId: " + propId.toString());
618
                        nestedPropertyIds.addParent(propId);
619
                    }
620
                    propertyIdPath = nestedPropertyIds;
621
                    break;
622
                }
623
                parentComponent = parentComponent.getParent();
624
            }
625
            // 2. check the NestedFieldGroup binding the field is direct or indirect child component of the editor
626
//            NO lONGER NEEDED
627
//            parentComponent = parentField.getParent(); // get component containing the last parent field found
628
//            while(true){
629
//                if(parentComponent == getFieldLayout()){
630
//                    propertyIdPath = nestedPropertyIds;
631
//                    break;
632
//                }
633
//                parentComponent = parentComponent.getParent();
634
//            }
635
        } else {
636
            propertyIdPath = new PropertyIdPath(propertyId);
637
        }
638
        return propertyIdPath;
639
    }
640

    
641
    protected void addComponent(Component component) {
642
        fieldLayout.addComponent(component);
643
        applyDefaultComponentStyles(component);
644
    }
645

    
646
    protected void bindField(Field field, String propertyId){
647
        fieldGroup.bind(field, propertyId);
648
    }
649

    
650
    protected void unbindField(Field field){
651
        fieldGroup.unbind(field);
652
    }
653

    
654
    /**
655
     * @param component
656
     */
657
    public void applyDefaultComponentStyles(Component component) {
658
        component.addStyleName(getDefaultComponentStyles());
659
    }
660

    
661
    protected abstract String getDefaultComponentStyles();
662

    
663
    /**
664
     * Can only be used if the <code>fieldlayout</code> is a GridLayout.
665
     * <p>
666
     * Adds the component to the grid in cells column1,row1 (NortWest corner of
667
     * the area.) End coordinates (SouthEast corner of the area) are the same as
668
     * column1,row1. The coordinates are zero-based. Component width and height
669
     * is 1.
670
     *
671
     * @param component
672
     *            the component to be added, not <code>null</code>.
673
     * @param column
674
     *            the column index, starting from 0.
675
     * @param row
676
     *            the row index, starting from 0.
677
     * @throws OverlapsException
678
     *             if the new component overlaps with any of the components
679
     *             already in the grid.
680
     * @throws OutOfBoundsException
681
     *             if the cell is outside the grid area.
682
     */
683
    public void addComponent(Component component, int column, int row)
684
            throws OverlapsException, OutOfBoundsException {
685
        applyDefaultComponentStyles(component);
686
        gridLayout().addComponent(component, column, row, column, row);
687
    }
688

    
689
    /**
690
     * Can only be used if the <code>fieldlayout</code> is a GridLayout.
691
     * <p>
692
     * Adds a component to the grid in the specified area. The area is defined
693
     * by specifying the upper left corner (column1, row1) and the lower right
694
     * corner (column2, row2) of the area. The coordinates are zero-based.
695
     * </p>
696
     *
697
     * <p>
698
     * If the area overlaps with any of the existing components already present
699
     * in the grid, the operation will fail and an {@link OverlapsException} is
700
     * thrown.
701
     * </p>
702
     *
703
     * @param component
704
     *            the component to be added, not <code>null</code>.
705
     * @param column1
706
     *            the column of the upper left corner of the area <code>c</code>
707
     *            is supposed to occupy. The leftmost column has index 0.
708
     * @param row1
709
     *            the row of the upper left corner of the area <code>c</code> is
710
     *            supposed to occupy. The topmost row has index 0.
711
     * @param column2
712
     *            the column of the lower right corner of the area
713
     *            <code>c</code> is supposed to occupy.
714
     * @param row2
715
     *            the row of the lower right corner of the area <code>c</code>
716
     *            is supposed to occupy.
717
     * @throws OverlapsException
718
     *             if the new component overlaps with any of the components
719
     *             already in the grid.
720
     * @throws OutOfBoundsException
721
     *             if the cells are outside the grid area.
722
     */
723
    public void addComponent(Component component, int column1, int row1,
724
            int column2, int row2)
725
            throws OverlapsException, OutOfBoundsException {
726
        applyDefaultComponentStyles(component);
727
        gridLayout().addComponent(component, column1, row1, column2, row2);
728
    }
729

    
730
    public void setSaveButtonEnabled(boolean enabled){
731
        save.setEnabled(enabled);
732
    }
733

    
734
    public void withDeleteButton(boolean withDelete){
735

    
736
        if(withDelete){
737
            buttonLayout.setExpandRatio(save, 0);
738
            buttonLayout.setExpandRatio(delete, 1);
739
        } else {
740
            buttonLayout.setExpandRatio(save, 1);
741
            buttonLayout.setExpandRatio(delete, 0);
742
        }
743
        delete.setVisible(withDelete);
744
    }
745

    
746
    public boolean addStatusMessage(String message){
747
        boolean returnVal = statusMessages.add(message);
748
        updateStatusLabel();
749
        return returnVal;
750
    }
751

    
752
    public boolean removeStatusMessage(String message){
753
        boolean returnVal = statusMessages.remove(message);
754
        updateStatusLabel();
755
        return returnVal;
756
    }
757

    
758
    /**
759
     *
760
     */
761
    private void updateStatusLabel() {
762
        String text = "";
763
        for(String s : statusMessages){
764
            text += s + " ";
765
        }
766
        statusMessageLabel.setValue(text);
767
        statusMessageLabel.setVisible(!text.isEmpty());
768
        statusMessageLabel.addStyleName(ValoTheme.LABEL_COLORED);
769
    }
770

    
771
    private void updateContextBreadcrumbs() {
772

    
773
        List<EditorActionContext> contextInfo = new ArrayList<>(getEditorActionContext());
774
        String breadcrumbs = "";
775
        EditorActionContextFormatter formatter = new EditorActionContextFormatter();
776

    
777
        int cnt = 0;
778
        for(EditorActionContext cntxt : contextInfo){
779
            cnt++;
780
            boolean isLast = cnt == contextInfo.size();
781
            boolean isFirst = cnt == 1;
782

    
783
            boolean doClass = false; // will be removed in future
784
            boolean classNameForMissingPropertyPath = true; // !doClass;
785
            boolean doProperties = true;
786
            boolean doCreateOrNew = !isFirst;
787
            String contextmarkup = formatter.format(
788
                    cntxt,
789
                    new EditorActionContextFormat(doClass, doProperties, classNameForMissingPropertyPath, doCreateOrNew,
790
                            EditorActionContextFormat.TargetInfoType.FIELD_CAPTION, (isLast ? "active" : ""))
791
                    );
792
//            if(!isLast){
793
//                contextmarkup += " " + FontAwesome.ANGLE_RIGHT.getHtml() + " ";
794
//            }
795
            if(isLast){
796
                contextmarkup = "<li><span class=\"crumb active\">" + contextmarkup + "</span></li>";
797
            } else {
798
                contextmarkup = "<li><span class=\"crumb\">" + contextmarkup + "</span></li>";
799
            }
800
            breadcrumbs += contextmarkup;
801
        }
802
        contextBreadcrumbsLabel.setValue("<ul class=\"breadcrumbs\">" + breadcrumbs + "</ul>");
803
    }
804

    
805
    // ------------------------ data binding ------------------------ //
806

    
807
    protected void bindDesign(Component component) {
808
        fieldLayout.removeAllComponents();
809
        fieldGroup.bindMemberFields(component);
810
        fieldLayout.addComponent(component);
811
    }
812

    
813

    
814
    public final void loadInEditor(Object identifier) {
815

    
816
        DTO beanToEdit = getPresenter().loadBeanById(identifier);
817
        fieldGroup.setItemDataSource(beanToEdit);
818
        afterItemDataSourceSet();
819
        getPresenter().onViewFormReady(beanToEdit);
820
        updateContextBreadcrumbs();
821
        isBeanLoaded = true;
822
    }
823

    
824
    /**
825
     * Passes the beanInstantiator to the presenter method {@link AbstractEditorPresenter#setBeanInstantiator(BeanInstantiator)}
826
     *
827
     * @param beanInstantiator
828
     */
829
    public final void setBeanInstantiator(BeanInstantiator<DTO> beanInstantiator) {
830
        if(AbstractCdmEditorPresenter.class.isAssignableFrom(getPresenter().getClass())){
831
            ((CdmEditorPresenterBase)getPresenter()).setBeanInstantiator(beanInstantiator);
832
        } else {
833
            throw new RuntimeException("BeanInstantiator can only be set for popup editors with a peresenter of the type CdmEditorPresenterBase");
834
        }
835
    }
836

    
837
    /**
838
     * Returns the bean contained in the itemDatasource of the fieldGroup.
839
     *
840
     * @return
841
     */
842
    public DTO getBean() {
843
        if(fieldGroup.getItemDataSource() != null){
844
            return fieldGroup.getItemDataSource().getBean();
845

    
846
        }
847
        return null;
848
    }
849

    
850
    /**
851
     * @return true once the bean has been loaded indicating that all fields have
852
     *   been setup configured so that the editor is ready for use.
853
     */
854
    public boolean isBeanLoaded() {
855
        return isBeanLoaded;
856
    }
857

    
858
    /**
859
     * This method should only be used by the presenter of this view
860
     *
861
     * @param bean
862
     */
863
    protected void updateItemDataSource(DTO bean) {
864
        fieldGroup.getItemDataSource().setBean(bean);
865
    }
866

    
867
    /**
868
     * This method is called after setting the item data source whereby the
869
     * {@link FieldGroup#configureField(Field<?> field)} method will be called.
870
     * In this method all fields are set to default states defined for the fieldGroup.
871
     * <p>
872
     * You can now implement this method if you need to modify the state or value of individual fields.
873
     */
874
    protected void afterItemDataSourceSet() {
875
        if(editorComponentsConfigurator != null){
876
            editorComponentsConfigurator.updateComponentStates(this);
877
        }
878
    }
879

    
880
    // ------------------------ issue related temporary solutions --------------------- //
881
    /**
882
     * Publicly accessible equivalent to getPreseneter(), needed for
883
     * managing the presenter listeners.
884
     * <p>
885
     * TODO: refactor the presenter listeners management to get rid of this method
886
     *
887
     * @return
888
     * @deprecated marked deprecated to emphasize on the special character of this method
889
     *    which should only be used internally see #6673
890
     */
891
    @Deprecated
892
    public P presenter() {
893
        return getPresenter();
894
    }
895

    
896
    /**
897
     * Returns the context of editor actions for this editor.
898
     * The context submitted with {@link #setParentContext(Stack)} will be updated
899
     * to represent the current context.
900
     *
901
     * @return the context
902
     */
903
    public Stack<EditorActionContext> getEditorActionContext() {
904
        if(!isContextUpdated){
905
            if(getBean() == null){
906
                throw new RuntimeException("getContext() is only possible after the bean is loaded");
907
            }
908
            context.push(new EditorActionContext(getBean(), this));
909
            isContextUpdated = true;
910
        }
911
        return context;
912
    }
913

    
914
    /**
915
     * Set the context of editor actions parent to this editor
916
     *
917
     * @param context the context to set
918
     */
919
    public void setParentEditorActionContext(Stack<EditorActionContext> context, Field<?> targetField) {
920
        if(context != null){
921
            this.context.addAll(context);
922
        }
923
        if(targetField != null){
924
            this.context.get(context.size() - 1).setTargetField(targetField);
925
        }
926
    }
927

    
928
    protected AbstractField<String> replaceComponent(String propertyId, AbstractField<String> oldField, AbstractField<String> newField, int column1, int row1, int column2,
929
            int row2) {
930
                String value = oldField.getValue();
931
                newField.setCaption(oldField.getCaption());
932
                GridLayout grid = (GridLayout)getFieldLayout();
933
                grid.removeComponent(oldField);
934

    
935
                unbindField(oldField);
936
                addField(newField, propertyId, column1, row1, column2, row2);
937
                getViewEventBus().publish(this, new FieldReplaceEvent(this, oldField, newField));
938
                // important: set newField value at last!
939
                newField.setValue(value);
940
                return newField;
941
            }
942

    
943
    public EditorFormConfigurator<? extends AbstractPopupEditor<DTO, P>> getEditorComponentsConfigurator() {
944
        return editorComponentsConfigurator;
945
    }
946

    
947
    public void setEditorComponentsConfigurator(
948
            EditorFormConfigurator<? extends AbstractPopupEditor<DTO, P>> editorComponentsConfigurator) {
949
        this.editorComponentsConfigurator = editorComponentsConfigurator;
950
    }
951

    
952
}
(6-6/15)