aboutsummaryrefslogtreecommitdiffstats
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ClientRulesEngine.java
blob: 9c73e1c3e8ae129fa5fafea96cdded63d36f1c63 (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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/*
 * Copyright (C) 2011 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 static com.android.sdklib.SdkConstants.CLASS_FRAGMENT;
import static com.android.sdklib.SdkConstants.CLASS_V4_FRAGMENT;
import static com.android.tools.lint.detector.api.LintConstants.AUTO_URI;
import static com.android.tools.lint.detector.api.LintConstants.URI_PREFIX;

import com.android.ide.common.api.IClientRulesEngine;
import com.android.ide.common.api.INode;
import com.android.ide.common.api.IValidator;
import com.android.ide.common.api.IViewMetadata;
import com.android.ide.common.api.IViewRule;
import com.android.ide.common.api.Margins;
import com.android.ide.common.api.Rect;
import com.android.ide.common.resources.ResourceRepository;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.internal.actions.AddCompatibilityJarAction;
import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationComposite;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SelectionManager;
import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
import com.android.ide.eclipse.adt.internal.resources.CyclicDependencyValidator;
import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
import com.android.ide.eclipse.adt.internal.sdk.Sdk;
import com.android.ide.eclipse.adt.internal.ui.MarginChooser;
import com.android.ide.eclipse.adt.internal.ui.ReferenceChooserDialog;
import com.android.ide.eclipse.adt.internal.ui.ResourceChooser;
import com.android.ide.eclipse.adt.internal.ui.ResourcePreviewHelper;
import com.android.resources.ResourceType;
import com.android.sdklib.IAndroidTarget;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.actions.OpenNewClassWizardAction;
import org.eclipse.jdt.ui.dialogs.ITypeInfoFilterExtension;
import org.eclipse.jdt.ui.dialogs.ITypeInfoRequestor;
import org.eclipse.jdt.ui.dialogs.TypeSelectionExtension;
import org.eclipse.jdt.ui.wizards.NewClassWizardPage;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.SelectionDialog;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Implementation of {@link IClientRulesEngine}. This provides {@link IViewRule} clients
 * with a few methods they can use to access functionality from this {@link RulesEngine}.
 */
class ClientRulesEngine implements IClientRulesEngine {
    private final RulesEngine mRulesEngine;
    private final String mFqcn;

    public ClientRulesEngine(RulesEngine rulesEngine, String fqcn) {
        mRulesEngine = rulesEngine;
        mFqcn = fqcn;
    }

    @Override
    public String getFqcn() {
        return mFqcn;
    }

    @Override
    public void debugPrintf(String msg, Object... params) {
        AdtPlugin.printToConsole(
                mFqcn == null ? "<unknown>" : mFqcn,
                String.format(msg, params)
                );
    }

    @Override
    public IViewRule loadRule(String fqcn) {
        return mRulesEngine.loadRule(fqcn, fqcn);
    }

    @Override
    public void displayAlert(String message) {
        MessageDialog.openInformation(
                AdtPlugin.getDisplay().getActiveShell(),
                mFqcn,  // title
                message);
    }

    @Override
    public String displayInput(String message, String value, final IValidator filter) {
        IInputValidator validator = null;
        if (filter != null) {
            validator = new IInputValidator() {
                @Override
                public String isValid(String newText) {
                    // IValidator has the same interface as SWT's IInputValidator
                    try {
                        return filter.validate(newText);
                    } catch (Exception e) {
                        AdtPlugin.log(e, "Custom validator failed: %s", e.toString());
                        return ""; //$NON-NLS-1$
                    }
                }
            };
        }

        InputDialog d = new InputDialog(
                    AdtPlugin.getDisplay().getActiveShell(),
                    mFqcn,  // title
                    message,
                    value == null ? "" : value, //$NON-NLS-1$
                    validator);
        if (d.open() == Window.OK) {
            return d.getValue();
        }
        return null;
    }

    @Override
    public IViewMetadata getMetadata(final String fqcn) {
        return new IViewMetadata() {
            @Override
            public String getDisplayName() {
                // This also works when there is no "."
                return fqcn.substring(fqcn.lastIndexOf('.') + 1);
            }

            @Override
            public FillPreference getFillPreference() {
                return ViewMetadataRepository.get().getFillPreference(fqcn);
            }

            @Override
            public Margins getInsets() {
                return mRulesEngine.getEditor().getCanvasControl().getInsets(fqcn);
            }

            @Override
            public List<String> getTopAttributes() {
                return ViewMetadataRepository.get().getTopAttributes(fqcn);
            }
        };
    }

    @Override
    public int getMinApiLevel() {
        Sdk currentSdk = Sdk.getCurrent();
        if (currentSdk != null) {
            IAndroidTarget target = currentSdk.getTarget(mRulesEngine.getEditor().getProject());
            if (target != null) {
                return target.getVersion().getApiLevel();
            }
        }

        return -1;
    }

    @Override
    public IValidator getResourceValidator() {
        // When https://review.source.android.com/#change,20168 is integrated,
        // change this to
        //return ResourceNameValidator.create(false, mDelegate.getProject(), ResourceType.ID);
        return null;
    }

    @Override
    public String displayReferenceInput(String currentValue) {
        GraphicalEditorPart graphicalEditor = mRulesEngine.getEditor();
        LayoutEditorDelegate delegate = graphicalEditor.getEditorDelegate();
        IProject project = delegate.getEditor().getProject();
        if (project != null) {
            // get the resource repository for this project and the system resources.
            ResourceRepository projectRepository =
                ResourceManager.getInstance().getProjectResources(project);
            Shell shell = AdtPlugin.getDisplay().getActiveShell();
            if (shell == null) {
                return null;
            }
            ReferenceChooserDialog dlg = new ReferenceChooserDialog(
                    project,
                    projectRepository,
                    shell);
            dlg.setPreviewHelper(new ResourcePreviewHelper(dlg, graphicalEditor));

            dlg.setCurrentResource(currentValue);

            if (dlg.open() == Window.OK) {
                return dlg.getCurrentResource();
            }
        }

        return null;
    }

    @Override
    public String displayResourceInput(String resourceTypeName, String currentValue) {
        return displayResourceInput(resourceTypeName, currentValue, null);
    }

    private String displayResourceInput(String resourceTypeName, String currentValue,
            IInputValidator validator) {
        GraphicalEditorPart graphicalEditor = mRulesEngine.getEditor();
        AndroidXmlEditor editor = graphicalEditor.getEditorDelegate().getEditor();
        IProject project = editor.getProject();
        ResourceType type = ResourceType.getEnum(resourceTypeName);
        if (project != null) {
            // get the resource repository for this project and the system resources.
            ResourceRepository projectRepository = ResourceManager.getInstance()
                    .getProjectResources(project);
            Shell shell = AdtPlugin.getDisplay().getActiveShell();
            if (shell == null) {
                return null;
            }

            AndroidTargetData data = editor.getTargetData();
            ResourceRepository systemRepository = data.getFrameworkResources();

            // open a resource chooser dialog for specified resource type.
            ResourceChooser dlg = new ResourceChooser(project, type, projectRepository,
                    systemRepository, shell);
            dlg.setPreviewHelper(new ResourcePreviewHelper(dlg, graphicalEditor));

            // When editing Strings, allow editing the value text directly. When we
            // get inline editing support (where values entered directly into the
            // textual widget are translated automatically into a resource) this can
            // go away.
            if (resourceTypeName.equals(ResourceType.STRING.getName())) {
                dlg.setResourceResolver(graphicalEditor.getResourceResolver());
                dlg.setShowValueText(true);
            } else if (resourceTypeName.equals(ResourceType.DIMEN.getName())
                    || resourceTypeName.equals(ResourceType.INTEGER.getName())) {
                dlg.setResourceResolver(graphicalEditor.getResourceResolver());
            }

            if (validator != null) {
                // Ensure wide enough to accommodate validator error message
                dlg.setSize(85, 10);
                dlg.setInputValidator(validator);
            }

            dlg.setCurrentResource(currentValue);

            int result = dlg.open();
            if (result == ResourceChooser.CLEAR_RETURN_CODE) {
                return ""; //$NON-NLS-1$
            } else if (result == Window.OK) {
                return dlg.getCurrentResource();
            }
        }

        return null;
    }

    @Override
    public String[] displayMarginInput(String all, String left, String right, String top,
            String bottom) {
        GraphicalEditorPart editor = mRulesEngine.getEditor();
        IProject project = editor.getProject();
        if (project != null) {
            Shell shell = AdtPlugin.getDisplay().getActiveShell();
            if (shell == null) {
                return null;
            }
            AndroidTargetData data = editor.getEditorDelegate().getEditor().getTargetData();
            MarginChooser dialog = new MarginChooser(shell, editor, data, all, left, right,
                    top, bottom);
            if (dialog.open() == Window.OK) {
                return dialog.getMargins();
            }
        }

        return null;
    }

    @Override
    public String displayIncludeSourceInput() {
        AndroidXmlEditor editor = mRulesEngine.getEditor().getEditorDelegate().getEditor();
        IInputValidator validator = CyclicDependencyValidator.create(editor.getInputFile());
        return displayResourceInput(ResourceType.LAYOUT.getName(), null, validator);
    }

    @Override
    public void select(final Collection<INode> nodes) {
        LayoutCanvas layoutCanvas = mRulesEngine.getEditor().getCanvasControl();
        final SelectionManager selectionManager = layoutCanvas.getSelectionManager();
        selectionManager.select(nodes);
        // ALSO run an async select since immediately after nodes are created they
        // may not be selectable. We can't ONLY run an async exec since
        // code may depend on operating on the selection.
        layoutCanvas.getDisplay().asyncExec(new Runnable() {
            @Override
            public void run() {
                selectionManager.select(nodes);
            }
        });
    }

    @Override
    public String displayFragmentSourceInput() {
        try {
            // Compute a search scope: We need to merge all the subclasses
            // android.app.Fragment and android.support.v4.app.Fragment
            IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
            IProject project = mRulesEngine.getProject();
            final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
            if (javaProject != null) {
                IType oldFragmentType = javaProject.findType(CLASS_V4_FRAGMENT);

                // First check to make sure fragments are available, and if not,
                // warn the user.
                IAndroidTarget target = Sdk.getCurrent().getTarget(project);
                // No, this should be using the min SDK instead!
                if (target.getVersion().getApiLevel() < 11 && oldFragmentType == null) {
                    // Compatibility library must be present
                    MessageDialog dialog =
                        new MessageDialog(
                                Display.getCurrent().getActiveShell(),
                          "Fragment Warning",
                          null,
                          "Fragments require API level 11 or higher, or a compatibility "
                          + "library for older versions.\n\n"
                          + " Do you want to install the compatibility library?",
                          MessageDialog.QUESTION,
                          new String[] { "Install", "Cancel" },
                          1 /* default button: Cancel */);
                      int answer = dialog.open();
                      if (answer == 0) {
                          if (!AddCompatibilityJarAction.install(project)) {
                              return null;
                          }
                      } else {
                          return null;
                      }
                }

                // Look up sub-types of each (new fragment class and compatibility fragment
                // class, if any) and merge the two arrays - then create a scope from these
                // elements.
                IType[] fragmentTypes = new IType[0];
                IType[] oldFragmentTypes = new IType[0];
                if (oldFragmentType != null) {
                    ITypeHierarchy hierarchy =
                        oldFragmentType.newTypeHierarchy(new NullProgressMonitor());
                    oldFragmentTypes = hierarchy.getAllSubtypes(oldFragmentType);
                }
                IType fragmentType = javaProject.findType(CLASS_FRAGMENT);
                if (fragmentType != null) {
                    ITypeHierarchy hierarchy =
                        fragmentType.newTypeHierarchy(new NullProgressMonitor());
                    fragmentTypes = hierarchy.getAllSubtypes(fragmentType);
                }
                IType[] subTypes = new IType[fragmentTypes.length + oldFragmentTypes.length];
                System.arraycopy(fragmentTypes, 0, subTypes, 0, fragmentTypes.length);
                System.arraycopy(oldFragmentTypes, 0, subTypes, fragmentTypes.length,
                        oldFragmentTypes.length);
                scope = SearchEngine.createJavaSearchScope(subTypes, IJavaSearchScope.SOURCES);
            }

            Shell parent = AdtPlugin.getDisplay().getActiveShell();
            final AtomicReference<String> returnValue =
                new AtomicReference<String>();
            final AtomicReference<SelectionDialog> dialogHolder =
                new AtomicReference<SelectionDialog>();
            final SelectionDialog dialog = JavaUI.createTypeDialog(
                    parent,
                    new ProgressMonitorDialog(parent),
                    scope,
                    IJavaElementSearchConstants.CONSIDER_CLASSES, false,
                    // Use ? as a default filter to fill dialog with matches
                    "?", //$NON-NLS-1$
                    new TypeSelectionExtension() {
                        @Override
                        public Control createContentArea(Composite parentComposite) {
                            Composite composite = new Composite(parentComposite, SWT.NONE);
                            composite.setLayout(new GridLayout(1, false));
                            Button button = new Button(composite, SWT.PUSH);
                            button.setText("Create New...");
                            button.addSelectionListener(new SelectionAdapter() {
                                @Override
                                public void widgetSelected(SelectionEvent e) {
                                    String fqcn = createNewFragmentClass(javaProject);
                                    if (fqcn != null) {
                                        returnValue.set(fqcn);
                                        dialogHolder.get().close();
                                    }
                                }
                            });
                            return composite;
                        }

                        @Override
                        public ITypeInfoFilterExtension getFilterExtension() {
                            return new ITypeInfoFilterExtension() {
                                @Override
                                public boolean select(ITypeInfoRequestor typeInfoRequestor) {
                                    int modifiers = typeInfoRequestor.getModifiers();
                                    if (!Flags.isPublic(modifiers)
                                            || Flags.isInterface(modifiers)
                                            || Flags.isEnum(modifiers)) {
                                        return false;
                                    }
                                    return true;
                                }
                            };
                        }
                    });
            dialogHolder.set(dialog);

            dialog.setTitle("Choose Fragment Class");
            dialog.setMessage("Select a Fragment class (? = any character, * = any string):");
            if (dialog.open() == IDialogConstants.CANCEL_ID) {
                return null;
            }
            if (returnValue.get() != null) {
                return returnValue.get();
            }

            Object[] types = dialog.getResult();
            if (types != null && types.length > 0) {
                return ((IType) types[0]).getFullyQualifiedName();
            }
        } catch (JavaModelException e) {
            AdtPlugin.log(e, null);
        } catch (CoreException e) {
            AdtPlugin.log(e, null);
        }
        return null;
    }

    @Override
    public void redraw() {
        mRulesEngine.getEditor().getCanvasControl().redraw();
    }

    @Override
    public void layout() {
        mRulesEngine.getEditor().recomputeLayout();
    }

    @Override
    public Map<INode, Rect> measureChildren(INode parent,
            IClientRulesEngine.AttributeFilter filter) {
        RenderService renderService = RenderService.create(mRulesEngine.getEditor());
        Map<INode, Rect> map = renderService.measureChildren(parent, filter);
        if (map == null) {
            map = Collections.emptyMap();
        }
        return map;
    }

    @Override
    public int pxToDp(int px) {
        ConfigurationComposite config = mRulesEngine.getEditor().getConfigurationComposite();
        float dpi = config.getDensity().getDpiValue();
        return (int) (px * 160 / dpi);
    }

    @Override
    public int dpToPx(int dp) {
        ConfigurationComposite config = mRulesEngine.getEditor().getConfigurationComposite();
        float dpi = config.getDensity().getDpiValue();
        return (int) (dp * dpi / 160);
    }

    @Override
    public int screenToLayout(int pixels) {
        return (int) (pixels / mRulesEngine.getEditor().getCanvasControl().getScale());
    }

    String createNewFragmentClass(IJavaProject javaProject) {
        NewClassWizardPage page = new NewClassWizardPage();

        IProject project = mRulesEngine.getProject();
        IAndroidTarget target = Sdk.getCurrent().getTarget(project);
        String superClass;
        if (target.getVersion().getApiLevel() < 11) {
            superClass = CLASS_V4_FRAGMENT;
        } else {
            superClass = CLASS_FRAGMENT;
        }
        page.setSuperClass(superClass, true /* canBeModified */);
        IPackageFragmentRoot root = ManifestInfo.getSourcePackageRoot(javaProject);
        if (root != null) {
            page.setPackageFragmentRoot(root, true /* canBeModified */);
        }
        ManifestInfo manifestInfo = ManifestInfo.get(project);
        IPackageFragment pkg = manifestInfo.getPackageFragment();
        if (pkg != null) {
            page.setPackageFragment(pkg, true /* canBeModified */);
        }
        OpenNewClassWizardAction action = new OpenNewClassWizardAction();
        action.setConfiguredWizardPage(page);
        action.run();
        IType createdType = page.getCreatedType();
        if (createdType != null) {
            return createdType.getFullyQualifiedName();
        } else {
            return null;
        }
    }

    @Override
    public String getUniqueId(String fqcn) {
        UiDocumentNode root = mRulesEngine.getEditor().getModel();
        String prefix = fqcn.substring(fqcn.lastIndexOf('.') + 1);
        prefix = Character.toLowerCase(prefix.charAt(0)) + prefix.substring(1);
        return DescriptorsUtils.getFreeWidgetId(root, prefix);
    }

    @Override
    public String getAppNameSpace() {
        IProject project = mRulesEngine.getEditor().getProject();

        ProjectState projectState = Sdk.getProjectState(project);
        if (projectState != null && projectState.isLibrary()) {
            return AUTO_URI;
        }

        ManifestInfo info = ManifestInfo.get(project);
        return URI_PREFIX + info.getPackage();
    }
}