aboutsummaryrefslogtreecommitdiff
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SdkSelectionPage.java
blob: 6cafcf0575a449eb6dd1903612b03cb0dbbac6ea (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
/*
 * 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.wizards.newproject;

import com.android.SdkConstants;
import com.android.annotations.Nullable;
import com.android.ide.common.sdk.LoadStatus;
import com.android.ide.common.xml.AndroidManifestParser;
import com.android.ide.common.xml.ManifestData;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.internal.sdk.Sdk;
import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener;
import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
import com.android.io.FileWrapper;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.SdkManager;
import com.android.sdkuilib.internal.widgets.SdkTargetSelector;
import com.android.utils.NullLogger;
import com.android.utils.Pair;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

/** A page in the New Project wizard where you select the target SDK */
class SdkSelectionPage extends WizardPage implements ITargetChangeListener {
    private final NewProjectWizardState mValues;
    private boolean mIgnore;
    private SdkTargetSelector mSdkTargetSelector;

    /**
     * Create the wizard.
     */
    SdkSelectionPage(NewProjectWizardState values) {
        super("sdkSelection"); //$NON-NLS-1$
        mValues = values;

        setTitle("Select Build Target");
        AdtPlugin.getDefault().addTargetListener(this);
    }

    @Override
    public void dispose() {
        AdtPlugin.getDefault().removeTargetListener(this);
        super.dispose();
    }

    /**
     * Create contents of the wizard.
     */
    @Override
    public void createControl(Composite parent) {
        Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
        // Layout has 1 column
        group.setLayout(new GridLayout());
        group.setLayoutData(new GridData(GridData.FILL_BOTH));
        group.setFont(parent.getFont());
        group.setText("Build Target");

        // The selector is created without targets. They are added below in the change listener.
        mSdkTargetSelector = new SdkTargetSelector(group, null);

        mSdkTargetSelector.setSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                if (mIgnore) {
                    return;
                }

                mValues.target = mSdkTargetSelector.getSelected();
                mValues.targetModifiedByUser = true;
                onSdkTargetModified();
                validatePage();
            }
        });

        onSdkLoaded();

        setControl(group);
    }

    @Override
    public void setVisible(boolean visible) {
        super.setVisible(visible);
        if (mValues.mode == Mode.SAMPLE) {
            setDescription("Choose an SDK to select a sample from");
        } else {
            setDescription("Choose an SDK to target");
        }
        try {
            mIgnore = true;
            if (mValues.target != null) {
                mSdkTargetSelector.setSelection(mValues.target);
            }
        } finally {
            mIgnore = false;
        }

        validatePage();
    }

    @Override
    public boolean isPageComplete() {
        // Ensure that the Finish button isn't enabled until
        // the user has reached and completed this page
        if (mValues.target == null) {
            return false;
        }

        return super.isPageComplete();
    }

    /**
     * Called when an SDK target is modified.
     *
     * Also changes the minSdkVersion field to reflect the sdk api level that has
     * just been selected.
     */
    private void onSdkTargetModified() {
        if (mIgnore) {
            return;
        }

        IAndroidTarget target = mValues.target;

        // Update the minimum SDK text field?
        // We do if one of two conditions are met:
        if (target != null) {
            boolean setMinSdk = false;
            AndroidVersion version = target.getVersion();
            int apiLevel = version.getApiLevel();
            // 1. Has the user not manually edited the SDK field yet? If so, keep
            //    updating it to the selected value.
            if (!mValues.minSdkModifiedByUser) {
                setMinSdk = true;
            } else {
                // 2. Is the API level set to a higher level than the newly selected
                //    target SDK? If so, change it down to the new lower value.
                String s = mValues.minSdk;
                if (s.length() > 0) {
                    try {
                        int currentApi = Integer.parseInt(s);
                        if (currentApi > apiLevel) {
                            setMinSdk = true;
                        }
                    } catch (NumberFormatException nfe) {
                        // User may have typed something invalid -- ignore
                    }
                }
            }
            if (setMinSdk) {
                String minSdk;
                if (version.isPreview()) {
                    minSdk = version.getCodename();
                } else {
                    minSdk = Integer.toString(apiLevel);
                }
                mValues.minSdk = minSdk;
            }
        }

        loadSamplesForTarget(target);
    }

    /**
     * Updates the list of all samples for the given target SDK.
     * The list is stored in mSamplesPaths as absolute directory paths.
     * The combo is recreated to match this.
     */
    private void loadSamplesForTarget(IAndroidTarget target) {
        // Keep the name of the old selection (if there were any samples)
        File previouslyChosenSample = mValues.chosenSample;

        mValues.samples.clear();
        mValues.chosenSample = null;

        if (target != null) {
            // Get the sample root path and recompute the list of samples
            String samplesRootPath = target.getPath(IAndroidTarget.SAMPLES);

            File root = new File(samplesRootPath);
            findSamplesManifests(root, root, null, null, mValues.samples);

            Sdk sdk = Sdk.getCurrent();
            if (sdk != null) {
                // Parse the extras to see if we can find samples that are
                // compatible with the selected target API.
                // First we need an SdkManager that suppresses all output.
                SdkManager sdkman = sdk.getNewSdkManager(NullLogger.getLogger());

                Map<File, String> extras = sdkman.getExtraSamples();
                for (Entry<File, String> entry : extras.entrySet()) {
                    File path = entry.getKey();
                    String name = entry.getValue();

                    // Case where the sample is at the root of the directory and not
                    // in a per-sample sub-directory.
                    if (path.getName().equals(SdkConstants.FD_SAMPLE)) {
                        findSampleManifestInDir(
                                path, path, name, target.getVersion(), mValues.samples);
                    }

                    // Scan sub-directories
                    findSamplesManifests(
                            path, path, name, target.getVersion(), mValues.samples);
                }
            }

            if (mValues.samples.isEmpty()) {
                return;
            } else {
                Collections.sort(mValues.samples, new Comparator<Pair<String, File>>() {
                    @Override
                    public int compare(Pair<String, File> o1, Pair<String, File> o2) {
                        // Compare the display name of the sample
                        return o1.getFirst().compareTo(o2.getFirst());
                    }
                });
            }

            // Try to find the old selection.
            if (previouslyChosenSample != null) {
                String previouslyChosenName = previouslyChosenSample.getName();
                for (int i = 0, n = mValues.samples.size(); i < n; i++) {
                    File file = mValues.samples.get(i).getSecond();
                    if (file.getName().equals(previouslyChosenName)) {
                        mValues.chosenSample = file;
                        break;
                    }
                }
            }
        }
    }

    /**
     * Recursively find potential sample directories under the given directory.
     * Actually lists any directory that contains an android manifest.
     * Paths found are added the samplesPaths list.
     *
     * @param rootDir The "samples" root directory. Doesn't change during recursion.
     * @param currDir The directory being scanned. Caller must initially set it to {@code rootDir}.
     * @param extraName Optional name appended to the samples display name. Typically used to
     *   indicate a sample comes from a given extra package.
     * @param targetVersion Optional target version filter. If non null, only samples that are
     *   compatible with the given target will be listed.
     * @param samplesPaths A non-null list filled by this method with all samples found. The
     *   pair is (String: sample display name => File: sample directory).
     */
    private void findSamplesManifests(
            File rootDir,
            File currDir,
            @Nullable String extraName,
            @Nullable AndroidVersion targetVersion,
            List<Pair<String, File>> samplesPaths) {
        if (!currDir.isDirectory()) {
            return;
        }

        for (File f : currDir.listFiles()) {
            if (f.isDirectory()) {
                findSampleManifestInDir(f, rootDir, extraName, targetVersion, samplesPaths);

                // Recurse in the project, to find embedded tests sub-projects
                // We can however skip this recursion for known android sub-dirs that
                // can't have projects, namely for sources, assets and resources.
                String leaf = f.getName();
                if (!SdkConstants.FD_SOURCES.equals(leaf) &&
                        !SdkConstants.FD_ASSETS.equals(leaf) &&
                        !SdkConstants.FD_RES.equals(leaf)) {
                    findSamplesManifests(rootDir, f, extraName, targetVersion, samplesPaths);
                }
            }
        }
    }

    private void findSampleManifestInDir(
            File sampleDir,
            File rootDir,
            String extraName,
            AndroidVersion targetVersion,
            List<Pair<String, File>> samplesPaths) {
        // Assume this is a sample if it contains an android manifest.
        File manifestFile = new File(sampleDir, SdkConstants.FN_ANDROID_MANIFEST_XML);
        if (manifestFile.isFile()) {
            try {
                ManifestData data =
                    AndroidManifestParser.parse(new FileWrapper(manifestFile));
                if (data != null) {
                    boolean accept = false;
                    if (targetVersion == null) {
                        accept = true;
                    } else if (targetVersion != null) {
                        int i = data.getMinSdkVersion();
                        if (i != ManifestData.MIN_SDK_CODENAME) {
                           accept = i <= targetVersion.getApiLevel();
                        } else {
                            String s = data.getMinSdkVersionString();
                            if (s != null) {
                                accept = s.equals(targetVersion.getCodename());
                            }
                        }
                    }

                    if (accept) {
                        String name = getSampleDisplayName(extraName, rootDir, sampleDir);
                        samplesPaths.add(Pair.of(name, sampleDir));
                    }
                }
            } catch (Exception e) {
                // Ignore. Don't use a sample which manifest doesn't parse correctly.
                AdtPlugin.log(IStatus.INFO,
                        "NPW ignoring malformed manifest %s",   //$NON-NLS-1$
                        manifestFile.getAbsolutePath());
            }
        }
    }

    /**
     * Compute the sample name compared to its root directory.
     */
    private String getSampleDisplayName(String extraName, File rootDir, File sampleDir) {
        String name = null;
        if (!rootDir.equals(sampleDir)) {
            String path = sampleDir.getPath();
            int n = rootDir.getPath().length();
            if (path.length() > n) {
                path = path.substring(n);
                if (path.charAt(0) == File.separatorChar) {
                    path = path.substring(1);
                }
                if (path.endsWith(File.separator)) {
                    path = path.substring(0, path.length() - 1);
                }
                name = path.replaceAll(Pattern.quote(File.separator), " > ");   //$NON-NLS-1$
            }
        }
        if (name == null &&
                rootDir.equals(sampleDir) &&
                sampleDir.getName().equals(SdkConstants.FD_SAMPLE) &&
                extraName != null) {
            // This is an old-style extra with one single sample directory. Just use the
            // extra's name as the same name.
            return extraName;
        }
        if (name == null) {
            // Otherwise try to use the sample's directory name as the sample name.
            while (sampleDir != null &&
                   (name == null ||
                    SdkConstants.FD_SAMPLE.equals(name) ||
                    SdkConstants.FD_SAMPLES.equals(name))) {
                name = sampleDir.getName();
                sampleDir = sampleDir.getParentFile();
            }
        }
        if (name == null) {
            if (extraName != null) {
                // In the unlikely case nothing worked and we have an extra name, use that.
                return extraName;
            } else {
                name = "Sample"; // fallback name... should not happen.         //$NON-NLS-1$
            }
        }
        if (extraName != null) {
            name = name + " [" + extraName + ']';                               //$NON-NLS-1$
        }

        return name;
    }

    private void validatePage() {
        String error = null;

        if (AdtPlugin.getDefault().getSdkLoadStatus() == LoadStatus.LOADING) {
            error = "The SDK is still loading; please wait.";
        }

        if (error == null && mValues.target == null) {
            error = "An SDK Target must be specified.";
        }

        if (error == null && mValues.mode == Mode.SAMPLE) {
            // Make sure this SDK target contains samples
            if (mValues.samples == null || mValues.samples.size() == 0) {
                error = "This target has no samples. Please select another target.";
            }
        }

        // -- update UI & enable finish if there's no error
        setPageComplete(error == null);
        if (error != null) {
            setMessage(error, IMessageProvider.ERROR);
        } else {
            setErrorMessage(null);
            setMessage(null);
        }
    }

    // ---- Implements ITargetChangeListener ----
    @Override
    public void onSdkLoaded() {
        if (mSdkTargetSelector == null) {
            return;
        }

        // Update the sdk target selector with the new targets

        // get the targets from the sdk
        IAndroidTarget[] targets = null;
        if (Sdk.getCurrent() != null) {
            targets = Sdk.getCurrent().getTargets();
        }
        mSdkTargetSelector.setTargets(targets);

        // If there's only one target, select it.
        // This will invoke the selection listener on the selector defined above.
        if (targets != null && targets.length == 1) {
            mValues.target = targets[0];
            mSdkTargetSelector.setSelection(mValues.target);
            onSdkTargetModified();
        } else if (targets != null) {
            // Pick the highest available platform by default (see issue #17505
            // for related discussion.)
            IAndroidTarget initialTarget = null;
            for (IAndroidTarget target : targets) {
                if (target.isPlatform()
                        && !target.getVersion().isPreview()
                        && (initialTarget == null ||
                                target.getVersion().getApiLevel() >
                                    initialTarget.getVersion().getApiLevel())) {
                    initialTarget = target;
                }
            }
            if (initialTarget != null) {
                mValues.target = initialTarget;
                try {
                    mIgnore = true;
                    mSdkTargetSelector.setSelection(mValues.target);
                } finally {
                    mIgnore = false;
                }
                onSdkTargetModified();
            }
        }

        validatePage();
    }

    @Override
    public void onProjectTargetChange(IProject changedProject) {
        // Ignore
    }

    @Override
    public void onTargetLoaded(IAndroidTarget target) {
        // Ignore
    }
}