1 /* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Eclipse Public License, Version 1.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.eclipse.org/org/documents/epl-v10.php 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.ide.eclipse.adt.internal.editors.layout.gre; 18 19 import com.android.ide.common.api.INode; 20 import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo; 21 import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas; 22 import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtUtils; 23 import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode; 24 25 import org.eclipse.swt.graphics.Rectangle; 26 27 import java.util.Map; 28 import java.util.WeakHashMap; 29 30 /** 31 * An object that can create {@link INode} proxies. 32 * This also keeps references to objects already created and tries to reuse them. 33 */ 34 public class NodeFactory { 35 36 private final Map<UiViewElementNode, NodeProxy> mNodeMap = 37 new WeakHashMap<UiViewElementNode, NodeProxy>(); 38 private LayoutCanvas mCanvas; 39 40 public NodeFactory(LayoutCanvas canvas) { 41 mCanvas = canvas; 42 } 43 44 /** 45 * Returns an {@link INode} proxy based on the view key of the given 46 * {@link CanvasViewInfo}. The bounds of the node are set to the canvas view bounds. 47 */ 48 public NodeProxy create(CanvasViewInfo canvasViewInfo) { 49 return create(canvasViewInfo.getUiViewNode(), canvasViewInfo.getAbsRect()); 50 } 51 52 /** 53 * Returns an {@link INode} proxy based on a given {@link UiViewElementNode} that 54 * is not yet part of the canvas, typically those created by layout rules 55 * when generating new XML. 56 */ 57 public NodeProxy create(UiViewElementNode uiNode) { 58 return create(uiNode, null /*bounds*/); 59 } 60 61 public void clear() { 62 mNodeMap.clear(); 63 } 64 65 public LayoutCanvas getCanvas() { 66 return mCanvas; 67 } 68 69 //---- 70 71 private NodeProxy create(UiViewElementNode uiNode, Rectangle bounds) { 72 NodeProxy proxy = mNodeMap.get(uiNode); 73 74 if (proxy == null) { 75 // Create a new proxy if the key doesn't exist 76 proxy = new NodeProxy(uiNode, bounds, this); 77 mNodeMap.put(uiNode, proxy); 78 79 } else if (bounds != null && !SwtUtils.equals(proxy.getBounds(), bounds)) { 80 // Update the bounds if necessary 81 proxy.setBounds(bounds); 82 } 83 84 return proxy; 85 } 86 } 87