Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.swing / org.gvsig.fmap.dal.swing.impl / src / main / java / org / gvsig / featureform / swing / impl / DefaultJFeaturesForm.java @ 45366

History | View | Annotate | Download (33.7 KB)

1
/* gvSIG. Desktop Geographic Information System.
2
 *
3
 * Copyright ? 2007-2014 gvSIG Association
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18
 * MA  02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us
21
 * at info AT gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.featureform.swing.impl;
24

    
25
import java.awt.BorderLayout;
26
import java.awt.Dimension;
27
import java.awt.event.ActionEvent;
28
import java.awt.event.ComponentAdapter;
29
import java.awt.event.ComponentEvent;
30
import java.net.URL;
31
import java.util.ArrayList;
32
import java.util.Collection;
33
import java.util.List;
34
import javax.swing.AbstractAction;
35
import javax.swing.Action;
36
import static javax.swing.Action.ACTION_COMMAND_KEY;
37
import static javax.swing.Action.NAME;
38
import static javax.swing.Action.SHORT_DESCRIPTION;
39
import static javax.swing.Action.SMALL_ICON;
40

    
41
import javax.swing.JComponent;
42
import javax.swing.JOptionPane;
43
import javax.swing.JPanel;
44
import org.apache.commons.lang3.StringUtils;
45
import org.gvsig.expressionevaluator.Expression;
46
import org.gvsig.expressionevaluator.ExpressionEvaluatorLocator;
47
import org.gvsig.expressionevaluator.ExpressionUtils;
48

    
49
import org.slf4j.Logger;
50
import org.slf4j.LoggerFactory;
51

    
52
import org.gvsig.featureform.swing.JFeaturesForm;
53
import org.gvsig.fmap.dal.DALLocator;
54
import org.gvsig.fmap.dal.DataStore;
55
import org.gvsig.fmap.dal.StoresRepository;
56
import org.gvsig.fmap.dal.exception.DataException;
57
import org.gvsig.expressionevaluator.ExpressionEvaluator;
58
import org.gvsig.fmap.dal.feature.EditableFeature;
59
import org.gvsig.fmap.dal.feature.Feature;
60
import org.gvsig.fmap.dal.feature.FacadeOfAFeature;
61
import org.gvsig.fmap.dal.feature.FeatureQuery;
62
import org.gvsig.fmap.dal.feature.FeatureStore;
63
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
64
import org.gvsig.fmap.dal.feature.FeatureType;
65
import org.gvsig.fmap.dal.feature.paging.FeaturePagingHelper;
66
import org.gvsig.fmap.dal.swing.AbstractDALActionFactory.AbstractDALActionContext;
67
import org.gvsig.fmap.dal.swing.DALActionFactory;
68
import org.gvsig.fmap.dal.swing.DALSwingLocator;
69
import org.gvsig.fmap.dal.swing.DataSwingManager;
70
import org.gvsig.fmap.dal.swing.impl.DefaultDataSwingManager;
71
import org.gvsig.fmap.dal.swing.impl.actions.ShowFormAction.ShowFormActionFactory;
72
import org.gvsig.fmap.dal.swing.searchpanel.FeatureStoreSearchPanel;
73
import org.gvsig.fmap.dal.swing.searchpanel.SearchParameters;
74
import org.gvsig.tools.ToolsLocator;
75
import org.gvsig.tools.dispose.Disposable;
76
import org.gvsig.tools.dispose.DisposeUtils;
77
import org.gvsig.tools.dynform.AbortActionException;
78
import org.gvsig.tools.dynform.DynFormDefinition;
79
import org.gvsig.tools.dynform.DynFormLocator;
80
import org.gvsig.tools.dynform.DynFormManager;
81
import org.gvsig.tools.dynform.JDynForm;
82
import org.gvsig.tools.dynform.JDynFormSet;
83
import static org.gvsig.tools.dynform.JDynFormSet.ACTION_CANCEL_NEW;
84
import static org.gvsig.tools.dynform.JDynFormSet.ACTION_DELETE;
85
import static org.gvsig.tools.dynform.JDynFormSet.ACTION_NEW;
86
import static org.gvsig.tools.dynform.JDynFormSet.ACTION_SAVE;
87
import static org.gvsig.tools.dynform.JDynFormSet.ACTION_SEARCH;
88
import org.gvsig.tools.dynform.JDynFormSet.JDynFormSetListener;
89
import org.gvsig.tools.dynobject.DynClass;
90
import org.gvsig.tools.dynobject.DynObject;
91
import org.gvsig.tools.evaluator.Evaluator;
92
import org.gvsig.tools.exception.BaseException;
93
import org.gvsig.tools.i18n.I18nManager;
94
import org.gvsig.tools.observer.Observable;
95
import org.gvsig.tools.observer.Observer;
96
import org.gvsig.tools.service.ServiceException;
97
import org.gvsig.tools.swing.api.ToolsSwingLocator;
98
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
99
import org.gvsig.tools.swing.api.windowmanager.Dialog;
100
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
101
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
102
import org.gvsig.tools.swing.api.windowmanager.WindowManager.MODE;
103
import org.gvsig.tools.swing.icontheme.IconTheme;
104
import org.gvsig.tools.resourcesstorage.ResourcesStorage;
105
import org.gvsig.tools.script.ScriptManager;
106

    
107
/**
108
 * @author fdiaz
109
 *
110
 */
111
@SuppressWarnings("UseSpecificCatch")
112
public class DefaultJFeaturesForm implements JFeaturesForm, Disposable {
113

    
114
    private final String STARTEDITING_ACTION = "startEditing";
115
    private final String FINISHEDITING_ACTION = "finishEditing";
116
    private final String REFRESHFORM_ACTION = "refreshForm";
117

    
118

    
119
    public class DefaultFeaturesFormContext implements FeaturesFormContext {
120

    
121
        private DefaultFeaturesFormContext() {
122
            
123
        }
124

    
125
        @Override
126
        public FeatureStore getFeatureStore() {
127
            return store;
128
        }
129
        
130
        @Override
131
        public FeatureType getFeatureType() {
132
            try {
133
                return store.getDefaultFeatureType();
134
            } catch (DataException ex) {
135
                return null;
136
            }
137
        }
138
        
139
        @Override
140
        public ResourcesStorage getResourcesStorage() {
141
            if( store == null ) {
142
                return null;
143
            }
144
            return store.getResourcesStorage();
145
        }
146

    
147
        @Override
148
        public StoresRepository getStoresRepository() {
149
            if( store == null ) {
150
                return null;
151
            }
152
            return store.getStoresRepository();
153
        }
154

    
155
        @Override
156
        public ScriptManager getScriptManager() {
157
            return ExpressionEvaluatorLocator.getExpressionEvaluatorManager();
158
        }
159

    
160
        
161
    }
162
    
163
    private class FormActionContext extends AbstractDALActionContext {
164

    
165
        public FormActionContext() {
166
            super(ACTION_CONTEXT_NAME);
167
        }
168
        
169
        @Override
170
        public DataStore getStore() {
171
            return store;
172
        }
173

    
174
        @Override
175
        public FeatureQuery getQuery() {
176
          return currentQuery;
177
        }
178

    
179
        @Override
180
        public int getSelectedsCount() {
181
            return 0;
182
        }
183

    
184
        @Override
185
        public Expression getFilterForSelecteds() {
186
            return null;
187
        }
188

    
189
        @Override
190
        public JComponent getActionButton(String actionName) {
191
            if( formset == null ) {
192
                return null;
193
            }
194
            return formset.getActionButton(actionName);
195
        }
196
        
197
    }
198
    
199
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultJFeaturesForm.class);
200

    
201
    private static final int PAGE_SIZE = 10;
202
    private JPanel panel;
203
    private JDynFormSet formset;
204
    private FeatureStore store;
205
    private FeaturePagingHelper features;
206
    private DynFormDefinition definition = null;
207
    private FeatureQuery currentQuery;
208
    private List<Action> otherActions;
209

    
210
    public DefaultJFeaturesForm() {
211
        this.otherActions = new ArrayList<>();
212
        this.panel = new JPanel(new BorderLayout());
213
        this.panel.addComponentListener(new ComponentAdapter() {
214
            @Override
215
            public void componentHidden(ComponentEvent e) {
216
                dispose();
217
            }
218
        });
219
    }
220

    
221
public static void selfRegister() {
222
        String[][] iconNames = new String[][]{
223
            new String[]{"dalswing", "form-refresh-data"}
224
        };
225
        IconTheme theme = ToolsSwingLocator.getIconThemeManager().getCurrent();
226
        for (String[] icon : iconNames) {
227
            URL url = DefaultJFeaturesForm.class.getResource(icon[1] + ".png");
228
            theme.registerDefault("DALSwing", icon[0], icon[1], null, url);
229
        }
230
        
231
    }
232
    @Override
233
    public void setPreferredSize(Dimension dimension) {
234
//        panel.setPreferredSize(dimension);
235
    }
236

    
237
    private void updateForm() {
238
        if (this.formset == null) {
239
            this.panel.add(this.getFormset().asJComponent(), BorderLayout.CENTER);
240
        }
241
        try {
242
            if( this.currentQuery!=null ) {
243
                this.currentQuery.retrievesAllAttributes();
244
            }
245
            this.features = DALLocator.getDataManager().createFeaturePagingHelper(store, this.currentQuery, PAGE_SIZE);
246
            this.formset.setValues(features.asListOfDynObjects());
247
        } catch (Exception ex) {
248
            throw new RuntimeException("Can't update form", ex);
249
        }
250
        updateButtonEnabledStatus();
251
    }
252

    
253
    @Override
254
    public JComponent asJComponent() {
255
        if (this.features == null) {
256
            try {
257
                updateForm();
258
            } catch (Exception ex) {
259
                throw new RuntimeException(ex);
260
            }
261
        }
262
        return this.panel;
263
    }
264

    
265
    @Override
266
    public void bind(FeatureStore store) {
267
        if (store == null) {
268
            throw new IllegalArgumentException("bind need a store as parameter, not a null.");
269
        }
270
        try {
271
            DefaultDataSwingManager manager = (DefaultDataSwingManager) DALSwingLocator.getSwingManager();
272
            DynClass theDefinition = manager.featureType2DynClass(store, store.getDefaultFeatureType());
273
            this.bind(store, theDefinition);
274
        } catch (Exception ex) {
275
            throw new RuntimeException("Can't bind store '" + store.getName() + "' to form", ex);
276
        }
277
    }
278

    
279
    public void bind(FeatureStore store, DynClass definition) throws ServiceException, DataException {
280
        if (this.store == store) {
281
            return;
282
        }
283
        DynFormManager formManager = DynFormLocator.getDynFormManager();
284
        this.definition = formManager.getDefinition(definition);
285
        if (formset != null) {
286
            this.panel.remove(formset.asJComponent());
287
            this.formset = null;
288
        }
289
        this.store = store;
290
        DisposeUtils.bind(store);
291
        this.features = null;
292
    }
293

    
294
    @Override
295
    public void dispose() {
296
        DisposeUtils.disposeQuietly(store);
297
        this.store = null;
298
        this.panel = null;
299
        this.formset = null;
300
        this.features = null;
301
        this.definition = null;
302
        this.currentQuery = null;
303
        this.otherActions = null;
304
    }
305
    
306
    @Override
307
    public JDynFormSet getFormset() {
308
        if (this.formset == null) {
309
            DynFormManager formManager = DynFormLocator.getDynFormManager();
310
            this.formset = formManager.createJDynFormSet(
311
                    new DefaultFeaturesFormContext(),
312
                    this.definition,
313
                    null
314
            );
315
            List<String> groups = this.definition.getGroups();
316
            if( groups.size()==1 && groups.get(0)==null ) {
317
                this.formset.setLayoutMode(JDynForm.USE_PLAIN);
318
            } else {
319
                this.formset.setLayoutMode(JDynForm.USE_TABS);
320
            }
321
            this.formset.setAllowNew(true);
322
            this.formset.setAllowDelete(true);
323
            this.formset.setAllowUpdate(true);
324
            this.formset.setAllowClose(true);
325
            this.formset.setAllowSearch(true);
326
            this.formset.setAutosave(true);
327

    
328
            this.formset.addAction(new StartEditingAction());
329
            this.formset.addAction(new FinishEditingAction());
330
            this.formset.addAction(new RefreshAction());
331
            
332
            FormActionContext actionContext = new FormActionContext();
333
            Collection<DALActionFactory> factories = DALSwingLocator.getSwingManager().getStoreActions();
334
            for (DALActionFactory factory : factories) {
335
                if( StringUtils.equalsIgnoreCase(factory.getName(), ShowFormActionFactory.ACTION_NAME) ) {
336
                    continue;
337
                }
338
                Action action = factory.createAction(actionContext);
339
                this.formset.addAction(action);
340
            }            
341
            for( Action action : this.otherActions ) {
342
                this.formset.addAction(action);
343
            }
344

    
345
            this.formset.addListener(new FormSetListener());
346
        }
347
        updateButtonEnabledStatus();
348
        return this.formset;
349
    }
350

    
351
    @Override
352
    public void addAction(Action action) {
353
        this.otherActions.add(action);
354
        if( this.formset!=null ) {
355
            this.formset.addAction(action);
356
        }
357
    }
358

    
359
    @Override
360
    public long getCurrentIndex() {
361
        if( this.formset==null ) {
362
            return -1;
363
        }
364
        return this.formset.getCurrentIndex();
365
    }
366

    
367
    @Override
368
    public Feature get(long index) {
369
        if( this.formset==null || this.features==null ) {
370
            return null;
371
        }
372
        try {
373
            return this.features.getFeatureAt(index);
374
        } catch (BaseException ex) {
375
            return null;
376
        }
377
    }
378
    
379
    private class RefreshAction extends AbstractAction {
380

    
381
        @SuppressWarnings({"OverridableMethodCallInConstructor", "LeakingThisInConstructor"})
382
        public RefreshAction() {
383
            I18nManager i18nManager = ToolsLocator.getI18nManager();
384
            IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getDefault();
385

    
386
            this.putValue(NAME, null);
387
            this.putValue(SHORT_DESCRIPTION, i18nManager.getTranslation("_Refresh"));
388
            this.putValue(SMALL_ICON, iconTheme.get("form-refresh-data"));
389
            this.putValue(ACTION_COMMAND_KEY, REFRESHFORM_ACTION);
390
            this.setEnabled(!formset.isInNewState());
391
        }
392

    
393
        @Override
394
        public void actionPerformed(ActionEvent ae) {
395
            try {
396
                I18nManager i18n = ToolsLocator.getI18nManager();
397
                formset.message(i18n.getTranslation("_Form_refreshed"));
398
                updateForm();
399
            } catch (Exception ex) {
400
                LOGGER.warn("Can't refresh form", ex);
401
            }
402
        }
403
    }
404

    
405
       
406
    private class FinishEditingAction extends AbstractAction implements Observer {
407

    
408
        @SuppressWarnings({"OverridableMethodCallInConstructor", "LeakingThisInConstructor"})
409
        public FinishEditingAction() {
410
            I18nManager i18nManager = ToolsLocator.getI18nManager();
411
            IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getDefault();
412

    
413
            this.putValue(NAME,null);
414
            this.putValue(SHORT_DESCRIPTION,i18nManager.getTranslation("_Stop_editing"));
415
            this.putValue(SMALL_ICON, iconTheme.get("table-stop-editing"));
416
            this.putValue(ACTION_COMMAND_KEY, FINISHEDITING_ACTION);
417

    
418
            this.setEnabled(store.isEditing());
419
            store.addObserver(this);
420
        }
421

    
422
        @Override
423
        public void actionPerformed(ActionEvent ae) {
424
            if( store.isEditing() ) {
425
                try {
426
                    I18nManager i18nManager = ToolsLocator.getI18nManager();
427
                    ThreadSafeDialogsManager dialogManager = ToolsSwingLocator.getThreadSafeDialogsManager();
428
                    int x = dialogManager.confirmDialog(
429
                            i18nManager.getTranslation("_Do_you_want_to_finish_editing_and_save_the_changes")+"\n\n"+
430
                                    i18nManager.getTranslation("_Press_cancel_to_cancel_editing_and_changes"),
431
                            i18nManager.getTranslation("_Stop_editing"),
432
                            JOptionPane.YES_NO_CANCEL_OPTION,
433
                            JOptionPane.QUESTION_MESSAGE
434
                    );
435
                    switch(x) {
436
                        case JOptionPane.YES_OPTION:
437
                            store.finishEditing();
438
                            break;
439
                        case JOptionPane.NO_OPTION:
440
                            break;
441
                        case JOptionPane.CANCEL_OPTION:
442
                            store.cancelEditing();
443
                            break;
444
                    }
445
                } catch (DataException ex) {
446
                    LOGGER.warn("Can't finish editing in FeatureForm ("+store.getName()+").",ex);
447
                }
448
            }
449
            updateButtonEnabledStatus();
450
        }
451
    
452
        @Override
453
        public void update(Observable observable, Object notification) {
454
            if( store == null || formset==null ) {
455
                return;
456
            }
457
            if( notification instanceof FeatureStoreNotification ) {
458
                FeatureStoreNotification n =  (FeatureStoreNotification) notification;
459
                switch( n.getType() )  {
460
                    case FeatureStoreNotification.AFTER_STARTEDITING:
461
                    case FeatureStoreNotification.AFTER_FINISHEDITING:
462
                    case FeatureStoreNotification.AFTER_CANCELEDITING:
463
                        updateButtonEnabledStatus();
464
                        break;
465
                }
466
            }
467
        }
468

    
469
    }
470
    
471
    private class StartEditingAction extends AbstractAction implements Observer {
472

    
473
        @SuppressWarnings({"OverridableMethodCallInConstructor", "LeakingThisInConstructor"})
474
        public StartEditingAction() {
475
            I18nManager i18nManager = ToolsLocator.getI18nManager();
476
            IconTheme iconTheme = ToolsSwingLocator.getIconThemeManager().getDefault();
477

    
478
            this.putValue(NAME,null);
479
            this.putValue(SHORT_DESCRIPTION,i18nManager.getTranslation("_Start_editing"));
480
            this.putValue(SMALL_ICON, iconTheme.get("table-start-editing"));
481
            this.putValue(ACTION_COMMAND_KEY, STARTEDITING_ACTION);
482

    
483
            this.setEnabled(!store.isEditing());
484
            store.addObserver(this);
485
        }
486

    
487
        @Override
488
        public void actionPerformed(ActionEvent ae) {
489
            if( !store.isEditing() ) {
490
                try {
491
                    store.edit();
492
                } catch (DataException ex) {
493
                    LOGGER.warn("Can't finish editing in FeatureForm ("+store.getName()+").",ex);
494
                }
495
            }
496
            updateButtonEnabledStatus();
497
        }
498

    
499
        @Override
500
        public void update(Observable observable, Object notification) {
501
            if( store == null || formset==null ) {
502
                return;
503
            }
504
            if( notification instanceof FeatureStoreNotification ) {
505
                FeatureStoreNotification n =  (FeatureStoreNotification) notification;
506
                switch( n.getType() )  {
507
                    case FeatureStoreNotification.AFTER_STARTEDITING:
508
                    case FeatureStoreNotification.AFTER_FINISHEDITING:
509
                    case FeatureStoreNotification.AFTER_CANCELEDITING:
510
                        updateButtonEnabledStatus();
511
                        break;
512
                }
513
            }
514
        }
515

    
516
    }
517

    
518
    @Override
519
    public void setQuery(FeatureQuery query) {
520
        if (this.features != null) {
521
            if (this.formset != null && !formset.isReadOnly() && this.formset.isAutosave() && this.formset.countValues() > 0) {
522
                if (!store.isEditing()) {
523
                    try {
524
                        store.edit();
525
                    } catch (DataException e1) {
526
                        throw new RuntimeException("Can't set query", e1);
527
                    }
528
                }
529
                saveChanges(this.formset);
530
            }
531
        }
532
        this.currentQuery = query;
533
        updateForm();
534
    }
535

    
536
    private FeatureQuery getCurrentQuery() {
537
        return this.currentQuery;
538
    }
539
    
540
    @Override
541
    public void showForm(MODE mode) {
542
        this.panel.add(this.getFormset().asJComponent(), BorderLayout.CENTER);
543
        WindowManager winmgr = ToolsSwingLocator.getWindowManager();
544
        String title = this.definition.getLabel();
545
        winmgr.showWindow(this.asJComponent(), title, mode);
546
    }
547

    
548
    private void saveChanges(JDynFormSet theFormSet) {
549
        I18nManager i18n = ToolsLocator.getI18nManager();
550
        try {
551
            if( theFormSet.isInNewState() ) {
552
                Feature newFeature = store.createNewFeature(false);
553
                DynObject newElement = newFeature.getAsDynObject();
554
                theFormSet.getFormValues(newElement);
555
                features.insert(((FacadeOfAFeature)newElement).getEditableFeature());
556
                this.formset.message(i18n.getTranslation("_Record_saved"));
557
                try {
558
                    this.formset.setValues(features.asListOfDynObjects());
559
                    this.formset.setCurrentIndex((int)(features.getTotalSize())-1);
560
                } catch(Exception ex) {
561
                    LOGGER.warn("Can't reload form data after insert.",ex);
562
                }
563
            } else {
564
                int index = theFormSet.getCurrentIndex();
565
                DynObject currentElement = theFormSet.get(index);
566
                theFormSet.getFormValues(currentElement);
567
                features.update(((FacadeOfAFeature)currentElement).getEditableFeature());
568
                this.formset.message(i18n.getTranslation("_Record_saved"));
569
            }
570
        } catch(Exception ex) {
571
            theFormSet.message(i18n.getTranslation("error_saving_data_will_not_save"));
572
            throw new RuntimeException("Can't save values",ex);
573
            
574
        } finally {
575
            updateButtonEnabledStatus();
576
        }
577

    
578
    }
579
    private void deleteCurrentElement(JDynFormSet theFormSet) {
580
        I18nManager i18n = ToolsLocator.getI18nManager();
581
        try {
582
            int index = theFormSet.getCurrentIndex();
583
            DynObject currentElement = theFormSet.get(index);
584
            theFormSet.getFormValues(currentElement);
585
            Feature feature = ((FacadeOfAFeature) currentElement).getFeature();
586
            if (feature instanceof EditableFeature) {
587
                feature = ((EditableFeature) feature).getNotEditableCopy();
588
            }
589
            features.delete(feature);
590
            
591
            this.formset.message(i18n.getTranslation("_Record_removed"));
592
            
593
            this.formset.setValues(features.asListOfDynObjects());
594
            if (features.getTotalSize()-1<index) {
595
                index = index-1;
596
            }
597
            this.formset.setCurrentIndex(index);
598

    
599
        } catch (Exception ex) {
600
            theFormSet.message(i18n.getTranslation("error_removing_data_will_not_remove"));
601
            throw new RuntimeException("Can't remove values", ex);
602

    
603
        } finally {
604
            updateButtonEnabledStatus();
605
        }
606

    
607
    }
608
    @Override
609
    public void saveChanges() {
610
        if (this.formset != null && this.formset.countValues() > 0) {
611
            if (store != null && !store.isEditing()) {
612
                try {
613
                    store.edit();
614
                } catch (DataException e1) {
615
                    LOGGER.warn("Can't edit the store " + store.getName());
616
                    throw new RuntimeException("Can't save changes.", e1);
617
                }
618
            }
619
            this.saveChanges(this.formset);
620
        }
621
    }
622

    
623
    private void updateButtonEnabledStatus() {
624
        if( this.formset == null ) {
625
            return;
626
        }
627
        if( this.store == null || store.isBroken() || store.isAppending() ) {
628
            this.formset.setReadOnly(true);
629
            formset.setActionVisible(STARTEDITING_ACTION, true);
630
            formset.setActionEnabled(STARTEDITING_ACTION, true);
631
            formset.setActionVisible(FINISHEDITING_ACTION, false);
632
            formset.setActionEnabled(FINISHEDITING_ACTION, false);
633
            formset.setActionEnabled(ACTION_DELETE, false);
634
            formset.setActionEnabled(ACTION_NEW,false);
635
            formset.setActionEnabled(ACTION_CANCEL_NEW,false);
636
            formset.setActionEnabled(ACTION_SAVE,false);
637
            formset.setActionEnabled(ACTION_SEARCH,false);
638
            formset.setActionEnabled(REFRESHFORM_ACTION, true);
639
            return;
640
        }
641
        if( store.isEditing() ) {
642
            this.formset.setReadOnly(false);
643
            formset.setActionVisible(STARTEDITING_ACTION, false);
644
            formset.setActionEnabled(STARTEDITING_ACTION, false);
645
            formset.setActionVisible(FINISHEDITING_ACTION, true);
646
            formset.setActionEnabled(FINISHEDITING_ACTION, true);
647
            if( formset.isInNewState() ) {
648
                formset.setActionEnabled(ACTION_DELETE, false);
649
                formset.setActionEnabled(ACTION_SEARCH,false);
650
                formset.setActionEnabled(ACTION_NEW,false);
651
                formset.setActionEnabled(ACTION_CANCEL_NEW,true);
652
                formset.setActionEnabled(ACTION_SAVE,true);
653
                formset.setActionEnabled(REFRESHFORM_ACTION, false);
654
                
655
            } else if( this.features!=null && this.features.isEmpty() ) {
656
                formset.setActionEnabled(ACTION_DELETE, false);
657
                formset.setActionEnabled(ACTION_SEARCH,false);
658
                formset.setActionEnabled(ACTION_NEW,true);
659
                formset.setActionEnabled(ACTION_CANCEL_NEW,true);
660
                formset.setActionEnabled(ACTION_SAVE,false);
661
                formset.setActionEnabled(REFRESHFORM_ACTION, true);
662

    
663
            } else if( formset.getForm().isModified() ) {
664
                formset.setActionEnabled(ACTION_DELETE, true);
665
                formset.setActionEnabled(ACTION_SEARCH,true);
666
                formset.setActionEnabled(ACTION_NEW,true);
667
                formset.setActionEnabled(ACTION_CANCEL_NEW,false);
668
                formset.setActionEnabled(ACTION_SAVE,true);
669
                formset.setActionEnabled(REFRESHFORM_ACTION, true);
670

    
671
            } else {
672
                formset.setActionEnabled(ACTION_DELETE, true);
673
                formset.setActionEnabled(ACTION_SEARCH,true);
674
                formset.setActionEnabled(ACTION_NEW,true);
675
                formset.setActionEnabled(ACTION_CANCEL_NEW,false);
676
                formset.setActionEnabled(ACTION_SAVE,true); //false);
677
                formset.setActionEnabled(REFRESHFORM_ACTION, true);
678
            }
679

    
680
            return;
681
        }
682
        this.formset.setReadOnly(true);
683
        formset.setActionVisible(STARTEDITING_ACTION, true);
684
        formset.setActionEnabled(STARTEDITING_ACTION, true);
685
        formset.setActionVisible(FINISHEDITING_ACTION, false);
686
        formset.setActionEnabled(FINISHEDITING_ACTION, false);
687
        formset.setActionEnabled(ACTION_DELETE, false);
688
        formset.setActionEnabled(ACTION_NEW,false);
689
        formset.setActionEnabled(ACTION_CANCEL_NEW,false);
690
        formset.setActionEnabled(ACTION_SAVE,false);
691
        formset.setActionEnabled(ACTION_SEARCH,true);
692
        formset.setActionEnabled(REFRESHFORM_ACTION,true);
693
    }
694
        
695
    @Override
696
    public long getDataSetSize() {
697
        if (this.features != null) {
698
            return features.getTotalSize();
699
        }
700
        return 0;
701
    }
702

    
703
    @Override
704
    public FeatureStore getFeatureStore() {
705
        return this.store;
706
    }
707

    
708
    private class FormSetListener implements JDynFormSetListener {
709

    
710
        @Override
711
        public void formMessage(String message) {
712
        }
713

    
714
        @Override
715
        public void formClose() {
716
            panel.setVisible(false);
717
        }
718

    
719
        @Override
720
        public void formMovedTo(int currentPosition) throws AbortActionException {
721
            LOGGER.trace("formMovedTo " + currentPosition);
722
            updateButtonEnabledStatus();
723
        }
724

    
725
        @Override
726
        public void formBeforeSave(JDynFormSet dynformSet) throws AbortActionException {
727
            LOGGER.trace("formBeforeSave");
728
            updateButtonEnabledStatus();
729
        }
730

    
731
        @Override
732
        public void formBeforeNew(JDynFormSet dynformSet) throws AbortActionException {
733
            LOGGER.trace("formBeforeNew");
734
            updateButtonEnabledStatus();
735
        }
736

    
737
        @Override
738
        public void formBeforeDelete(JDynFormSet dynformSet) throws AbortActionException {
739
            LOGGER.trace("formBeforeDelete");
740
            updateButtonEnabledStatus();
741
        }
742

    
743
        @Override
744
        public void formAfterSave(JDynFormSet dynformSet) throws AbortActionException {
745
            LOGGER.trace("formAfterSave");
746
            saveChanges(dynformSet);
747
            updateButtonEnabledStatus();
748
        }
749

    
750
        @Override
751
        public void formAfterNew(JDynFormSet dynformSet) throws AbortActionException {
752
            LOGGER.trace("formAfterNew");
753
            updateButtonEnabledStatus();
754
        }
755

    
756
        @Override
757
        public void formAfterDelete(JDynFormSet dynformSet) throws AbortActionException {
758
            LOGGER.trace("formAfterDelete");
759
            deleteCurrentElement(dynformSet);
760
            updateButtonEnabledStatus();
761
        }
762

    
763
//        @Override
764
//        public void formBeforeSearch(JDynFormSet dynformSet) throws AbortActionException {
765
//            LOGGER.trace("formBeforeSearch");
766
//            DataSwingManager dataSwingmanager = DALSwingLocator.getSwingManager();
767
//            WindowManager_v2 winmgr = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
768
//
769
//            JExpressionBuilder builder = dataSwingmanager.createQueryFilterExpresion(store);
770
//            FeatureQuery currentQuery = getCurrentQuery();
771
//            if( currentQuery!=null ) {
772
//                Evaluator filter = currentQuery.getFilter();
773
//                if( filter instanceof ExpressionEvaluator ) {
774
//                    Expression expression = ((ExpressionEvaluator)filter).getExpression();
775
//                    builder.setExpression(expression);
776
//                }
777
//            }
778
//            Dialog dialog = winmgr.createDialog(
779
//                    builder.asJComponent(),
780
//                    "Filtro",
781
//                    "Creacion de filtro sobre '"+store.getName()+"'",
782
//                    WindowManager_v2.BUTTONS_OK_CANCEL
783
//            );
784
//            dialog.show(WindowManager.MODE.DIALOG);
785
//            if( dialog.getAction() == WindowManager_v2.BUTTON_OK ) {
786
//                Expression expresion = builder.getExpression();
787
//                try {
788
//                    FeatureQuery query = store.createFeatureQuery();
789
//                    if( ExpressionUtils.isPhraseEmpty(expresion) ) {
790
//                        query.clearFilter();
791
//                    } else {
792
//                        query.setFilter(expresion);
793
//                    }
794
//                    setQuery(query);
795
//                } catch (Exception ex) {
796
//                    LOGGER.warn("Can't apply filter '" + expresion + "'.", ex);
797
//                }
798
//            }
799
//        }
800

    
801
        @Override
802
        public void formBeforeSearch(JDynFormSet dynformSet) throws AbortActionException {
803
            LOGGER.trace("formBeforeSearch");
804
            DataSwingManager dataSwingmanager = DALSwingLocator.getSwingManager();
805
            WindowManager_v2 winmgr = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
806

    
807
            final FeatureStoreSearchPanel searchPanel = dataSwingmanager.createFeatureStoreSearchPanel(store);
808
            searchPanel.setShowActions(false);
809
            FeatureQuery currentQuery = getCurrentQuery();
810
            if( currentQuery!=null ) {
811
                Evaluator filter = currentQuery.getFilter();
812
                if( filter instanceof ExpressionEvaluator ) {
813
                    Expression expression = ((ExpressionEvaluator)filter).toExpression();
814
                    searchPanel.setFilter(expression);
815
                    searchPanel.search();
816
                }
817
            }
818
            searchPanel.asJComponent().setPreferredSize(
819
                    new Dimension(FeatureStoreSearchPanel.DEFAULT_WIDTH, 320)
820
            );
821
            I18nManager i18n = ToolsLocator.getI18nManager();
822
            Dialog dialog = winmgr.createDialog(
823
                    searchPanel.asJComponent(),
824
                    i18n.getTranslation("_Filter"),
825
                    i18n.getTranslation("_Creating_filter_for") + ": '"+store.getName()+"'",
826
                    WindowManager_v2.BUTTONS_OK_CANCEL
827
            );
828
            dialog.show(WindowManager.MODE.DIALOG);
829
            if( dialog.getAction() == WindowManager_v2.BUTTON_OK ) {
830
                SearchParameters params = searchPanel.fetch(null);
831
                if (params.getQuery()!=null) {
832
                FeatureQuery searchQuery = params.getQuery().getCopy();
833
               
834
                Expression expresion = null;
835
                if( searchQuery!=null ) {
836
                  expresion = searchQuery.getExpressionFilter();
837
                }
838
                try {
839
                    FeatureQuery query = store.createFeatureQuery();
840
                    if( ExpressionUtils.isPhraseEmpty(expresion) ) {
841
                        query.clearFilter();
842
                    } else {
843
                        query.setFilter(expresion);
844
                    }
845
                    setQuery(query);
846
                } catch (Exception ex) {
847
                    LOGGER.warn("Can't apply filter '" + expresion + "'.", ex);
848
                }
849
                } else {
850
                    LOGGER.warn("FeatureQuery from parameters is null. Query is not applied to the JFeaturesFrom");
851
                }
852
            }
853
        }
854

    
855
        @Override
856
        public void formAfterSearch(JDynFormSet dynformSet) throws AbortActionException {
857
            LOGGER.trace("formAfterSearch");
858
        }
859

    
860
        @Override
861
        public void formBeforeCancelNew(JDynFormSet dynformSet) throws AbortActionException {
862
            LOGGER.trace("formBeforeCancelNew");
863
            updateButtonEnabledStatus();
864
        }
865

    
866
        @Override
867
        public void formAfterCancelNew(JDynFormSet dynformSet) throws AbortActionException {
868
            LOGGER.trace("formAfterCancelNew");
869
            updateButtonEnabledStatus();
870
        }
871
    }
872

    
873
//    private static class StoreEditException extends AbortActionException {
874
//
875
//        /**
876
//         *
877
//         */
878
//        private static final long serialVersionUID = -7682017811778577130L;
879
//
880
//        public StoreEditException(Throwable cause, String storename) {
881
//            super("Can't edit the store '%(storename)'", cause, "cant_edit_the store_XstorenameX", serialVersionUID);
882
//            setValue("storename", storename);
883
//        }
884
//    }
885
}