use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.
the class MigrateDrawableToMipmapFix method apply.
@Override
public void apply(@NotNull PsiElement startElement, @NotNull PsiElement endElement, @NotNull AndroidQuickfixContexts.Context context) {
Project project = startElement.getProject();
AndroidFacet facet = AndroidFacet.getInstance(startElement);
if (facet == null) {
return;
}
final List<PsiFile> bitmaps = Lists.newArrayList();
final Set<PsiElement> references = Sets.newHashSet();
GlobalSearchScope useScope = GlobalSearchScope.projectScope(project);
ProjectResourceRepository projectResources = facet.getProjectResources(true);
List<ResourceItem> resourceItems = projectResources.getResourceItem(myUrl.type, myUrl.name);
if (resourceItems != null) {
for (ResourceItem item : resourceItems) {
PsiFile file = LocalResourceRepository.getItemPsiFile(project, item);
if (file == null) {
continue;
}
bitmaps.add(file);
Iterable<PsiReference> allReferences = SearchUtils.findAllReferences(file, useScope);
for (PsiReference next : allReferences) {
PsiElement element = next.getElement();
if (element != null) {
references.add(element);
}
}
}
}
PsiField[] resourceFields = AndroidResourceUtil.findResourceFields(facet, ResourceType.DRAWABLE.getName(), myUrl.name, true);
if (resourceFields.length == 1) {
Iterable<PsiReference> allReferences = SearchUtils.findAllReferences(resourceFields[0], useScope);
for (PsiReference next : allReferences) {
PsiElement element = next.getElement();
if (element != null) {
references.add(element);
}
}
}
Set<PsiFile> applicableFiles = Sets.newHashSet();
applicableFiles.addAll(bitmaps);
for (PsiElement element : references) {
PsiFile containingFile = element.getContainingFile();
if (containingFile != null) {
applicableFiles.add(containingFile);
}
}
WriteCommandAction<Void> action = new WriteCommandAction<Void>(project, "Migrate Drawable to Bitmap", applicableFiles.toArray(new PsiFile[applicableFiles.size()])) {
@Override
protected void run(@NotNull Result<Void> result) throws Throwable {
// Move each drawable bitmap from drawable-my-qualifiers to bitmap-my-qualifiers
for (PsiFile bitmap : bitmaps) {
VirtualFile file = bitmap.getVirtualFile();
if (file == null) {
continue;
}
VirtualFile parent = file.getParent();
if (parent == null) {
// shouldn't happen for bitmaps found in the resource repository
continue;
}
if (file.getFileType() == StdFileTypes.XML && parent.getName().startsWith(FD_RES_VALUES)) {
// Resource alias rather than an actual drawable XML file: update the type reference instead
XmlFile xmlFile = (XmlFile) bitmap;
XmlTag root = xmlFile.getRootTag();
if (root != null) {
for (XmlTag item : root.getSubTags()) {
String name = item.getAttributeValue(ATTR_NAME);
if (myUrl.name.equals(name)) {
if (ResourceType.DRAWABLE.getName().equals(item.getName())) {
item.setName(ResourceType.MIPMAP.getName());
} else if (ResourceType.DRAWABLE.getName().equals(item.getAttributeValue(ATTR_TYPE))) {
item.setAttribute(ATTR_TYPE, ResourceType.MIPMAP.getName());
}
}
}
}
// Don't move the file
continue;
}
VirtualFile res = parent.getParent();
if (res == null) {
// shouldn't happen for bitmaps found in the resource repository
continue;
}
FolderConfiguration configuration = FolderConfiguration.getConfigForFolder(parent.getName());
if (configuration == null) {
continue;
}
String targetFolderName = configuration.getFolderName(ResourceFolderType.MIPMAP);
VirtualFile targetFolder = res.findChild(targetFolderName);
if (targetFolder == null) {
targetFolder = res.createChildDirectory(this, targetFolderName);
}
file.move(this, targetFolder);
}
// Update references
for (PsiElement reference : references) {
if (reference instanceof XmlAttributeValue) {
// Convert @drawable/foo references to @mipmap/foo
XmlAttributeValue value = (XmlAttributeValue) reference;
XmlAttribute attribute = (XmlAttribute) value.getParent();
attribute.setValue(ResourceUrl.create(ResourceType.MIPMAP, myUrl.name, false, false).toString());
} else if (reference instanceof PsiReferenceExpression) {
// Convert R.drawable.foo references to R.mipmap.foo
PsiReferenceExpression inner = (PsiReferenceExpression) reference;
PsiExpression qualifier = inner.getQualifierExpression();
if (qualifier instanceof PsiReferenceExpression) {
PsiReferenceExpression outer = (PsiReferenceExpression) qualifier;
if (outer.getReferenceNameElement() instanceof PsiIdentifier) {
PsiIdentifier identifier = (PsiIdentifier) outer.getReferenceNameElement();
if (ResourceType.DRAWABLE.getName().equals(identifier.getText())) {
Project project = reference.getProject();
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
PsiIdentifier newIdentifier = elementFactory.createIdentifier(ResourceType.MIPMAP.getName());
identifier.replace(newIdentifier);
}
}
}
}
}
}
};
action.execute();
}
use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.
the class RenderTemplateModel method handleFinished.
@Override
protected void handleFinished() {
if (!myProject.get().isPresent()) {
getLog().error("RenderTemplateModel did not collect expected information and will not complete. Please report this error.");
return;
}
AndroidProjectPaths paths = mySourceSet.get().getPaths();
final Project project = myProject.getValue();
boolean canRender = renderTemplate(true, project, paths, null, null);
if (!canRender) {
// If here, there was a render conflict and the user chose to cancel creating the template
return;
}
final List<File> filesToOpen = Lists.newArrayListWithExpectedSize(3);
final List<File> filesToReformat = Lists.newArrayList();
boolean success = new WriteCommandAction<Boolean>(project, myCommandName) {
@Override
protected void run(@NotNull Result<Boolean> result) throws Throwable {
boolean success = renderTemplate(false, project, paths, filesToOpen, filesToReformat);
if (success && myIconGenerator != null) {
myIconGenerator.generateImageIconsIntoPath(paths);
}
result.setResult(success);
}
}.execute().getResultObject();
if (success) {
ApplicationManager.getApplication().invokeLater(() -> TemplateUtils.openEditors(project, filesToOpen, true));
}
}
use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.
the class NewModuleModel method handleFinished.
@Override
protected void handleFinished() {
if (myTemplateFile.getValueOrNull() == null) {
// If here, the user opted to skip creating any module at all, or is just adding a new Activity
return;
}
// By the time we run handleFinished(), we must have a Project
if (!myProject.get().isPresent()) {
getLog().error("NewModuleModel did not collect expected information and will not complete. Please report this error.");
return;
}
Map<String, Object> renderTemplateValues = myRenderTemplateValues.getValueOrNull();
Map<String, Object> templateValues = new HashMap<>();
if (renderTemplateValues != null) {
templateValues.putAll(renderTemplateValues);
}
templateValues.putAll(myTemplateValues);
templateValues.put(ATTR_IS_LIBRARY_MODULE, myIsLibrary.get());
Project project = myProject.getValue();
boolean canRender = renderModule(true, templateValues, project);
if (!canRender) {
// If here, there was a render conflict and the user chose to cancel creating the template
return;
}
boolean success = new WriteCommandAction<Boolean>(project, "New Module") {
@Override
protected void run(@NotNull Result<Boolean> result) throws Throwable {
boolean success = renderModule(false, templateValues, project);
result.setResult(success);
}
}.execute().getResultObject();
if (!success) {
getLog().warn("A problem occurred while creating a new Module. Please check the log file for possible errors.");
}
}
use of com.intellij.openapi.command.WriteCommandAction in project intellij-community by JetBrains.
the class AppEngineUploader method createUploader.
@Nullable
public static AppEngineUploader createUploader(@NotNull Project project, @NotNull Artifact artifact, @NotNull AppEngineServerConfiguration configuration, @NotNull ServerRuntimeInstance.DeploymentOperationCallback callback, @NotNull LoggingHandler loggingHandler) {
final String explodedPath = artifact.getOutputPath();
if (explodedPath == null) {
callback.errorOccurred("Output path isn't specified for '" + artifact.getName() + "' artifact");
return null;
}
final AppEngineFacet appEngineFacet = AppEngineUtil.findAppEngineFacet(project, artifact);
if (appEngineFacet == null) {
callback.errorOccurred("App Engine facet not found in '" + artifact.getName() + "' artifact");
return null;
}
final AppEngineSdk sdk = appEngineFacet.getSdk();
if (!sdk.getAppCfgFile().exists()) {
callback.errorOccurred("Path to App Engine SDK isn't specified correctly in App Engine Facet settings");
return null;
}
PackagingElementResolvingContext context = ArtifactManager.getInstance(project).getResolvingContext();
VirtualFile descriptorFile = ArtifactUtil.findSourceFileByOutputPath(artifact, "WEB-INF/appengine-web.xml", context);
final AppEngineWebApp root = AppEngineFacet.getDescriptorRoot(descriptorFile, appEngineFacet.getModule().getProject());
if (root != null) {
final GenericDomValue<String> application = root.getApplication();
if (StringUtil.isEmptyOrSpaces(application.getValue())) {
final String name = Messages.showInputDialog(project, "<html>Application name is not specified in appengine-web.xml.<br>" + "Enter application name (see your <a href=\"http://appengine.google.com\">AppEngine account</a>):</html>", CommonBundle.getErrorTitle(), null, "", null);
if (name == null)
return null;
final PsiFile file = application.getXmlTag().getContainingFile();
new WriteCommandAction(project, file) {
protected void run(@NotNull final Result result) {
application.setStringValue(name);
}
}.execute();
final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
if (document != null) {
FileDocumentManager.getInstance().saveDocument(document);
}
}
}
AppEngineAuthData authData = AppEngineAccountDialog.createAuthData(project, configuration);
if (authData == null)
return null;
return new AppEngineUploader(project, artifact, appEngineFacet, sdk, authData, callback, loggingHandler);
}
use of com.intellij.openapi.command.WriteCommandAction in project intellij-community by JetBrains.
the class VariableInplaceRenamer method performRefactoringRename.
protected void performRefactoringRename(final String newName, final StartMarkAction markAction) {
final String refactoringId = getRefactoringId();
try {
PsiNamedElement elementToRename = getVariable();
if (refactoringId != null) {
final RefactoringEventData beforeData = new RefactoringEventData();
beforeData.addElement(elementToRename);
beforeData.addStringProperties(myOldName);
myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData);
}
if (!isIdentifier(newName, myLanguage)) {
return;
}
if (elementToRename != null) {
new WriteCommandAction(myProject, getCommandName()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
renameSynthetic(newName);
}
}.execute();
}
AutomaticRenamerFactory[] factories = Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME);
for (AutomaticRenamerFactory renamerFactory : factories) {
if (elementToRename != null && renamerFactory.isApplicable(elementToRename)) {
final List<UsageInfo> usages = new ArrayList<>();
final AutomaticRenamer renamer = renamerFactory.createRenamer(elementToRename, newName, new ArrayList<>());
if (renamer.hasAnythingToRename()) {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
final AutomaticRenamingDialog renamingDialog = new AutomaticRenamingDialog(myProject, renamer);
if (!renamingDialog.showAndGet()) {
continue;
}
}
final Runnable runnable = () -> ApplicationManager.getApplication().runReadAction(() -> renamer.findUsages(usages, false, false));
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, RefactoringBundle.message("searching.for.variables"), true, myProject)) {
return;
}
if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, PsiUtilCore.toPsiElementArray(renamer.getElements())))
return;
final Runnable performAutomaticRename = () -> {
CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject);
final UsageInfo[] usageInfos = usages.toArray(new UsageInfo[usages.size()]);
final MultiMap<PsiElement, UsageInfo> classified = RenameProcessor.classifyUsages(renamer.getElements(), usageInfos);
for (final PsiNamedElement element : renamer.getElements()) {
final String newElementName = renamer.getNewName(element);
if (newElementName != null) {
final Collection<UsageInfo> infos = classified.get(element);
RenameUtil.doRename(element, newElementName, infos.toArray(new UsageInfo[infos.size()]), myProject, RefactoringElementListener.DEAF);
}
}
};
final WriteCommandAction writeCommandAction = new WriteCommandAction(myProject, getCommandName()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
performAutomaticRename.run();
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
writeCommandAction.execute();
} else {
ApplicationManager.getApplication().invokeLater(() -> writeCommandAction.execute());
}
}
}
}
} finally {
if (refactoringId != null) {
final RefactoringEventData afterData = new RefactoringEventData();
afterData.addElement(getVariable());
afterData.addStringProperties(newName);
myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, afterData);
}
try {
((EditorImpl) InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater();
} finally {
FinishMarkAction.finish(myProject, myEditor, markAction);
}
}
}
Aggregations