Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.app / org.gvsig.app.mainplugin / src / main / java / org / gvsig / app / project / ProjectManager.java @ 45931

History | View | Annotate | Download (11.8 KB)

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

    
26
import java.text.MessageFormat;
27
import java.util.ArrayList;
28
import java.util.Collections;
29
import java.util.Comparator;
30
import java.util.EventListener;
31
import java.util.HashMap;
32
import java.util.Iterator;
33
import java.util.List;
34
import java.util.Map;
35

    
36
import org.slf4j.Logger;
37
import org.slf4j.LoggerFactory;
38

    
39
import org.gvsig.andami.PluginServices;
40
import org.gvsig.app.extension.ProjectExtension;
41
import org.gvsig.app.project.documents.DefaultDocumentActionGroup;
42
import org.gvsig.app.project.documents.Document;
43
import org.gvsig.app.project.documents.DocumentAction;
44
import org.gvsig.app.project.documents.DocumentActionGroup;
45
import org.gvsig.app.project.documents.DocumentManager;
46
import org.gvsig.app.project.documents.gui.ProjectWindow;
47
import org.gvsig.tools.ToolsLocator;
48
import org.gvsig.tools.extensionpoint.ExtensionPoint;
49
import org.gvsig.tools.extensionpoint.ExtensionPoint.Extension;
50
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
51
import org.gvsig.tools.observer.impl.BaseWeakReferencingObservable;
52
import org.gvsig.tools.util.BaseListenerSupport;
53
import org.gvsig.tools.util.BaseListenerSupport.NotificationListener;
54
import org.gvsig.tools.util.Invocable;
55

    
56
public class ProjectManager extends BaseWeakReferencingObservable {
57

    
58
    private static final Logger logger = LoggerFactory
59
        .getLogger(ProjectManager.class);
60
    private static ProjectManager factory = null;
61

    
62
    // private static final String KEY_PROJECT = "app.project";
63
    // private static final String KEY_DOCUMENTS = "app.project.documents";
64
    private static final String KEY_DOCUMENTS_FACTORIES =
65
        "app.project.documents.factories";
66
    private static final String KEY_DOCUMENTS_ACTIONS =
67
        "app.project.documents.actions";
68

    
69
    private Map<String, DocumentActionGroup> documentActionGroups;
70

    
71
    private final BaseListenerSupport newProjectListeners;
72
            
73
    public interface ProjectEvent extends EventListener {
74
        public Project getProject();
75
    }
76

    
77
    public interface NewProjectEvent extends ProjectEvent {
78
        
79
    }
80
    
81
    public static ProjectManager getInstance() {
82
        if (factory == null) {
83
            factory = new ProjectManager();
84
        }
85
        return factory;
86
    }
87

    
88
    private ProjectManager() {
89
        this.documentActionGroups = new HashMap<String, DocumentActionGroup>();
90
        this.newProjectListeners = new BaseListenerSupport();
91
    }
92

    
93
    
94
    public Project getCurrentProject() {
95
        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
96
        if( ext==null ) {
97
            return null;
98
        }
99
        return ext.getProject();
100
    }
101
    
102
    public void setCurrentProject(Project project) {
103
        ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).setProject(project);
104
    }
105

    
106
    public ProjectWindow getCurrentProjectWindow() {
107
        ProjectExtension projectExtension =
108
            (ProjectExtension) PluginServices
109
                .getExtension(ProjectExtension.class);
110
        ProjectWindow window =
111
            (ProjectWindow) projectExtension.getProjectWindow();
112
        return window;
113
    }
114

    
115
    /**
116
     * @deprecated use {@link #getDocumentManagers()} instead.
117
     */
118
    public List<DocumentManager> getDocumentManager() {
119
        return getDocumentManagers();
120
    }
121

    
122
    @SuppressWarnings("unchecked")
123
    public List<DocumentManager> getDocumentManagers() {
124
        Iterator<Extension> iterator =
125
            ToolsLocator.getExtensionPointManager()
126
                .get(KEY_DOCUMENTS_FACTORIES).iterator();
127
        List<DocumentManager> factories = new ArrayList<DocumentManager>();
128
        while (iterator.hasNext()) {
129
            Extension extension = iterator.next();
130
            try {
131
                factories.add((DocumentManager) extension.create());
132
            } catch (InstantiationException e) {
133
                logger.error("Can't access to project document factory ("
134
                    + extension.getName() + ").");
135
            } catch (IllegalAccessException e) {
136
                logger.error("Can't access to project document factory ("
137
                    + extension.getName() + ").");
138
            }
139
        }
140
        return factories;
141
    }
142

    
143
    /**
144
     * @deprecated use {@link #getDocumentManager(String)} instead.
145
     */
146
    public DocumentManager getDocumentManagers(String type) {
147
        return getDocumentManager(type);
148
    }
149

    
150
    public DocumentManager getDocumentManager(String type) {
151
        DocumentManager factory = null;
152
        try {
153
            factory =
154
                (DocumentManager) ToolsLocator.getExtensionPointManager()
155
                    .get(KEY_DOCUMENTS_FACTORIES).create(type);
156
        } catch (Exception ex) {
157
            logger
158
                .warn(
159
                    MessageFormat.format(
160
                        "Unable to locate factory for documents of type {0}",
161
                        type), ex);
162
        }
163
        return factory;
164
    }
165

    
166
    public Document createDocument(String type) {
167
        Document doc = getDocumentManager(type).createDocument();
168
        return doc;
169
    }
170

    
171
    public Document createDocument(String type, String name) {
172
        Document doc = createDocument(type);
173
        doc.setName(name);
174
        return doc;
175
    }
176

    
177
    /**
178
     * @deprecated use {@link #createDocumentsByUser(String)} instead
179
     */
180
    public Document createDocumentByUser(String type) {
181
        Document doc = getDocumentManager(type).createDocumentByUser();
182
        return doc;
183
    }
184

    
185
    /**
186
     * Creates a group of documents of a given type through the user interface.
187
     * 
188
     * @param type
189
     *            the type of documents to create
190
     * @return the created documents
191
     */
192
    public Iterator<? extends Document> createDocumentsByUser(String type) {
193
        logger.info("createDocumentsByUser('{}')", type);
194
        return getDocumentManager(type).createDocumentsByUser();
195
    }
196

    
197
    public Iterator<? extends Document> createDocumentsByUser(String type, Invocable whenDocumentsLoadeds) {
198
        logger.info("createDocumentsByUser('{}')", type);
199
        return getDocumentManager(type).createDocumentsByUser(whenDocumentsLoadeds);
200
    }
201

    
202
    public Project createProject() {
203
        return new DefaultProject();
204
    }
205

    
206
    public ProjectExtent createExtent() {
207
        return new ProjectExtent();
208
    }
209

    
210
    public void registerDocumentFactory(DocumentManager documentManager) {
211
        ExtensionPointManager manager = ToolsLocator.getExtensionPointManager();
212
        manager.add(KEY_DOCUMENTS_FACTORIES).append(
213
            documentManager.getTypeName(), null, documentManager);
214
        notifyObservers();
215
    }
216

    
217
    public void registerDocumentFactoryAlias(String typeName, String alias) {
218
        ExtensionPointManager manager = ToolsLocator.getExtensionPointManager();
219

    
220
        manager.get(KEY_DOCUMENTS_FACTORIES).addAlias(typeName, alias);
221
    }
222

    
223
    public void registerDocumentAction(String typeName, DocumentAction action) {
224
        ExtensionPointManager manager = ToolsLocator.getExtensionPointManager();
225

    
226
        String key = KEY_DOCUMENTS_ACTIONS + "." + typeName;
227
        String description =
228
            MessageFormat.format("Actions for {1} documents ", typeName);
229

    
230
        manager.add(key, description).append(action.getId(),
231
            action.getDescription(), action);
232
    }
233

    
234
    /**
235
     * Gets a list of actions for the document type especified.
236
     * 
237
     * La lista esta ordenada deacuerdo al orden especificado en
238
     * las acciones y grupos de acciones involucrados.
239
     * 
240
     * @param doctype
241
     * @return list of actions as List<DocumentAction>
242
     */
243
    @SuppressWarnings("unchecked")
244
    public List<DocumentAction> getDocumentActions(String doctype) {
245

    
246
        ExtensionPointManager manager = ToolsLocator.getExtensionPointManager();
247

    
248
        String key = KEY_DOCUMENTS_ACTIONS + "." + doctype;
249
        ExtensionPoint extensionPoint = manager.get(key);
250
        if (extensionPoint == null) {
251
            // No hay acciones registradas para ese tipo de documento
252
            return null;
253
        }
254
        List<DocumentAction> actions = new ArrayList<DocumentAction>();
255
        Iterator<Extension> it = extensionPoint.iterator();
256
        while (it.hasNext()) {
257
            try {
258
                DocumentAction action;
259
                action = (DocumentAction) it.next().create();
260
                actions.add(action);
261
            } catch (InstantiationException e) {
262
                logger.warn("Can't retrieve document action", e);
263
            } catch (IllegalAccessException e) {
264
                logger.warn("Can't retrieve document action", e);
265
            }
266
        }
267
        if (actions.size() < 1) {
268
            return null;
269
        }
270
        Collections.sort(actions, new CompareAction());
271
        return actions;
272
    }
273

    
274
    private class CompareAction implements Comparator<DocumentAction> {
275

    
276
        public int compare(DocumentAction action1, DocumentAction action2) {
277
            // FIXME: flata formatear los enteros!!!!
278
            String key1 =
279
                MessageFormat.format("{1}.{2}.{3}", action1.getGroup()
280
                    .getOrder(), action1.getGroup().getTitle(), action1
281
                    .getOrder());
282
            String key2 =
283
                MessageFormat.format("{1}.{2}.{3}", action2.getGroup()
284
                    .getOrder(), action2.getGroup().getTitle(), action2
285
                    .getOrder());
286
            return key1.compareTo(key2);
287
        }
288
    }
289

    
290
    /**
291
     * Create, add and return a new action for documents.
292
     * 
293
     * If action already exists don't create and return this.
294
     * 
295
     * @param unique
296
     *            identifier for the action
297
     * @param title
298
     * @param description
299
     * @param order
300
     * @return
301
     */
302
    public DocumentActionGroup addDocumentActionGroup(String id, String title,
303
        String description, int order) {
304
        DocumentActionGroup group = this.documentActionGroups.get(id);
305
        if (group != null) {
306
            return group;
307
        }
308
        group = new DefaultDocumentActionGroup(id, title, description, order);
309
        this.documentActionGroups.put(id, group);
310
        return group;
311
    }
312

    
313
    public ProjectPreferences getProjectPreferences() {
314
        return DefaultProject.getPreferences();
315
    }
316

    
317
    public void addProjectListener(NotificationListener listener) {
318
        this.newProjectListeners.addListener(listener);
319
    }
320

    
321
    public NotificationListener[] getProjectListeners() {
322
        return (NotificationListener[]) this.newProjectListeners.getListeners();
323
    }
324

    
325
    public boolean hasProjectListeners() {
326
        return this.newProjectListeners.hasListeners();
327
    }
328
    
329
    public void removeProjectListener(NotificationListener listener) {
330
        this.newProjectListeners.removeListener(listener);
331
    }
332

    
333
    public void removeAllProjectListener() {    
334
        this.newProjectListeners.removeAllListener();
335
    }
336
    
337
    public void notifyProjectEvent(ProjectEvent event) {
338
        this.newProjectListeners.notifyEvent(event);
339
    }
340
}