update copyright
[fedora-idea.git] / java / java-impl / src / com / intellij / codeInsight / generation / surroundWith / JavaWithSynchronizedSurrounder.java
blobb2fcf1554ebebf8efdd4e1af6db9feaefa2c2cae
2 /*
3 * Copyright 2000-2009 JetBrains s.r.o.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package com.intellij.codeInsight.generation.surroundWith;
19 import com.intellij.codeInsight.CodeInsightBundle;
20 import com.intellij.codeInsight.CodeInsightUtilBase;
21 import com.intellij.openapi.editor.Editor;
22 import com.intellij.openapi.project.Project;
23 import com.intellij.openapi.util.TextRange;
24 import com.intellij.psi.*;
25 import com.intellij.psi.codeStyle.CodeStyleManager;
26 import com.intellij.util.IncorrectOperationException;
27 import org.jetbrains.annotations.NonNls;
29 class JavaWithSynchronizedSurrounder extends JavaStatementsSurrounder{
30 public String getTemplateDescription() {
31 return CodeInsightBundle.message("surround.with.synchronized.template");
34 public TextRange surroundStatements(Project project, Editor editor, PsiElement container, PsiElement[] statements) throws IncorrectOperationException{
35 PsiManager manager = PsiManager.getInstance(project);
36 PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
37 CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
39 statements = SurroundWithUtil.moveDeclarationsOut(container, statements, false);
40 if (statements.length == 0){
41 return null;
44 @NonNls String text = "synchronized(a){\n}";
45 PsiSynchronizedStatement synchronizedStatement = (PsiSynchronizedStatement)factory.createStatementFromText(text, null);
46 synchronizedStatement = (PsiSynchronizedStatement)codeStyleManager.reformat(synchronizedStatement);
48 synchronizedStatement = (PsiSynchronizedStatement)container.addAfter(synchronizedStatement, statements[statements.length - 1]);
50 PsiCodeBlock synchronizedBlock = synchronizedStatement.getBody();
51 synchronizedBlock.addRange(statements[0], statements[statements.length - 1]);
52 container.deleteChildRange(statements[0], statements[statements.length - 1]);
54 synchronizedStatement = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(synchronizedStatement);
55 TextRange range = synchronizedStatement.getLockExpression().getTextRange();
56 editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
57 return new TextRange(range.getStartOffset(), range.getStartOffset());