aboutsummaryrefslogtreecommitdiffstats
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseLayout.java
blob: 979a4a2455459be3b9242dcf78d934a6956d0fcb (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
/*
 * Copyright (C) 2010 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.common.layout;

import static com.android.ide.common.layout.LayoutConstants.ANDROID_URI;
import static com.android.ide.common.layout.LayoutConstants.ATTR_ID;
import static com.android.ide.common.layout.LayoutConstants.ATTR_TEXT;

import com.android.ide.common.api.DropFeedback;
import com.android.ide.common.api.IAttributeInfo;
import com.android.ide.common.api.IAttributeInfo.Format;
import com.android.ide.common.api.IClientRulesEngine;
import com.android.ide.common.api.IDragElement;
import com.android.ide.common.api.IDragElement.IDragAttribute;
import com.android.ide.common.api.IGraphics;
import com.android.ide.common.api.INode;
import com.android.ide.common.api.MenuAction;
import com.android.ide.common.api.Point;
import com.android.ide.common.api.Rect;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class BaseLayout extends BaseView {

    @Override
    public boolean onInitialize(String fqcn, IClientRulesEngine engine) {
        return super.onInitialize(fqcn, engine);
    }

    @Override
    public void onDispose() {
        super.onDispose();
    }

    @Override
    public List<MenuAction> getContextMenu(INode selectedNode) {
        return super.getContextMenu(selectedNode);
    }

    // ==== Paste support ====

    /**
     * The default behavior for pasting in a layout is to simulate a drop in the
     * top-left corner of the view.
     * <p/>
     * Note that we explicitly do not call super() here -- the BasView.onPaste
     * will call onPasteBeforeChild() instead.
     * <p/>
     * Derived layouts should override this behavior if not appropriate.
     */
    @Override
    public void onPaste(INode targetNode, IDragElement[] elements) {

        DropFeedback feedback = onDropEnter(targetNode, elements);
        if (feedback != null) {
            Point p = targetNode.getBounds().getTopLeft();
            feedback = onDropMove(targetNode, elements, feedback, p);
            if (feedback != null) {
                onDropLeave(targetNode, elements, feedback);
                onDropped(targetNode, elements, feedback, p);
            }
        }
    }

    /**
     * The default behavior for pasting in a layout with a specific child target
     * is to simulate a drop right above the top left of the given child target.
     * <p/>
     * This method is invoked by BaseView when onPaste() is called --
     * views don't generally accept children and instead use the target node as
     * a hint to paste "before" it.
     */
    public void onPasteBeforeChild(INode parentNode, INode targetNode, IDragElement[] elements) {

        DropFeedback feedback = onDropEnter(parentNode, elements);
        if (feedback != null) {
            Point parentP = parentNode.getBounds().getTopLeft();
            Point targetP = targetNode.getBounds().getTopLeft();
            if (parentP.y < targetP.y) {
                targetP.y -= 1;
            }

            feedback = onDropMove(parentNode, elements, feedback, targetP);
            if (feedback != null) {
                onDropLeave(parentNode, elements, feedback);
                onDropped(parentNode, elements, feedback, targetP);
            }
        }
    }

    // ==== Utility methods used by derived layouts ====

    /**
     * Draws the bounds of the given elements and all its children elements in
     * the canvas with the specified offset.
     */
    protected void drawElement(IGraphics gc, IDragElement element, int offsetX, int offsetY) {
        Rect b = element.getBounds();
        if (b.isValid()) {
            b = b.copy().offsetBy(offsetX, offsetY);
            gc.drawRect(b);
        }

        for (IDragElement inner : element.getInnerElements()) {
            drawElement(gc, inner, offsetX, offsetY);
        }
    }

    /**
     * Collect all the "android:id" IDs from the dropped elements. When moving
     * objects within the same canvas, that's all there is to do. However if the
     * objects are moved to a different canvas or are copied then set
     * createNewIds to true to find the existing IDs under targetNode and create
     * a map with new non-conflicting unique IDs as needed. Returns a map String
     * old-id => tuple (String new-id, String fqcn) where fqcn is the FQCN of
     * the element.
     */
    protected Map<String, Pair<String, String>> getDropIdMap(INode targetNode,
            IDragElement[] elements, boolean createNewIds) {
        Map<String, Pair<String, String>> idMap = new HashMap<String, Pair<String, String>>();

        if (createNewIds) {
            collectIds(idMap, elements);
            // Need to remap ids if necessary
            idMap = remapIds(targetNode, idMap);
        }

        return idMap;
    }

    /**
     * Fills idMap with a map String id => tuple (String id, String fqcn) where
     * fqcn is the FQCN of the element (in case we want to generate new IDs
     * based on the element type.)
     *
     * @see #getDropIdMap
     */
    protected Map<String, Pair<String, String>> collectIds(Map<String, Pair<String, String>> idMap,
            IDragElement[] elements) {
        for (IDragElement element : elements) {
            IDragAttribute attr = element.getAttribute(ANDROID_URI, ATTR_ID);
            if (attr != null) {
                String id = attr.getValue();
                if (id != null && id.length() > 0) {
                    idMap.put(id, Pair.of(id, element.getFqcn()));
                }
            }

            collectIds(idMap, element.getInnerElements());
        }

        return idMap;
    }

    /**
     * Used by #getDropIdMap to find new IDs in case of conflict.
     */
    protected Map<String, Pair<String, String>> remapIds(INode node,
            Map<String, Pair<String, String>> idMap) {
        // Visit the document to get a list of existing ids
        Set<String> existingIdSet = new HashSet<String>();
        collectExistingIds(node.getRoot(), existingIdSet);

        Map<String, Pair<String, String>> new_map = new HashMap<String, Pair<String, String>>();
        for (Map.Entry<String, Pair<String, String>> entry : idMap.entrySet()) {
            String key = entry.getKey();
            Pair<String, String> value = entry.getValue();

            String id = normalizeId(key);

            if (!existingIdSet.contains(id)) {
                // Not a conflict. Use as-is.
                new_map.put(key, value);
                if (!key.equals(id)) {
                    new_map.put(id, value);
                }
            } else {
                // There is a conflict. Get a new id.
                String new_id = findNewId(value.getSecond(), existingIdSet);
                value = Pair.of(new_id, value.getSecond());
                new_map.put(id, value);
                new_map.put(id.replaceFirst("@\\+", "@"), value); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }

        return new_map;
    }

    /**
     * Used by #remapIds to find a new ID for a conflicting element.
     */
    protected String findNewId(String fqcn, Set<String> existingIdSet) {
        // Get the last component of the FQCN (e.g. "android.view.Button" =>
        // "Button")
        String name = fqcn.substring(fqcn.lastIndexOf('.') + 1);

        for (int i = 1; i < 1000000; i++) {
            String id = String.format("@+id/%s%02d", name, i); //$NON-NLS-1$
            if (!existingIdSet.contains(id)) {
                existingIdSet.add(id);
                return id;
            }
        }

        // We'll never reach here.
        return null;
    }

    /**
     * Used by #getDropIdMap to find existing IDs recursively.
     */
    protected void collectExistingIds(INode root, Set<String> existingIdSet) {
        if (root == null) {
            return;
        }

        String id = root.getStringAttr(ANDROID_URI, ATTR_ID);
        if (id != null) {
            id = normalizeId(id);

            if (!existingIdSet.contains(id)) {
                existingIdSet.add(id);
            }
        }

        for (INode child : root.getChildren()) {
            collectExistingIds(child, existingIdSet);
        }
    }

    /**
     * Transforms @id/name into @+id/name to treat both forms the same way.
     */
    protected String normalizeId(String id) {
        if (id.indexOf("@+") == -1) { //$NON-NLS-1$
            id = id.replaceFirst("@", "@+"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        return id;
    }

    /**
     * For use by {@link BaseLayout#addAttributes} A filter should return a
     * valid replacement string.
     */
    public static interface AttributeFilter {
        String replace(String attributeUri, String attributeName, String attributeValue);
    }

    private static final String[] EXCLUDED_ATTRIBUTES = new String[] {
        // from AbsoluteLayout
        "layout_x",                      //$NON-NLS-1$
        "layout_y",                      //$NON-NLS-1$

        // from RelativeLayout
        "layout_above",                  //$NON-NLS-1$
        "layout_below",                  //$NON-NLS-1$
        "layout_toLeftOf",               //$NON-NLS-1$
        "layout_toRightOf",              //$NON-NLS-1$
        "layout_alignBaseline",          //$NON-NLS-1$
        "layout_alignTop",               //$NON-NLS-1$
        "layout_alignBottom",            //$NON-NLS-1$
        "layout_alignLeft",              //$NON-NLS-1$
        "layout_alignRight",             //$NON-NLS-1$
        "layout_alignParentTop",         //$NON-NLS-1$
        "layout_alignParentBottom",      //$NON-NLS-1$
        "layout_alignParentLeft",        //$NON-NLS-1$
        "layout_alignParentRight",       //$NON-NLS-1$
        "layout_alignWithParentMissing", //$NON-NLS-1$
        "layout_centerHorizontal",       //$NON-NLS-1$
        "layout_centerInParent",         //$NON-NLS-1$
        "layout_centerVertical",         //$NON-NLS-1$
    };

    /**
     * Default attribute filter used by the various layouts to filter out some properties
     * we don't want to offer.
     */
    public static final AttributeFilter DEFAULT_ATTR_FILTER = new AttributeFilter() {
        Set<String> mExcludes;

        public String replace(String uri, String name, String value) {
            if (!ANDROID_URI.equals(uri)) {
                return value;
            }

            if (mExcludes == null) {
                mExcludes = new HashSet<String>(EXCLUDED_ATTRIBUTES.length);
                mExcludes.addAll(Arrays.asList(EXCLUDED_ATTRIBUTES));
            }

            return mExcludes.contains(name) ? null : value;
        }
    };

    /**
     * Copies all the attributes from oldElement to newNode. Uses the idMap to
     * transform the value of all attributes of Format.REFERENCE. If filter is
     * non-null, it's a filter that can rewrite the attribute string.
     */
    protected void addAttributes(INode newNode, IDragElement oldElement,
            Map<String, Pair<String, String>> idMap, AttributeFilter filter) {

        // A little trick here: when creating new UI widgets by dropping them
        // from the palette, we assign them a new id and then set the text
        // attribute to that id, so for example a Button will have
        // android:text="@+id/Button01".
        // Here we detect if such an id is being remapped to a new id and if
        // there's a text attribute with exactly the same id name, we update it
        // too.
        String oldText = null;
        String oldId = null;
        String newId = null;

        for (IDragAttribute attr : oldElement.getAttributes()) {
            String uri = attr.getUri();
            String name = attr.getName();
            String value = attr.getValue();

            if (uri.equals(ANDROID_URI)) {
                if (name.equals(ATTR_ID)) {
                    oldId = value;
                } else if (name.equals(ATTR_TEXT)) {
                    oldText = value;
                }
            }

            IAttributeInfo attrInfo = newNode.getAttributeInfo(uri, name);
            if (attrInfo != null) {
                Format[] formats = attrInfo.getFormats();
                if (IAttributeInfo.Format.REFERENCE.in(formats)) {
                    if (idMap.containsKey(value)) {
                        value = idMap.get(value).getFirst();
                    }
                }
            }

            if (filter != null) {
                value = filter.replace(uri, name, value);
            }
            if (value != null && value.length() > 0) {
                newNode.setAttribute(uri, name, value);

                if (uri.equals(ANDROID_URI) && name.equals(ATTR_ID) &&
                        oldId != null && !oldId.equals(value)) {
                    newId = value;
                }
            }
        }

        if (newId != null && oldText != null && oldText.equals(oldId)) {
            newNode.setAttribute(ANDROID_URI, ATTR_TEXT, newId);
        }
    }

    /**
     * Adds all the children elements of oldElement to newNode, recursively.
     * Attributes are adjusted by calling addAttributes with idMap as necessary,
     * with no closure filter.
     */
    protected void addInnerElements(INode newNode, IDragElement oldElement,
            Map<String, Pair<String, String>> idMap) {

        for (IDragElement element : oldElement.getInnerElements()) {
            String fqcn = element.getFqcn();
            INode childNode = newNode.appendChild(fqcn);

            addAttributes(childNode, element, idMap, null /* filter */);
            addInnerElements(childNode, element, idMap);
        }
    }
}