summaryrefslogtreecommitdiff
path: root/android/src/com/android/tools/idea/configurations/ActivityMenuAction.java
blob: aecc8af6c0f60b6b488e94905c13ec453bc0c59e (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
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 *
 * 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.tools.idea.configurations;

import com.android.resources.ResourceType;
import com.android.tools.idea.model.ManifestInfo;
import com.android.tools.idea.model.ManifestInfo.ActivityAttributes;
import com.android.tools.idea.rendering.ResourceHelper;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.refactoring.psi.SearchUtils;
import icons.AndroidIcons;
import org.jetbrains.android.inspections.lint.SuppressLintIntentionAction;
import org.jetbrains.android.uipreview.ChooseClassDialog;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Iterator;

import static com.android.SdkConstants.*;

public class ActivityMenuAction extends FlatComboAction {
  private final RenderContext myRenderContext;

  public ActivityMenuAction(RenderContext renderContext) {
    myRenderContext = renderContext;
    Presentation presentation = getTemplatePresentation();
    presentation.setIcon(AndroidIcons.Activity);
    presentation.setDescription("Associate with Activity...");
    updatePresentation(presentation);
  }

  @Override
  public void update(AnActionEvent e) {
    super.update(e);
    updatePresentation(e.getPresentation());
  }

  private void updatePresentation(Presentation presentation) {
    Configuration configuration = myRenderContext.getConfiguration();
    boolean visible = configuration != null;
    if (visible) {
      String activity = configuration.getActivity();
      String label = getActivityLabel(activity, true);
      presentation.setText(label);
    }
    if (visible != presentation.isVisible()) {
      presentation.setVisible(visible);
    }
  }

  /**
   * Returns a suitable label to use to display the given activity
   *
   * @param fqcn the activity class to look up a label for
   * @param brief if true, generate a brief label (suitable for a toolbar
   *            button), otherwise a fuller name (suitable for a menu item)
   * @return the label
   */
  @NotNull
  public static String getActivityLabel(@Nullable String fqcn, boolean brief) {
    if (fqcn == null) {
      return "";
    }

    if (brief) {
      String label = fqcn;
      int packageIndex = label.lastIndexOf('.');
      if (packageIndex != -1) {
        label = label.substring(packageIndex + 1);
      }
      int innerClass = label.lastIndexOf('$');
      if (innerClass != -1) {
        label = label.substring(innerClass + 1);
      }

      // Also strip out the "Activity" or "Fragment" common suffix if this is a long name
      if (label.endsWith("Activity") && label.length() > 12) { // 8 for name and a few others (e.g. don't make FooActivity just Foo)
        label = label.substring(0, label.length() - 8);
      } else if (label.endsWith("Fragment") && label.length() > 12) {
        label = label.substring(0, label.length() - 8);
      }

      return label;
    }

    return fqcn;
  }

  @Override
  @NotNull
  protected DefaultActionGroup createPopupActionGroup(JComponent button) {
    DefaultActionGroup group = new DefaultActionGroup("Activity", true);

    Configuration configuration = myRenderContext.getConfiguration();
    if (configuration != null) {
      Module module = myRenderContext.getModule();
      assert module != null;
      String activity = configuration.getActivity();
      String currentFqcn = null;
      // Note: We need the manifest package, not the current variant's package, since
      // the activity names etc are always relative to the manifest package, not the effective
      // variant package
      String pkg = ManifestInfo.get(module, false).getPackage();
      if (activity != null && !activity.isEmpty()) {
        int dotIndex = activity.indexOf('.');
        if (dotIndex <= 0) {
          if (pkg != null) {
            activity = pkg + (dotIndex == -1 ? "." : "") + activity;
          }
          currentFqcn = activity;
        } else {
          currentFqcn = activity;
        }

        String title = String.format("Open %1$s", activity.substring(activity.lastIndexOf('.') + 1).replace('$','.'));
        group.add(new ShowActivityAction(myRenderContext, title, activity));
        group.addSeparator();
      }

      // List activities that reference the R.layout.<self> field here
      boolean haveSpecificActivities = false;
      VirtualFile file = configuration.getFile();
      if (file != null) {
        String layoutName = ResourceHelper.getResourceName(file);
        Project project = module.getProject();
        String rLayoutFqcn = StringUtil.notNullize(pkg) + '.' + R_CLASS + '.' + ResourceType.LAYOUT.getName();
        PsiClass layoutClass = findClassSafe(JavaPsiFacade.getInstance(project), rLayoutFqcn, GlobalSearchScope.projectScope(project));
        if (layoutClass != null) {
          PsiClass activityBase = findClassSafe(JavaPsiFacade.getInstance(project), CLASS_ACTIVITY, GlobalSearchScope.allScope(project));
          PsiField field = layoutClass.findFieldByName(layoutName, false);
          if (field != null && activityBase != null) {
            Iterable<PsiReference> allReferences = SearchUtils.findAllReferences(field, GlobalSearchScope.projectScope(project));
            Iterator<PsiReference> iterator = allReferences.iterator();
            if (iterator.hasNext()) {
              PsiReference reference = iterator.next();
              PsiElement element = reference.getElement();
              if (element != null) {
                PsiFile containingFile = element.getContainingFile();
                if (containingFile instanceof PsiJavaFile) {
                  PsiJavaFile javaFile = (PsiJavaFile)containingFile;
                  for (PsiClass cls : javaFile.getClasses()) {
                    if (cls.isInheritor(activityBase, false)) {
                      String fqcn = cls.getQualifiedName();
                      if (fqcn != null && !fqcn.equals(currentFqcn)) {
                        String className = cls.getName();
                        String title = String.format("Associate with %1$s", className);
                        group.add(new ChooseActivityAction(myRenderContext, title, fqcn));
                        haveSpecificActivities = true;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      if (haveSpecificActivities) {
        group.addSeparator();
      }

      group.add(new ChooseActivityAction(myRenderContext, "Associate with other Activity...", null));
    }

    return group;
  }

  /**
   * Try to look up class by name and scope using JavaPsiFacade, return null if IndexNotReadyException is thrown.
   */
  @Nullable
  private static PsiClass findClassSafe(@NotNull JavaPsiFacade facade, @NotNull String qualifiedName, GlobalSearchScope scope) {
    PsiClass result;
    try {
      result = facade.findClass(qualifiedName, scope);
    }
    catch (IndexNotReadyException e) {
      result = null;
    }
    return result;
  }

  private static class ChooseActivityAction extends AnAction {
    private final RenderContext myRenderContext;
    private String myActivity;

    public ChooseActivityAction(@NotNull RenderContext renderContext, @NotNull String title, @Nullable String activity) {
      super(title);
      myRenderContext = renderContext;
      myActivity = activity;
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      final Module module = myRenderContext.getModule();
      if (module == null) {
        return;
      }
      if (myActivity == null) {
        ChooseClassDialog dialog = new ChooseClassDialog(module, "Activities", false /*includeAll*/, CLASS_ACTIVITY);
        if (!dialog.showAndGet()) {
          return;
        }
        myActivity = dialog.getClassName();
        if (myActivity == null) {
          return;
        }
      }
      Configuration configuration = myRenderContext.getConfiguration();
      if (configuration != null) {
        configuration.setActivity(myActivity);

        // TODO: Should this be done elsewhere?
        // Would be nice if any call to setActivity() (from anywhere) would have this effect,
        // but is the semantics of editing a file under a write lock from a simple setter clear?
        // What about the bulk editing scheme in the configuration; should this be queued until the batch
        // edits are complete?
        final XmlFile file = myRenderContext.getXmlFile();
        assert file != null;
        WriteCommandAction<Void> action = new WriteCommandAction<Void>(module.getProject(), "Choose Activity", file) {
          @Override
          protected void run(Result<Void> result) throws Throwable {
            String activity = myActivity;
            String pkg = ManifestInfo.get(module, false).getPackage();
            if (pkg != null && activity.startsWith(pkg) && activity.length() > pkg.length()
                && activity.charAt(pkg.length()) == '.') {
              activity = activity.substring(pkg.length());
            }
            SuppressLintIntentionAction.ensureNamespaceImported(myRenderContext.getModule().getProject(), file, TOOLS_URI);
            XmlTag rootTag = file.getRootTag();
            if (rootTag != null) {
              rootTag.setAttribute(ATTR_CONTEXT, TOOLS_URI, activity);
            }
          }
        };
        action.execute();

        // Consider switching themes if the given activity has an implied theme
        ManifestInfo manifestInfo = ManifestInfo.get(module);
        ActivityAttributes attributes = manifestInfo.getActivityAttributes(myActivity);
        if (attributes != null) {
          String theme = attributes.getTheme();
          if (theme != null) {
            assert theme.startsWith(PREFIX_RESOURCE_REF) : theme;
            configuration.setTheme(theme);
          }
        }
      }
    }
  }

  private static class ShowActivityAction extends AnAction {
    private final RenderContext myRenderContext;
    private final String myActivity;

    public ShowActivityAction(@NotNull RenderContext renderContext, @NotNull String title, @NotNull String activity) {
      super(title);
      myRenderContext = renderContext;
      myActivity = activity;
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      Module module = myRenderContext.getModule();
      if (module == null) {
        return;
      }
      Project project = module.getProject();
      PsiClass clz = JavaPsiFacade.getInstance(project).findClass(myActivity.replace('$','.'), GlobalSearchScope.allScope(project));
      if (clz != null) {
        PsiFile containingFile = clz.getContainingFile();
        if (containingFile != null) {
          VirtualFile file = containingFile.getVirtualFile();
          if (file != null) {
            OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file, clz.getTextOffset());
            FileEditorManager.getInstance(project).openEditor(descriptor, true);
          }
        }
      }
    }
  }
}