aboutsummaryrefslogtreecommitdiff
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeProxy.java
blob: 19d5e16b0742d6b898ffffad2396a8c5292af405 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Eclipse Public License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.eclipse.org/org/documents/epl-v10.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.ide.eclipse.adt.internal.editors.layout.gre;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.ide.common.api.IAttributeInfo;
import com.android.ide.common.api.INode;
import com.android.ide.common.api.INodeHandler;
import com.android.ide.common.api.Margins;
import com.android.ide.common.api.Rect;
import com.android.ide.common.resources.platform.AttributeInfo;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SimpleAttribute;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtUtils;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ViewHierarchy;
import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
import com.android.ide.eclipse.adt.internal.project.SupportLibraryHelper;

import org.eclipse.core.resources.IProject;
import org.eclipse.swt.graphics.Rectangle;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class NodeProxy implements INode {
    private static final Margins NO_MARGINS = new Margins(0, 0, 0, 0);
    private final UiViewElementNode mNode;
    private final Rect mBounds;
    private final NodeFactory mFactory;
    /** Map from URI to Map(key=>value) (where no namespace uses "" as a key) */
    private Map<String, Map<String, String>> mPendingAttributes;

    /**
     * Creates a new {@link INode} that wraps an {@link UiViewElementNode} that is
     * actually valid in the current UI/XML model. The view may not be part of the canvas
     * yet (e.g. if it has just been dynamically added and the canvas hasn't reloaded yet.)
     * <p/>
     * This method is package protected. To create a node, please use {@link NodeFactory} instead.
     *
     * @param uiNode The node to wrap.
     * @param bounds The bounds of a the view in the canvas. Must be either: <br/>
     *   - a valid rect for a view that is actually in the canvas <br/>
     *   - <b>*or*</b> null (or an invalid rect) for a view that has just been added dynamically
     *   to the model. We never store a null bounds rectangle in the node, a null rectangle
     *   will be converted to an invalid rectangle.
     * @param factory A {@link NodeFactory} to create unique children nodes.
     */
    /*package*/ NodeProxy(UiViewElementNode uiNode, Rectangle bounds, NodeFactory factory) {
        mNode = uiNode;
        mFactory = factory;
        if (bounds == null) {
            mBounds = new Rect();
        } else {
            mBounds = SwtUtils.toRect(bounds);
        }
    }

    @Override
    public @NonNull Rect getBounds() {
        return mBounds;
    }

    @Override
    public @NonNull Margins getMargins() {
        ViewHierarchy viewHierarchy = mFactory.getCanvas().getViewHierarchy();
        CanvasViewInfo view = viewHierarchy.findViewInfoFor(this);
        if (view != null) {
            Margins margins = view.getMargins();
            if (margins != null) {
                return margins;
            }
        }

        return NO_MARGINS;
    }


    @Override
    public int getBaseline() {
        ViewHierarchy viewHierarchy = mFactory.getCanvas().getViewHierarchy();
        CanvasViewInfo view = viewHierarchy.findViewInfoFor(this);
        if (view != null) {
            return view.getBaseline();
        }

        return -1;
    }

    /**
     * Updates the bounds of this node proxy. Bounds cannot be null, but it can be invalid.
     * This is a package-protected method, only the {@link NodeFactory} uses this method.
     */
    /*package*/ void setBounds(Rectangle bounds) {
        SwtUtils.set(mBounds, bounds);
    }

    /**
     * Returns the {@link UiViewElementNode} corresponding to this
     * {@link NodeProxy}.
     *
     * @return The {@link UiViewElementNode} corresponding to this
     *         {@link NodeProxy}
     */
    public UiViewElementNode getNode() {
        return mNode;
    }

    @Override
    public @NonNull String getFqcn() {
        if (mNode != null) {
            ElementDescriptor desc = mNode.getDescriptor();
            if (desc instanceof ViewElementDescriptor) {
                return ((ViewElementDescriptor) desc).getFullClassName();
            }
        }

        return "";
    }


    // ---- Hierarchy handling ----


    @Override
    public INode getRoot() {
        if (mNode != null) {
            UiElementNode p = mNode.getUiRoot();
            // The node root should be a document. Instead what we really mean to
            // return is the top level view element.
            if (p instanceof UiDocumentNode) {
                List<UiElementNode> children = p.getUiChildren();
                if (children.size() > 0) {
                    p = children.get(0);
                }
            }

            // Cope with a badly structured XML layout
            while (p != null && !(p instanceof UiViewElementNode)) {
                p = p.getUiNextSibling();
            }

            if (p == mNode) {
                return this;
            }
            if (p instanceof UiViewElementNode) {
                return mFactory.create((UiViewElementNode) p);
            }
        }

        return null;
    }

    @Override
    public INode getParent() {
        if (mNode != null) {
            UiElementNode p = mNode.getUiParent();
            if (p instanceof UiViewElementNode) {
                return mFactory.create((UiViewElementNode) p);
            }
        }

        return null;
    }

    @Override
    public @NonNull INode[] getChildren() {
        if (mNode != null) {
            List<UiElementNode> uiChildren = mNode.getUiChildren();
            List<INode> nodes = new ArrayList<INode>(uiChildren.size());
            for (UiElementNode uiChild : uiChildren) {
                if (uiChild instanceof UiViewElementNode) {
                    nodes.add(mFactory.create((UiViewElementNode) uiChild));
                }
            }

            return nodes.toArray(new INode[nodes.size()]);
        }

        return new INode[0];
    }


    // ---- XML Editing ---

    @Override
    public void editXml(@NonNull String undoName, final @NonNull INodeHandler c) {
        final AndroidXmlEditor editor = mNode.getEditor();

        if (editor != null) {
            // Create an undo edit XML wrapper, which takes a runnable
            editor.wrapUndoEditXmlModel(
                    undoName,
                    new Runnable() {
                        @Override
                        public void run() {
                            // Here editor.isEditXmlModelPending returns true and it
                            // is safe to edit the model using any method from INode.

                            // Finally execute the closure that will act on the XML
                            c.handle(NodeProxy.this);
                            applyPendingChanges();
                        }
                    });
        }
    }

    private void checkEditOK() {
        final AndroidXmlEditor editor = mNode.getEditor();
        if (!editor.isEditXmlModelPending()) {
            throw new RuntimeException("Error: XML edit call without using INode.editXml!");
        }
    }

    @Override
    public @NonNull INode appendChild(@NonNull String viewFqcn) {
        return insertOrAppend(viewFqcn, -1);
    }

    @Override
    public @NonNull INode insertChildAt(@NonNull String viewFqcn, int index) {
        return insertOrAppend(viewFqcn, index);
    }

    @Override
    public void removeChild(@NonNull INode node) {
        checkEditOK();

        ((NodeProxy) node).mNode.deleteXmlNode();
    }

    private INode insertOrAppend(String viewFqcn, int index) {
        checkEditOK();

        AndroidXmlEditor editor = mNode.getEditor();
        if (editor != null) {
            // Possibly replace the tag with a compatibility version if the
            // minimum SDK requires it
            IProject project = editor.getProject();
            if (project != null) {
                viewFqcn = SupportLibraryHelper.getTagFor(project, viewFqcn);
            }
        }

        // Find the descriptor for this FQCN
        ViewElementDescriptor vd = getFqcnViewDescriptor(viewFqcn);
        if (vd == null) {
            warnPrintf("Can't create a new %s element", viewFqcn);
            return null;
        }

        final UiElementNode uiNew;
        if (index == -1) {
            // Append at the end.
            uiNew = mNode.appendNewUiChild(vd);
        } else {
            // Insert at the requested position or at the end.
            int n = mNode.getUiChildren().size();
            if (index < 0 || index >= n) {
                uiNew = mNode.appendNewUiChild(vd);
            } else {
                uiNew = mNode.insertNewUiChild(index, vd);
            }
        }

        // Set default attributes -- but only for new widgets (not when moving or copying)
        RulesEngine engine = null;
        LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(editor);
        if (delegate != null) {
            engine = delegate.getRulesEngine();
        }
        if (engine == null || engine.getInsertType().isCreate()) {
            // TODO: This should probably use IViewRule#getDefaultAttributes() at some point
            DescriptorsUtils.setDefaultLayoutAttributes(uiNew, false /*updateLayout*/);
        }

        Node xmlNode = uiNew.createXmlNode();

        if (!(uiNew instanceof UiViewElementNode) || xmlNode == null) {
            // Both things are not supposed to happen. When they do, we're in big trouble.
            // We don't really know how to revert the state at this point and the UI model is
            // now out of sync with the XML model.
            // Panic ensues.
            // The best bet is to abort now. The edit wrapper will release the edit and the
            // XML/UI should get reloaded properly (with a likely invalid XML.)
            warnPrintf("Failed to create a new %s element", viewFqcn);
            throw new RuntimeException("XML node creation failed."); //$NON-NLS-1$
        }

        UiViewElementNode uiNewView = (UiViewElementNode) uiNew;
        NodeProxy newNode = mFactory.create(uiNewView);

        if (engine != null) {
            engine.callCreateHooks(editor, this, newNode, null);
        }

        return newNode;
    }

    @Override
    public boolean setAttribute(
            @Nullable String uri,
            @NonNull String name,
            @Nullable String value) {
        checkEditOK();
        UiAttributeNode attr = mNode.setAttributeValue(name, uri, value, true /* override */);

        if (uri == null) {
            uri = ""; //$NON-NLS-1$
        }

        Map<String, String> map = null;
        if (mPendingAttributes == null) {
            // Small initial size: we don't expect many different namespaces
            mPendingAttributes = new HashMap<String, Map<String, String>>(3);
        } else {
            map = mPendingAttributes.get(uri);
        }
        if (map == null) {
            map = new HashMap<String, String>();
            mPendingAttributes.put(uri, map);
        }
        map.put(name, value);

        return attr != null;
    }

    @Override
    public String getStringAttr(@Nullable String uri, @NonNull String attrName) {
        UiElementNode uiNode = mNode;

        if (attrName == null) {
            return null;
        }

        if (mPendingAttributes != null) {
            Map<String, String> map = mPendingAttributes.get(uri == null ? "" : uri); //$NON-NLS-1$
            if (map != null) {
                String value = map.get(attrName);
                if (value != null) {
                    return value;
                }
            }
        }

        if (uiNode.getXmlNode() != null) {
            Node xmlNode = uiNode.getXmlNode();
            if (xmlNode != null) {
                NamedNodeMap nodeAttributes = xmlNode.getAttributes();
                if (nodeAttributes != null) {
                    Node attr = nodeAttributes.getNamedItemNS(uri, attrName);
                    if (attr != null) {
                        return attr.getNodeValue();
                    }
                }
            }
        }
        return null;
    }

    @Override
    public IAttributeInfo getAttributeInfo(@Nullable String uri, @NonNull String attrName) {
        UiElementNode uiNode = mNode;

        if (attrName == null) {
            return null;
        }

        for (AttributeDescriptor desc : uiNode.getAttributeDescriptors()) {
            String dUri = desc.getNamespaceUri();
            String dName = desc.getXmlLocalName();
            if ((uri == null && dUri == null) || (uri != null && uri.equals(dUri))) {
                if (attrName.equals(dName)) {
                    return desc.getAttributeInfo();
                }
            }
        }

        return null;
    }

    @Override
    public @NonNull IAttributeInfo[] getDeclaredAttributes() {

        AttributeDescriptor[] descs = mNode.getAttributeDescriptors();
        int n = descs.length;
        IAttributeInfo[] infos = new AttributeInfo[n];

        for (int i = 0; i < n; i++) {
            infos[i] = descs[i].getAttributeInfo();
        }

        return infos;
    }

    @Override
    public @NonNull List<String> getAttributeSources() {
        ElementDescriptor descriptor = mNode.getDescriptor();
        if (descriptor instanceof ViewElementDescriptor) {
            return ((ViewElementDescriptor) descriptor).getAttributeSources();
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    public @NonNull IAttribute[] getLiveAttributes() {
        UiElementNode uiNode = mNode;

        if (uiNode.getXmlNode() != null) {
            Node xmlNode = uiNode.getXmlNode();
            if (xmlNode != null) {
                NamedNodeMap nodeAttributes = xmlNode.getAttributes();
                if (nodeAttributes != null) {

                    int n = nodeAttributes.getLength();
                    IAttribute[] result = new IAttribute[n];
                    for (int i = 0; i < n; i++) {
                        Node attr = nodeAttributes.item(i);
                        String uri = attr.getNamespaceURI();
                        String name = attr.getLocalName();
                        String value = attr.getNodeValue();

                        result[i] = new SimpleAttribute(uri, name, value);
                    }
                    return result;
                }
            }
        }

        return new IAttribute[0];

    }

    @Override
    public String toString() {
        return "NodeProxy [node=" + mNode + ", bounds=" + mBounds + "]";
    }

    // --- internal helpers ---

    /**
     * Helper methods that returns a {@link ViewElementDescriptor} for the requested FQCN.
     * Will return null if we can't find that FQCN or we lack the editor/data/descriptors info
     * (which shouldn't really happen since at this point the SDK should be fully loaded and
     * isn't reloading, or we wouldn't be here editing XML for a layout rule.)
     */
    private ViewElementDescriptor getFqcnViewDescriptor(String fqcn) {
        LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(mNode.getEditor());
        if (delegate != null) {
            return delegate.getFqcnViewDescriptor(fqcn);
        }

        return null;
    }

    private void warnPrintf(String msg, Object...params) {
        AdtPlugin.printToConsole(
                mNode == null ? "" : mNode.getDescriptor().getXmlLocalName(),
                String.format(msg, params)
                );
    }

    /**
     * If there are any pending changes in these nodes, apply them now
     *
     * @return true if any modifications were made
     */
    public boolean applyPendingChanges() {
        boolean modified = false;

        // Flush all pending attributes
        if (mPendingAttributes != null) {
            mNode.commitDirtyAttributesToXml();
            modified = true;
            mPendingAttributes = null;

        }
        for (INode child : getChildren()) {
            modified |= ((NodeProxy) child).applyPendingChanges();
        }

        return modified;
    }
}