Search in sources :

Example 81 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class HtmlLinkManager method handleAssignFragmentUrl.

private static void handleAssignFragmentUrl(@NotNull String url, @NotNull Module module, @NotNull final PsiFile file) {
    assert url.startsWith(URL_ASSIGN_FRAGMENT_URL) : url;
    final String className = ChooseClassDialog.openDialog(module, "Fragments", true, null, CLASS_FRAGMENT, CLASS_V4_FRAGMENT);
    if (className == null) {
        return;
    }
    final String fragmentClass = getFragmentClass(module, className);
    int start = URL_ASSIGN_FRAGMENT_URL.length();
    final String id;
    if (start == url.length()) {
        // No specific fragment identified; use the first one
        id = null;
    } else {
        id = LintUtils.stripIdPrefix(url.substring(start));
    }
    WriteCommandAction<Void> action = new WriteCommandAction<Void>(module.getProject(), "Assign Fragment", file) {

        @Override
        protected void run(@NotNull Result<Void> result) throws Throwable {
            Collection<XmlTag> tags = PsiTreeUtil.findChildrenOfType(file, XmlTag.class);
            for (XmlTag tag : tags) {
                if (!tag.getName().equals(VIEW_FRAGMENT)) {
                    continue;
                }
                if (id != null) {
                    String tagId = tag.getAttributeValue(ATTR_ID, ANDROID_URI);
                    if (tagId == null || !tagId.endsWith(id) || !id.equals(LintUtils.stripIdPrefix(tagId))) {
                        continue;
                    }
                }
                if (tag.getAttribute(ATTR_NAME, ANDROID_URI) == null && tag.getAttribute(ATTR_CLASS) == null) {
                    tag.setAttribute(ATTR_NAME, ANDROID_URI, fragmentClass);
                    return;
                }
            }
            if (id == null) {
                for (XmlTag tag : tags) {
                    if (!tag.getName().equals(VIEW_FRAGMENT)) {
                        continue;
                    }
                    tag.setAttribute(ATTR_NAME, ANDROID_URI, fragmentClass);
                    break;
                }
            }
        }
    };
    action.execute();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) XmlTag(com.intellij.psi.xml.XmlTag)

Example 82 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class HtmlLinkManager method handleReplaceAttributeValue.

private static void handleReplaceAttributeValue(@NotNull String url, @NotNull Module module, @NotNull final PsiFile file) {
    assert url.startsWith(URL_REPLACE_ATTRIBUTE_VALUE);
    int attributeStart = URL_REPLACE_ATTRIBUTE_VALUE.length();
    int valueStart = url.indexOf('/');
    int newValueStart = url.indexOf('/', valueStart + 1);
    final String attributeName = url.substring(attributeStart, valueStart);
    final String oldValue = url.substring(valueStart + 1, newValueStart);
    final String newValue = url.substring(newValueStart + 1);
    WriteCommandAction<Void> action = new WriteCommandAction<Void>(module.getProject(), "Set Attribute Value", file) {

        @Override
        protected void run(@NotNull Result<Void> result) throws Throwable {
            Collection<XmlAttribute> attributes = PsiTreeUtil.findChildrenOfType(file, XmlAttribute.class);
            int oldValueLen = oldValue.length();
            for (XmlAttribute attribute : attributes) {
                if (attributeName.equals(attribute.getLocalName())) {
                    String attributeValue = attribute.getValue();
                    if (attributeValue == null) {
                        continue;
                    }
                    if (oldValue.equals(attributeValue)) {
                        attribute.setValue(newValue);
                    } else {
                        int index = attributeValue.indexOf(oldValue);
                        if (index != -1) {
                            if ((index == 0 || attributeValue.charAt(index - 1) == '|') && (index + oldValueLen == attributeValue.length() || attributeValue.charAt(index + oldValueLen) == '|')) {
                                attributeValue = attributeValue.substring(0, index) + newValue + attributeValue.substring(index + oldValueLen);
                                attribute.setValue(attributeValue);
                            }
                        }
                    }
                }
            }
        }
    };
    action.execute();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) XmlAttribute(com.intellij.psi.xml.XmlAttribute) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result)

Example 83 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class AndroidExtractStyleAction method doExtractStyle.

@Nullable
public static String doExtractStyle(@NotNull Module module, @NotNull final XmlTag viewTag, final boolean addStyleAttributeToTag, @Nullable MyTestConfig testConfig) {
    final PsiFile file = viewTag.getContainingFile();
    if (file == null) {
        return null;
    }
    final String dialogTitle = AndroidBundle.message("android.extract.style.title");
    final String fileName = AndroidResourceUtil.getDefaultResourceFileName(ResourceType.STYLE);
    assert fileName != null;
    final List<String> dirNames = Collections.singletonList(ResourceFolderType.VALUES.getName());
    final List<XmlAttribute> extractableAttributes = getExtractableAttributes(viewTag);
    final Project project = module.getProject();
    if (extractableAttributes.size() == 0) {
        AndroidUtils.reportError(project, "The tag doesn't contain any attributes that can be extracted", dialogTitle);
        return null;
    }
    final LayoutViewElement viewElement = getLayoutViewElement(viewTag);
    assert viewElement != null;
    final ResourceValue parentStyleValue = viewElement.getStyle().getValue();
    final String parentStyle;
    boolean supportImplicitParent = false;
    if (parentStyleValue != null) {
        parentStyle = parentStyleValue.getResourceName();
        if (ResourceType.STYLE != parentStyleValue.getType() || parentStyle == null || parentStyle.length() == 0) {
            AndroidUtils.reportError(project, "Invalid parent style reference " + parentStyleValue.toString(), dialogTitle);
            return null;
        }
        supportImplicitParent = parentStyleValue.getNamespace() == null;
    } else {
        parentStyle = null;
    }
    final String styleName;
    final List<XmlAttribute> styledAttributes;
    final VirtualFile chosenDirectory;
    final boolean searchStyleApplications;
    if (testConfig == null) {
        final ExtractStyleDialog dialog = new ExtractStyleDialog(module, fileName, supportImplicitParent ? parentStyle : null, dirNames, extractableAttributes);
        dialog.setTitle(dialogTitle);
        if (!dialog.showAndGet()) {
            return null;
        }
        searchStyleApplications = dialog.isToSearchStyleApplications();
        chosenDirectory = dialog.getResourceDirectory();
        if (chosenDirectory == null) {
            AndroidUtils.reportError(project, AndroidBundle.message("check.resource.dir.error", module.getName()));
            return null;
        }
        styledAttributes = dialog.getStyledAttributes();
        styleName = dialog.getStyleName();
    } else {
        testConfig.validate(extractableAttributes);
        chosenDirectory = testConfig.getResourceDirectory();
        styleName = testConfig.getStyleName();
        final Set<String> attrsToExtract = new HashSet<String>(Arrays.asList(testConfig.getAttributesToExtract()));
        styledAttributes = new ArrayList<XmlAttribute>();
        for (XmlAttribute attribute : extractableAttributes) {
            if (attrsToExtract.contains(attribute.getName())) {
                styledAttributes.add(attribute);
            }
        }
        searchStyleApplications = false;
    }
    final boolean[] success = { false };
    final Ref<Style> createdStyleRef = Ref.create();
    final boolean finalSupportImplicitParent = supportImplicitParent;
    new WriteCommandAction(project, "Extract Android Style '" + styleName + "'", file) {

        @Override
        protected void run(@NotNull final Result result) throws Throwable {
            final List<XmlAttribute> attributesToDelete = new ArrayList<XmlAttribute>();
            if (!AndroidResourceUtil.createValueResource(project, chosenDirectory, styleName, null, ResourceType.STYLE, fileName, dirNames, new Processor<ResourceElement>() {

                @Override
                public boolean process(ResourceElement element) {
                    assert element instanceof Style;
                    final Style style = (Style) element;
                    createdStyleRef.set(style);
                    for (XmlAttribute attribute : styledAttributes) {
                        if (SdkConstants.NS_RESOURCES.equals(attribute.getNamespace())) {
                            final StyleItem item = style.addItem();
                            item.getName().setStringValue("android:" + attribute.getLocalName());
                            item.setStringValue(attribute.getValue());
                            attributesToDelete.add(attribute);
                        }
                    }
                    if (parentStyleValue != null && (!finalSupportImplicitParent || !styleName.startsWith(parentStyle + "."))) {
                        final String aPackage = parentStyleValue.getNamespace();
                        style.getParentStyle().setStringValue((aPackage != null ? aPackage + ":" : "") + parentStyle);
                    }
                    return true;
                }
            })) {
                return;
            }
            ApplicationManager.getApplication().runWriteAction(new Runnable() {

                @Override
                public void run() {
                    for (XmlAttribute attribute : attributesToDelete) {
                        attribute.delete();
                    }
                    if (addStyleAttributeToTag) {
                        final LayoutViewElement viewElement = getLayoutViewElement(viewTag);
                        assert viewElement != null;
                        viewElement.getStyle().setStringValue("@style/" + styleName);
                    }
                }
            });
            success[0] = true;
        }

        @Override
        protected UndoConfirmationPolicy getUndoConfirmationPolicy() {
            return UndoConfirmationPolicy.REQUEST_CONFIRMATION;
        }
    }.execute();
    if (!success[0]) {
        return null;
    }
    final Style createdStyle = createdStyleRef.get();
    final XmlTag createdStyleTag = createdStyle != null ? createdStyle.getXmlTag() : null;
    if (createdStyleTag != null) {
        final AndroidFindStyleApplicationsAction.MyStyleData createdStyleData = AndroidFindStyleApplicationsAction.getStyleData(createdStyleTag);
        if (createdStyleData != null && searchStyleApplications) {
            ApplicationManager.getApplication().invokeLater(new Runnable() {

                @Override
                public void run() {
                    AndroidFindStyleApplicationsAction.doRefactoringForTag(createdStyleTag, createdStyleData, file, null);
                }
            });
        }
    }
    return styleName;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) XmlAttribute(com.intellij.psi.xml.XmlAttribute) LayoutViewElement(org.jetbrains.android.dom.layout.LayoutViewElement) StyleItem(org.jetbrains.android.dom.resources.StyleItem) Result(com.intellij.openapi.application.Result) UndoConfirmationPolicy(com.intellij.openapi.command.UndoConfirmationPolicy) ResourceValue(org.jetbrains.android.dom.resources.ResourceValue) Style(org.jetbrains.android.dom.resources.Style) PsiFile(com.intellij.psi.PsiFile) HashSet(com.intellij.util.containers.HashSet) ResourceElement(org.jetbrains.android.dom.resources.ResourceElement) Project(com.intellij.openapi.project.Project) XmlTag(com.intellij.psi.xml.XmlTag) Nullable(org.jetbrains.annotations.Nullable)

Example 84 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class MockupFileHelper method writePositionToXML.

/**
   * Write the attribute {@link SdkConstants#ATTR_MOCKUP_CROP} and its value using the provided mockup
   * @param mockup The mockup to retrieve the position string from
   * @see #getPositionString(Mockup)
   */
public static void writePositionToXML(@NotNull Mockup mockup) {
    NlComponent component = mockup.getComponent();
    if (component == null) {
        return;
    }
    final NlModel model = component.getModel();
    final WriteCommandAction action = new WriteCommandAction(model.getProject(), "Edit Mockup Crop", model.getFile()) {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            if (mockup.isFullScreen()) {
                component.removeAttribute(SdkConstants.TOOLS_URI, SdkConstants.ATTR_MOCKUP_CROP);
            } else {
                final String cropping = getPositionString(mockup);
                component.setAttribute(SdkConstants.TOOLS_URI, SdkConstants.ATTR_MOCKUP_CROP, cropping);
            }
        }
    };
    action.execute();
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) NlComponent(com.android.tools.idea.uibuilder.model.NlComponent) NlModel(com.android.tools.idea.uibuilder.model.NlModel) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result)

Example 85 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class DragDropInteraction method moveTo.

private void moveTo(@SwingCoordinate int x, @SwingCoordinate int y, @InputEventMask final int modifiers, boolean commit) {
    myScreenView = myDesignSurface.getScreenView(x, y);
    if (myScreenView == null) {
        return;
    }
    myDesignSurface.getLayeredPane().scrollRectToVisible(new Rectangle(x - NlConstants.DEFAULT_SCREEN_OFFSET_X, y - NlConstants.DEFAULT_SCREEN_OFFSET_Y, 2 * NlConstants.DEFAULT_SCREEN_OFFSET_X, 2 * NlConstants.DEFAULT_SCREEN_OFFSET_Y));
    final int ax = Coordinates.getAndroidX(myScreenView, x);
    final int ay = Coordinates.getAndroidY(myScreenView, y);
    Project project = myScreenView.getModel().getProject();
    ViewGroupHandler handler = findViewGroupHandlerAt(ax, ay);
    if (handler != myCurrentHandler) {
        if (myDragHandler != null) {
            myDragHandler.cancel();
            myDragHandler = null;
            myScreenView.getSurface().repaint();
        }
        myCurrentHandler = handler;
        if (myCurrentHandler != null) {
            assert myDragReceiver != null;
            String error = null;
            ViewHandlerManager viewHandlerManager = ViewHandlerManager.get(project);
            for (NlComponent component : myDraggedComponents) {
                if (!myCurrentHandler.acceptsChild(myDragReceiver, component, ax, ay)) {
                    error = String.format("<%1$s> does not accept <%2$s> as a child", myDragReceiver.getTagName(), component.getTagName());
                    break;
                }
                ViewHandler viewHandler = viewHandlerManager.getHandler(component);
                if (viewHandler != null && !viewHandler.acceptsParent(myDragReceiver, component)) {
                    error = String.format("<%1$s> does not accept <%2$s> as a parent", component.getTagName(), myDragReceiver.getTagName());
                    break;
                }
            }
            if (error == null) {
                myDragHandler = myCurrentHandler.createDragHandler(new ViewEditorImpl(myScreenView), myDragReceiver, myDraggedComponents, myType);
                if (myDragHandler != null) {
                    myDragHandler.start(Coordinates.getAndroidX(myScreenView, myStartX), Coordinates.getAndroidY(myScreenView, myStartY), myStartMask);
                }
            } else {
                myCurrentHandler = null;
            }
        }
    }
    if (myDragHandler != null && myCurrentHandler != null) {
        String error = myDragHandler.update(ax, ay, modifiers);
        final List<NlComponent> added = Lists.newArrayList();
        if (commit && error == null) {
            added.addAll(myDraggedComponents);
            final NlModel model = myScreenView.getModel();
            XmlFile file = model.getFile();
            String label = myType.getDescription();
            WriteCommandAction action = new WriteCommandAction(project, label, file) {

                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    InsertType insertType = model.determineInsertType(myType, myTransferItem, false);
                    // TODO: Run this *after* making a copy
                    myDragHandler.commit(ax, ay, modifiers, insertType);
                }
            };
            action.execute();
            model.notifyModified(NlModel.ChangeType.DND_COMMIT);
            // Select newly dropped components
            model.getSelectionModel().setSelection(added);
        }
        myScreenView.getSurface().repaint();
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) XmlFile(com.intellij.psi.xml.XmlFile) ViewHandlerManager(com.android.tools.idea.uibuilder.handlers.ViewHandlerManager) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) Project(com.intellij.openapi.project.Project) ViewEditorImpl(com.android.tools.idea.uibuilder.handlers.ViewEditorImpl)

Aggregations

WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)176 Result (com.intellij.openapi.application.Result)175 NotNull (org.jetbrains.annotations.NotNull)62 Project (com.intellij.openapi.project.Project)45 VirtualFile (com.intellij.openapi.vfs.VirtualFile)29 XmlFile (com.intellij.psi.xml.XmlFile)28 XmlTag (com.intellij.psi.xml.XmlTag)23 Document (com.intellij.openapi.editor.Document)22 PsiFile (com.intellij.psi.PsiFile)16 Module (com.intellij.openapi.module.Module)14 Nullable (org.jetbrains.annotations.Nullable)12 NlModel (com.android.tools.idea.uibuilder.model.NlModel)11 AttributesTransaction (com.android.tools.idea.uibuilder.model.AttributesTransaction)10 Editor (com.intellij.openapi.editor.Editor)10 TextRange (com.intellij.openapi.util.TextRange)8 XmlAttribute (com.intellij.psi.xml.XmlAttribute)8 File (java.io.File)8 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8 GradleBuildModel (com.android.tools.idea.gradle.dsl.model.GradleBuildModel)7