Tidy up code samples and wrap at 80 chars #IJSDK-24

This commit is contained in:
Breandan Considine 2016-03-21 16:08:47 -04:00
parent 8aaf13b046
commit f416f02ce2
127 changed files with 2659 additions and 2528 deletions

View File

@ -3,9 +3,9 @@
<description>Inspection for (probably) inappropriate use of equality relation operation.</description>
<version>1.0</version>
<vendor>JetBrains</vendor>
<!--
<idea-version since-build="3000"/>
-->
<!--
<idea-version since-build="3000"/>
-->
<extensions defaultExtensionNs="com.intellij">
<inspectionToolProvider implementation="com.intellij.codeInspection.ComparingReferencesProvider"/>

View File

@ -3,7 +3,6 @@ package com.intellij.codeInspection;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.ui.DocumentAdapter;
@ -14,8 +13,6 @@ import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
@ -26,13 +23,17 @@ public class ComparingReferencesInspection extends BaseJavaLocalInspectionTool {
private final LocalQuickFix myQuickFix = new MyQuickFix();
@SuppressWarnings({"WeakerAccess"}) @NonNls public String CHECKED_CLASSES = "java.lang.String;java.util.Date";
@NonNls private static final String DESCRIPTION_TEMPLATE = InspectionsBundle.message("inspection.comparing.references.problem.descriptor");
@SuppressWarnings({"WeakerAccess"})
@NonNls
public String CHECKED_CLASSES = "java.lang.String;java.util.Date";
@NonNls
private static final String DESCRIPTION_TEMPLATE =
InspectionsBundle.message("inspection.comparing.references.problem.descriptor");
@NotNull
public String getDisplayName() {
return "'==' or '!=' instead of 'equals()'";
return "'==' or '!=' instead of 'equals()'";
}
@NotNull
@ -57,32 +58,33 @@ public class ComparingReferencesInspection extends BaseJavaLocalInspectionTool {
return false;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitReferenceExpression(PsiReferenceExpression psiReferenceExpression) {
}
@Override
public void visitReferenceExpression(PsiReferenceExpression psiReferenceExpression) {
}
@Override public void visitBinaryExpression(PsiBinaryExpression expression) {
super.visitBinaryExpression(expression);
@Override
public void visitBinaryExpression(PsiBinaryExpression expression) {
super.visitBinaryExpression(expression);
IElementType opSign = expression.getOperationTokenType();
if (opSign == JavaTokenType.EQEQ || opSign == JavaTokenType.NE) {
PsiExpression lOperand = expression.getLOperand();
PsiExpression rOperand = expression.getROperand();
if (rOperand == null || isNullLiteral(lOperand) || isNullLiteral(rOperand)) return;
if (opSign == JavaTokenType.EQEQ || opSign == JavaTokenType.NE) {
PsiExpression lOperand = expression.getLOperand();
PsiExpression rOperand = expression.getROperand();
if (rOperand == null || isNullLiteral(lOperand) || isNullLiteral(rOperand)) return;
PsiType lType = lOperand.getType();
PsiType rType = rOperand.getType();
PsiType lType = lOperand.getType();
PsiType rType = rOperand.getType();
if (isCheckedType(lType) || isCheckedType(rType)) {
holder.registerProblem(expression,
DESCRIPTION_TEMPLATE, myQuickFix);
}
if (isCheckedType(lType) || isCheckedType(rType)) {
holder.registerProblem(expression,
DESCRIPTION_TEMPLATE, myQuickFix);
}
}
}
};
}
@ -94,14 +96,14 @@ public class ComparingReferencesInspection extends BaseJavaLocalInspectionTool {
private static class MyQuickFix implements LocalQuickFix {
@NotNull
public String getName() {
// The test (see the TestThisPlugin class) uses this string to identify the quick fix action.
// The test (see the TestThisPlugin class) uses this string to identify the quick fix action.
return InspectionsBundle.message("inspection.comparing.references.use.quickfix");
}
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
try {
PsiBinaryExpression binaryExpression = (PsiBinaryExpression)descriptor.getPsiElement();
PsiBinaryExpression binaryExpression = (PsiBinaryExpression) descriptor.getPsiElement();
IElementType opSign = binaryExpression.getOperationTokenType();
PsiExpression lExpr = binaryExpression.getLOperand();
PsiExpression rExpr = binaryExpression.getROperand();
@ -109,20 +111,20 @@ public class ComparingReferencesInspection extends BaseJavaLocalInspectionTool {
return;
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
PsiMethodCallExpression equalsCall = (PsiMethodCallExpression)factory.createExpressionFromText("a.equals(b)", null);
PsiMethodCallExpression equalsCall =
(PsiMethodCallExpression) factory.createExpressionFromText("a.equals(b)", null);
equalsCall.getMethodExpression().getQualifierExpression().replace(lExpr);
equalsCall.getArgumentList().getExpressions()[0].replace(rExpr);
PsiExpression result = (PsiExpression)binaryExpression.replace(equalsCall);
PsiExpression result = (PsiExpression) binaryExpression.replace(equalsCall);
if (opSign == JavaTokenType.NE) {
PsiPrefixExpression negation = (PsiPrefixExpression)factory.createExpressionFromText("!a", null);
PsiPrefixExpression negation = (PsiPrefixExpression) factory.createExpressionFromText("!a", null);
negation.getOperand().replace(result);
result.replace(negation);
}
}
catch (IncorrectOperationException e) {
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}

View File

@ -5,6 +5,6 @@ package com.intellij.codeInspection;
*/
public class ComparingReferencesProvider implements InspectionToolProvider {
public Class[] getInspectionClasses() {
return new Class[] { ComparingReferencesInspection.class};
return new Class[]{ComparingReferencesInspection.class};
}
}

View File

@ -17,51 +17,52 @@ import java.util.List;
*/
public class TestThisPlugin extends UsefulTestCase {
protected CodeInsightTestFixture myFixture;
// Specify path to your test data directory
// e.g. final String dataPath = "c:\\users\\john.doe\\idea\\community\\samples\\ComparingReferences/testData";
final String dataPath = "c:\\users\\John.Doe\\idea\\community\\samples\\comparingReferences/testData";
protected CodeInsightTestFixture myFixture;
// Specify path to your test data directory
// e.g. final String dataPath = "c:\\users\\john.doe\\idea\\community\\samples\\ComparingReferences/testData";
final String dataPath = "c:\\users\\John.Doe\\idea\\community\\samples\\comparingReferences/testData";
public void setUp() throws Exception {
public void setUp() throws Exception {
final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = fixtureFactory.createFixtureBuilder(getName());
myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(testFixtureBuilder.getFixture());
myFixture.setTestDataPath(dataPath);
final JavaModuleFixtureBuilder builder = testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class);
final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder =
fixtureFactory.createFixtureBuilder(getName());
myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(testFixtureBuilder.getFixture());
myFixture.setTestDataPath(dataPath);
final JavaModuleFixtureBuilder builder = testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class);
builder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot("");
builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15);
myFixture.setUp();
}
builder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot("");
builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15);
myFixture.setUp();
}
public void tearDown() throws Exception {
myFixture.tearDown();
myFixture = null;
}
public void tearDown() throws Exception {
myFixture.tearDown();
myFixture = null;
}
protected void doTest(String testName, String hint) throws Throwable {
myFixture.configureByFile(testName + ".java");
myFixture.enableInspections(ComparingReferencesInspection.class);
List<HighlightInfo> highlightInfos = myFixture.doHighlighting();
Assert.assertTrue(!highlightInfos.isEmpty());
protected void doTest(String testName, String hint) throws Throwable {
myFixture.configureByFile(testName + ".java");
myFixture.enableInspections(ComparingReferencesInspection.class);
List<HighlightInfo> highlightInfos = myFixture.doHighlighting();
Assert.assertTrue(!highlightInfos.isEmpty());
final IntentionAction action = myFixture.findSingleIntention(hint);
final IntentionAction action = myFixture.findSingleIntention(hint);
Assert.assertNotNull(action);
myFixture.launchAction(action);
myFixture.checkResultByFile(testName + ".after.java");
}
Assert.assertNotNull(action);
myFixture.launchAction(action);
myFixture.checkResultByFile(testName + ".after.java");
}
// Test the "==" case
public void test() throws Throwable {
doTest("before", "Use equals()");
}
// Test the "==" case
public void test() throws Throwable {
doTest("before", "Use equals()");
}
// Test the "!=" case
public void test1() throws Throwable {
doTest("before1", "Use equals()");
}
// Test the "!=" case
public void test1() throws Throwable {
doTest("before1", "Use equals()");
}
}

View File

@ -1,27 +1,27 @@
<idea-plugin version="2">
<name>Conditional Operator Converter</name>
<id>ConditionalOperatorConverter</id>
<description>Intention action that suggests to convert a conditional operator into
'if' block.
</description>
<version>1.3</version>
<vendor>JetBrains</vendor>
<!--
<idea-version since-build="2000"/>
-->
<name>Conditional Operator Converter</name>
<id>ConditionalOperatorConverter</id>
<description>Intention action that suggests to convert a conditional operator into
'if' block.
</description>
<version>1.3</version>
<vendor>JetBrains</vendor>
<!--
<idea-version since-build="2000"/>
-->
<extensions defaultExtensionNs="com.intellij">
<intentionAction>
<className>com.intellij.codeInsight.intention.ConditionalOperatorConvertor</className>
<category>Conditional Operator</category>
<descriptionDirectoryName>ConditionalOperatorConvertor</descriptionDirectoryName>
<extensions defaultExtensionNs="com.intellij">
<intentionAction>
<className>com.intellij.codeInsight.intention.ConditionalOperatorConvertor</className>
<category>Conditional Operator</category>
<descriptionDirectoryName>ConditionalOperatorConvertor</descriptionDirectoryName>
</intentionAction>
</extensions>
</intentionAction>
</extensions>
<project-components>
<component>
<implementation-class>com.intellij.codeInsight.intention.ConditionalOperatorConvertor</implementation-class>
</component>
</project-components>
<project-components>
<component>
<implementation-class>com.intellij.codeInsight.intention.ConditionalOperatorConvertor</implementation-class>
</component>
</project-components>
</idea-plugin>

View File

@ -13,7 +13,8 @@ import org.jetbrains.annotations.Nullable;
/**
* @author dsl
*/
@NonNls public class ConditionalOperatorConvertor extends PsiElementBaseIntentionAction implements IntentionAction {
@NonNls
public class ConditionalOperatorConvertor extends PsiElementBaseIntentionAction implements IntentionAction {
@NotNull
public String getText() {
@ -30,10 +31,10 @@ import org.jetbrains.annotations.Nullable;
if (!element.isWritable()) return false;
if (element instanceof PsiJavaToken) {
final PsiJavaToken token = (PsiJavaToken)element;
final PsiJavaToken token = (PsiJavaToken) element;
if (token.getTokenType() != JavaTokenType.QUEST) return false;
if (token.getParent() instanceof PsiConditionalExpression) {
final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)token.getParent();
final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression) token.getParent();
if (conditionalExpression.getThenExpression() == null
|| conditionalExpression.getElseExpression() == null) {
return false;
@ -63,12 +64,13 @@ import org.jetbrains.annotations.Nullable;
// Maintain declrations
if (originalStatement instanceof PsiDeclarationStatement) {
final PsiDeclarationStatement declaration = (PsiDeclarationStatement)originalStatement;
final PsiDeclarationStatement declaration = (PsiDeclarationStatement) originalStatement;
final PsiElement[] declaredElements = declaration.getDeclaredElements();
PsiLocalVariable variable = null;
for (PsiElement declaredElement : declaredElements) {
if (declaredElement instanceof PsiLocalVariable && PsiTreeUtil.isAncestor(declaredElement, conditionalExpression, true)) {
variable = (PsiLocalVariable)declaredElement;
if (declaredElement instanceof PsiLocalVariable &&
PsiTreeUtil.isAncestor(declaredElement, conditionalExpression, true)) {
variable = (PsiLocalVariable) declaredElement;
break;
}
}
@ -77,31 +79,31 @@ import org.jetbrains.annotations.Nullable;
final Object marker = new Object();
PsiTreeUtil.mark(conditionalExpression, marker);
PsiExpressionStatement statement =
(PsiExpressionStatement)factory.createStatementFromText(variable.getName() + " = 0;", null);
statement = (PsiExpressionStatement)CodeStyleManager.getInstance(project).reformat(statement);
((PsiAssignmentExpression)statement.getExpression()).getRExpression().replace(variable.getInitializer());
(PsiExpressionStatement) factory.createStatementFromText(variable.getName() + " = 0;", null);
statement = (PsiExpressionStatement) CodeStyleManager.getInstance(project).reformat(statement);
((PsiAssignmentExpression) statement.getExpression()).getRExpression().replace(variable.getInitializer());
variable.getInitializer().delete();
final PsiElement variableParent = variable.getParent();
originalStatement = variableParent.getParent().addAfter(statement, variableParent);
conditionalExpression = (PsiConditionalExpression)PsiTreeUtil.releaseMark(originalStatement, marker);
conditionalExpression = (PsiConditionalExpression) PsiTreeUtil.releaseMark(originalStatement, marker);
}
// create then and else branches
final PsiElement[] originalElements = new PsiElement[]{originalStatement, conditionalExpression};
final PsiExpression condition = (PsiExpression)conditionalExpression.getCondition().copy();
final PsiExpression condition = (PsiExpression) conditionalExpression.getCondition().copy();
final PsiElement[] thenElements = PsiTreeUtil.copyElements(originalElements);
final PsiElement[] elseElements = PsiTreeUtil.copyElements(originalElements);
thenElements[1].replace(conditionalExpression.getThenExpression());
elseElements[1].replace(conditionalExpression.getElseExpression());
PsiIfStatement statement = (PsiIfStatement)factory.createStatementFromText("if (true) { a = b } else { c = d }",
null);
statement = (PsiIfStatement)CodeStyleManager.getInstance(project).reformat(statement);
PsiIfStatement statement = (PsiIfStatement) factory.createStatementFromText("if (true) { a = b } else { c = d }",
null);
statement = (PsiIfStatement) CodeStyleManager.getInstance(project).reformat(statement);
statement.getCondition().replace(condition);
statement = (PsiIfStatement)originalStatement.replace(statement);
statement = (PsiIfStatement) originalStatement.replace(statement);
((PsiBlockStatement)statement.getThenBranch()).getCodeBlock().getStatements()[0].replace(thenElements[0]);
((PsiBlockStatement)statement.getElseBranch()).getCodeBlock().getStatements()[0].replace(elseElements[0]);
((PsiBlockStatement) statement.getThenBranch()).getCodeBlock().getStatements()[0].replace(thenElements[0]);
((PsiBlockStatement) statement.getElseBranch()).getCodeBlock().getStatements()[0].replace(elseElements[0]);
}
public boolean startInWriteAction() {

View File

@ -1,5 +1,5 @@
<html>
<body>
This intention converts a ternary operator to a corresponding if statement. <br>
This intention converts a ternary operator to a corresponding if statement. <br>
</body>
</html>

View File

@ -1,11 +1,11 @@
public class X {
void f(boolean isMale) {
String title;
if (isMale) {
title = "Mr.";
} else {
title = "Ms.";
}
System.out.println("title = " + title);
}
if (isMale) {
title = "Mr.";
} else {
title = "Ms.";
}
System.out.println("title = " + title);
}
}

View File

@ -1,6 +1,6 @@
public class X {
void f(boolean isMale) {
String title = isMale <caret>? "Mr." : "Ms.";
String title = isMale < caret > ? "Mr." : "Ms.";
System.out.println("title = " + title);
}
}
}

View File

@ -1,7 +1,6 @@
package testPlugin;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.*;
import junit.framework.Assert;
@ -18,45 +17,46 @@ import org.junit.Test;
*/
public class YourTest {
protected CodeInsightTestFixture myFixture;
// Specify path to your test data
// e.g. final String dataPath = "c:\\users\\john.doe\\idea\\community\\samples\\conditionalOperatorConvertor/testData";
final String dataPath = "c:\\users\\John.Doe\\idea\\community\\samples\\conditionalOperatorConvertor/testData";
protected CodeInsightTestFixture myFixture;
// Specify path to your test data
// e.g. final String dataPath = "c:\\users\\john
// .doe\\idea\\community\\samples\\conditionalOperatorConvertor/testData";
final String dataPath = "c:\\users\\John.Doe\\idea\\community\\samples\\conditionalOperatorConvertor/testData";
@Before
@Before
public void setUp() throws Exception {
public void setUp() throws Exception {
final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = fixtureFactory.createFixtureBuilder();
myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(testFixtureBuilder.getFixture());
myFixture.setTestDataPath(dataPath);
final JavaModuleFixtureBuilder builder = testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class);
final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = fixtureFactory.createFixtureBuilder();
myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(testFixtureBuilder.getFixture());
myFixture.setTestDataPath(dataPath);
final JavaModuleFixtureBuilder builder = testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class);
builder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot("");
builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15);
myFixture.setUp();
builder.addContentRoot(myFixture.getTempDirPath()).addSourceRoot("");
builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15);
myFixture.setUp();
}
}
@After
public void tearDown() throws Exception {
myFixture.tearDown();
myFixture = null;
}
@After
public void tearDown() throws Exception {
myFixture.tearDown();
myFixture = null;
}
protected void doTest(String testName, String hint) throws Throwable {
// Messages.showInfoMessage("Test started", "Info");
myFixture.configureByFile(testName + ".java");
final IntentionAction action = myFixture.findSingleIntention(hint);
Assert.assertNotNull(action);
myFixture.launchAction(action);
myFixture.checkResultByFile(testName + ".after.java");
}
protected void doTest(String testName, String hint) throws Throwable {
// Messages.showInfoMessage("Test started", "Info");
myFixture.configureByFile(testName + ".java");
final IntentionAction action = myFixture.findSingleIntention(hint);
Assert.assertNotNull(action);
myFixture.launchAction(action);
myFixture.checkResultByFile(testName + ".after.java");
}
@Test
public void test() throws Throwable {
doTest("before.template", "Convert ternary operator to if statement");
}
@Test
public void test() throws Throwable {
doTest("before.template", "Convert ternary operator to if statement");
}
}

View File

@ -25,15 +25,21 @@
</project-components>
<actions>
<action id="EditorBasics.EditorIllustration" class="org.jetbrains.tutorials.editor.basics.EditorIllustration" text="Editor Basics"
description="Illustrates how to plug an action in">
<add-to-group group-id="EditorPopupMenu" anchor="first"/>
</action>
<action id="EditorBasics.EditorHandlerIllustration" class="org.jetbrains.tutorials.editor.basics.EditorHandlerIllustration" text="Editor Handler"
<action id="EditorBasics.EditorIllustration"
class="org.jetbrains.tutorials.editor.basics.EditorIllustration"
text="Editor Basics"
description="Illustrates how to plug an action in">
<add-to-group group-id="EditorPopupMenu" anchor="first"/>
</action>
<action id="EditorBasics.LogicalPositionIllustration" class="org.jetbrains.tutorials.editor.basics.EditorAreaIllustration" text="Caret Position"
<action id="EditorBasics.EditorHandlerIllustration"
class="org.jetbrains.tutorials.editor.basics.EditorHandlerIllustration"
text="Editor Handler"
description="Illustrates how to plug an action in">
<add-to-group group-id="EditorPopupMenu" anchor="first"/>
</action>
<action id="EditorBasics.LogicalPositionIllustration"
class="org.jetbrains.tutorials.editor.basics.EditorAreaIllustration"
text="Caret Position"
description="Illustrates how editor area is organized">
<add-to-group group-id="EditorPopupMenu" anchor="first"/>
</action>

View File

@ -3,7 +3,10 @@ package org.jetbrains.tutorials.editor.basics;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
@ -11,22 +14,22 @@ import com.intellij.openapi.ui.Messages;
* @author Anna Bulenkova
*/
public class EditorAreaIllustration extends AnAction {
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
CaretModel caretModel = editor.getCaretModel();
LogicalPosition logicalPosition = caretModel.getLogicalPosition();
VisualPosition visualPosition = caretModel.getVisualPosition();
int offset = caretModel.getOffset();
Messages.showInfoMessage(logicalPosition.toString() + "\n" +
visualPosition.toString() + "\n" +
"Offset: " + offset, "Caret Parameters Inside The Editor");
}
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
CaretModel caretModel = editor.getCaretModel();
LogicalPosition logicalPosition = caretModel.getLogicalPosition();
VisualPosition visualPosition = caretModel.getVisualPosition();
int offset = caretModel.getOffset();
Messages.showInfoMessage(logicalPosition.toString() + "\n" +
visualPosition.toString() + "\n" +
"Offset: " + offset, "Caret Parameters Inside The Editor");
}
@Override
public void update(AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT);
final Editor editor = e.getData(CommonDataKeys.EDITOR);
e.getPresentation().setVisible(project != null && editor != null);
}
@Override
public void update(AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT);
final Editor editor = e.getData(CommonDataKeys.EDITOR);
e.getPresentation().setVisible(project != null && editor != null);
}
}

View File

@ -14,19 +14,21 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class EditorHandlerIllustration extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
EditorActionManager actionManager = EditorActionManager.getInstance();
//Insert one more caret below the active caret
EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_CLONE_CARET_BELOW);
actionHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), anActionEvent.getDataContext());
}
@Override
public void update(@NotNull final AnActionEvent anActionEvent) {
//Set visible if at least one caret is available
final Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
final Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);
anActionEvent.getPresentation().setVisible((project != null && editor != null && !editor.getCaretModel().getAllCarets().isEmpty()));
}
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
EditorActionManager actionManager = EditorActionManager.getInstance();
//Insert one more caret below the active caret
EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_CLONE_CARET_BELOW);
actionHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), anActionEvent.getDataContext());
}
@Override
public void update(@NotNull final AnActionEvent anActionEvent) {
//Set visible if at least one caret is available
final Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
final Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);
anActionEvent.getPresentation()
.setVisible((project != null && editor != null && !editor.getCaretModel().getAllCarets().isEmpty()));
}
}

View File

@ -16,40 +16,41 @@ import com.intellij.openapi.project.Project;
*/
public class EditorIllustration extends AnAction {
static {
final EditorActionManager actionManager = EditorActionManager.getInstance();
final TypedAction typedAction = actionManager.getTypedAction();
typedAction.setupHandler(new MyTypedHandler());
}
static {
final EditorActionManager actionManager = EditorActionManager.getInstance();
final TypedAction typedAction = actionManager.getTypedAction();
typedAction.setupHandler(new MyTypedHandler());
}
@Override
public void actionPerformed(final AnActionEvent anActionEvent) {
//Get all the required data from data keys
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT);
//Access document, caret, and selection
final Document document = editor.getDocument();
final SelectionModel selectionModel = editor.getSelectionModel();
@Override
public void actionPerformed(final AnActionEvent anActionEvent) {
//Get all the required data from data keys
final Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT);
//Access document, caret, and selection
final Document document = editor.getDocument();
final SelectionModel selectionModel = editor.getSelectionModel();
final int start = selectionModel.getSelectionStart();
final int end = selectionModel.getSelectionEnd();
//New instance of Runnable to make a replacement
Runnable runnable = new Runnable() {
@Override
public void run() {
document.replaceString(start, end, "Replacement");
}
};
//Making the replacement
WriteCommandAction.runWriteCommandAction(project, runnable);
selectionModel.removeSelection();
}
@Override
public void update(final AnActionEvent e) {
//Get required data keys
final Project project = e.getData(CommonDataKeys.PROJECT);
final Editor editor = e.getData(CommonDataKeys.EDITOR);
//Set visibility only in case of existing project and editor and if some text in the editor is selected
e.getPresentation().setVisible((project != null && editor != null && editor.getSelectionModel().hasSelection()));
}
final int start = selectionModel.getSelectionStart();
final int end = selectionModel.getSelectionEnd();
//New instance of Runnable to make a replacement
Runnable runnable = new Runnable() {
@Override
public void run() {
document.replaceString(start, end, "Replacement");
}
};
//Making the replacement
WriteCommandAction.runWriteCommandAction(project, runnable);
selectionModel.removeSelection();
}
@Override
public void update(final AnActionEvent e) {
//Get required data keys
final Project project = e.getData(CommonDataKeys.PROJECT);
final Editor editor = e.getData(CommonDataKeys.EDITOR);
//Set visibility only in case of existing project and editor and if some text in the editor is selected
e.getPresentation().setVisible((project != null && editor != null && editor.getSelectionModel().hasSelection()));
}
}

View File

@ -12,16 +12,16 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class MyTypedHandler implements TypedActionHandler {
@Override
public void execute(@NotNull Editor editor, char c, @NotNull DataContext dataContext) {
final Document document = editor.getDocument();
Project project = editor.getProject();
Runnable runnable = new Runnable() {
@Override
public void run() {
document.insertString(0, "Typed\n");
}
};
WriteCommandAction.runWriteCommandAction(project, runnable);
}
@Override
public void execute(@NotNull Editor editor, char c, @NotNull DataContext dataContext) {
final Document document = editor.getDocument();
Project project = editor.getProject();
Runnable runnable = new Runnable() {
@Override
public void run() {
document.insertString(0, "Typed\n");
}
};
WriteCommandAction.runWriteCommandAction(project, runnable);
}
}

View File

@ -1,36 +1,36 @@
<idea-plugin version="2">
<id>com.intellij.tutorials.facet</id>
<name>Facet Demo</name>
<version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.yourcompany.com">JetBrains</vendor>
<id>com.intellij.tutorials.facet</id>
<name>Facet Demo</name>
<version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.yourcompany.com">JetBrains</vendor>
<description>Basic example of working with facets</description>
<description>Basic example of working with facets</description>
<change-notes>Initial commit</change-notes>
<change-notes>Initial commit</change-notes>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products -->
<!-- uncomment to enable plugin in all products
<depends>com.intellij.modules.lang</depends>
-->
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products -->
<!-- uncomment to enable plugin in all products
<depends>com.intellij.modules.lang</depends>
-->
<extensions defaultExtensionNs="com.intellij">
<facetType implementation="com.intellij.tutorials.facet.DemoFacetType"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<facetType implementation="com.intellij.tutorials.facet.DemoFacetType"/>
</extensions>
<application-components>
<!-- Add your application components here -->
</application-components>
<application-components>
<!-- Add your application components here -->
</application-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<actions>
<!-- Add your actions here -->
</actions>
<actions>
<!-- Add your actions here -->
</actions>
</idea-plugin>

View File

@ -8,9 +8,13 @@ import com.intellij.openapi.module.Module;
* @author Anna Bulenkova
*/
public class DemoFacet extends Facet<DemoFacetConfiguration> {
public static final String ID = "DEMO_FACET_ID";
public static final String ID = "DEMO_FACET_ID";
public DemoFacet(FacetType facetType, Module module, String name, DemoFacetConfiguration configuration, Facet underlyingFacet) {
super(facetType, module, name, configuration, underlyingFacet);
}
public DemoFacet(FacetType facetType,
Module module,
String name,
DemoFacetConfiguration configuration,
Facet underlyingFacet) {
super(facetType, module, name, configuration, underlyingFacet);
}
}

View File

@ -17,63 +17,64 @@ import java.awt.*;
* @author Anna Bulenkova
*/
public class DemoFacetConfiguration implements FacetConfiguration {
public static final String DEMO_FACET_TAG_NAME = "DemoFacet";
public static final String PATH_TO_SDK_ATTR_NAME = "pathToSdk";
private String myPathToSdk = "";
JTextField myPath = new JTextField(myPathToSdk);
@Override
public FacetEditorTab[] createEditorTabs(FacetEditorContext context, FacetValidatorsManager manager) {
return new FacetEditorTab[] {
new FacetEditorTab() {
public static final String DEMO_FACET_TAG_NAME = "DemoFacet";
public static final String PATH_TO_SDK_ATTR_NAME = "pathToSdk";
private String myPathToSdk = "";
JTextField myPath = new JTextField(myPathToSdk);
@NotNull
@Override
public JComponent createComponent() {
JPanel top = new JPanel(new BorderLayout());
top.add(new JLabel("Path to SDK: "), BorderLayout.WEST);
top.add(myPath);
JPanel panel = new JPanel(new BorderLayout());
panel.add(top, BorderLayout.NORTH);
return panel;
}
@Override
public FacetEditorTab[] createEditorTabs(FacetEditorContext context, FacetValidatorsManager manager) {
return new FacetEditorTab[]{
new FacetEditorTab() {
@Nls
@Override
public String getDisplayName() {
return "Demo Framework";
}
@NotNull
@Override
public JComponent createComponent() {
JPanel top = new JPanel(new BorderLayout());
top.add(new JLabel("Path to SDK: "), BorderLayout.WEST);
top.add(myPath);
JPanel panel = new JPanel(new BorderLayout());
panel.add(top, BorderLayout.NORTH);
return panel;
}
@Override
public boolean isModified() {
return myPath.getText().equalsIgnoreCase(myPathToSdk);
@Nls
@Override
public String getDisplayName() {
return "Demo Framework";
}
@Override
public boolean isModified() {
return myPath.getText().equalsIgnoreCase(myPathToSdk);
// return !StringUtil.equalsIgnoreWhitespaces(myPath.getText(), myPathToSdk);
}
}
@Override
public void reset() {
myPath.setText(myPathToSdk);
}
@Override
public void disposeUIResources() {
}
}
};
}
@Override
public void readExternal(Element element) throws InvalidDataException {
Element facet = element.getChild(DEMO_FACET_TAG_NAME);
if (facet != null) {
myPathToSdk = facet.getAttributeValue(PATH_TO_SDK_ATTR_NAME, "");
@Override
public void reset() {
myPath.setText(myPathToSdk);
}
}
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
Element facet = new Element(DEMO_FACET_TAG_NAME);
facet.setAttribute(PATH_TO_SDK_ATTR_NAME, myPathToSdk);
element.addContent(facet);
@Override
public void disposeUIResources() {
}
}
};
}
@Override
public void readExternal(Element element) throws InvalidDataException {
Element facet = element.getChild(DEMO_FACET_TAG_NAME);
if (facet != null) {
myPathToSdk = facet.getAttributeValue(PATH_TO_SDK_ATTR_NAME, "");
myPath.setText(myPathToSdk);
}
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
Element facet = new Element(DEMO_FACET_TAG_NAME);
facet.setAttribute(PATH_TO_SDK_ATTR_NAME, myPathToSdk);
element.addContent(facet);
}
}

View File

@ -15,29 +15,33 @@ import javax.swing.*;
* @author Anna Bulenkova
*/
public class DemoFacetType extends FacetType<DemoFacet, DemoFacetConfiguration> {
private static final FacetTypeId<DemoFacet> TYPE_ID = new FacetTypeId<DemoFacet>(DemoFacet.ID);
public DemoFacetType() {
super(TYPE_ID, DemoFacet.ID, "Demo Facet");
}
private static final FacetTypeId<DemoFacet> TYPE_ID = new FacetTypeId<DemoFacet>(DemoFacet.ID);
@Override
public DemoFacetConfiguration createDefaultConfiguration() {
return new DemoFacetConfiguration();
}
public DemoFacetType() {
super(TYPE_ID, DemoFacet.ID, "Demo Facet");
}
@Override
public DemoFacet createFacet(@NotNull Module module, String s, @NotNull DemoFacetConfiguration configuration, Facet facet) {
return new DemoFacet(this, module, s, configuration, facet);
}
@Override
public DemoFacetConfiguration createDefaultConfiguration() {
return new DemoFacetConfiguration();
}
@Override
public boolean isSuitableModuleType(ModuleType type) {
return true;
}
@Override
public DemoFacet createFacet(@NotNull Module module,
String s,
@NotNull DemoFacetConfiguration configuration,
Facet facet) {
return new DemoFacet(this, module, s, configuration, facet);
}
@Nullable
@Override
public Icon getIcon() {
return AllIcons.General.Information;
}
@Override
public boolean isSuitableModuleType(ModuleType type) {
return true;
}
@Nullable
@Override
public Icon getIcon() {
return AllIcons.General.Information;
}
}

View File

@ -18,54 +18,57 @@ import javax.swing.*;
* @author Anna Bulenkova
*/
public class DemoFramework extends FrameworkTypeEx {
public static final String FRAMEWORK_ID = "Demo";
protected DemoFramework() {
super(FRAMEWORK_ID);
}
public static final String FRAMEWORK_ID = "Demo";
@NotNull
@Override
public FrameworkSupportInModuleProvider createProvider() {
return new FrameworkSupportInModuleProvider() {
@NotNull
@Override
public FrameworkTypeEx getFrameworkType() {
return DemoFramework.this;
}
protected DemoFramework() {
super(FRAMEWORK_ID);
}
@NotNull
@Override
public FrameworkSupportInModuleConfigurable createConfigurable(@NotNull FrameworkSupportModel model) {
return new FrameworkSupportInModuleConfigurable() {
@Nullable
@Override
public JComponent createComponent() {
return new JCheckBox("Extra Option");
}
@NotNull
@Override
public FrameworkSupportInModuleProvider createProvider() {
return new FrameworkSupportInModuleProvider() {
@NotNull
@Override
public FrameworkTypeEx getFrameworkType() {
return DemoFramework.this;
}
@Override
public void addSupport(@NotNull Module module, @NotNull ModifiableRootModel model, @NotNull ModifiableModelsProvider provider) {
//do what you want here: setup a library, generate a specific file, etc
}
};
}
@NotNull
@Override
public FrameworkSupportInModuleConfigurable createConfigurable(@NotNull FrameworkSupportModel model) {
return new FrameworkSupportInModuleConfigurable() {
@Nullable
@Override
public JComponent createComponent() {
return new JCheckBox("Extra Option");
}
@Override
public boolean isEnabledForModuleType(@NotNull ModuleType type) {
return true;
}
@Override
public void addSupport(@NotNull Module module,
@NotNull ModifiableRootModel model,
@NotNull ModifiableModelsProvider provider) {
//do what you want here: setup a library, generate a specific file, etc
}
};
}
}
@NotNull
@Override
public String getPresentableName() {
return "Demo Framework";
}
@Override
public boolean isEnabledForModuleType(@NotNull ModuleType type) {
return true;
}
};
}
@NotNull
@Override
public Icon getIcon() {
return AllIcons.Providers.Apache;
}
@NotNull
@Override
public String getPresentableName() {
return "Demo Framework";
}
@NotNull
@Override
public Icon getIcon() {
return AllIcons.Providers.Apache;
}
}

View File

@ -27,5 +27,5 @@ group 'org.jetbrains'
version '0.0.1-SNAPSHOT'
repositories {
mavenCentral ()
mavenCentral()
}

View File

@ -8,12 +8,12 @@ import com.intellij.openapi.ui.Messages;
* Created by breandan on 11/25/2015.
*/
public class HelloAction extends AnAction {
public HelloAction() {
super("Hello");
}
public HelloAction() {
super("Hello");
}
public void actionPerformed(AnActionEvent event) {
Project project = event.getData(PlatformDataKeys.PROJECT);
Messages.showMessageDialog(project, "Hello world!", "Greeting", Messages.getInformationIcon());
}
public void actionPerformed(AnActionEvent event) {
Project project = event.getData(PlatformDataKeys.PROJECT);
Messages.showMessageDialog(project, "Hello world!", "Greeting", Messages.getInformationIcon());
}
}

View File

@ -33,8 +33,8 @@
<actions>
<group id="MyPlugin.SampleMenu" text="Greeting" description="Greeting menu">
<add-to-group group-id="MainMenu" anchor="last" />
<action id="Myplugin.Textboxes" class="HelloAction" text="Hello" description="Says hello" />
<add-to-group group-id="MainMenu" anchor="last"/>
<action id="Myplugin.Textboxes" class="HelloAction" text="Hello" description="Says hello"/>
</group>
</actions>

View File

@ -1,30 +1,30 @@
<idea-plugin version="2">
<id>com.intellij.tutorials.inspection</id>
<name>Inspection Demo</name>
<version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<id>com.intellij.tutorials.inspection</id>
<name>Inspection Demo</name>
<version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Basic example of working with code inspections</description>
<description>Basic example of working with code inspections</description>
<change-notes>Initial commit</change-notes>
<change-notes>Initial commit</change-notes>
<idea-version since-build="131"/>
<idea-version since-build="131"/>
<extensions defaultExtensionNs="com.intellij">
<inspectionToolProvider implementation="com.intellij.tutorials.inspection.DemoInspectionToolProvider"/>
<extensions defaultExtensionNs="com.intellij">
<inspectionToolProvider implementation="com.intellij.tutorials.inspection.DemoInspectionToolProvider"/>
</extensions>
</extensions>
<application-components>
<!-- Add your application components here -->
</application-components>
<application-components>
<!-- Add your application components here -->
</application-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<actions>
<!-- Add your actions here -->
</actions>
<actions>
<!-- Add your actions here -->
</actions>
</idea-plugin>

View File

@ -9,16 +9,16 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class DemoCodeInspection extends LocalInspectionTool {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "Demo Inspection";
}
@Nls
@NotNull
@Override
public String getDisplayName() {
return "Demo Inspection";
}
@NotNull
@Override
public DemoInspectionVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new DemoInspectionVisitor();
}
@NotNull
@Override
public DemoInspectionVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new DemoInspectionVisitor();
}
}

View File

@ -6,7 +6,7 @@ import com.intellij.codeInspection.InspectionToolProvider;
* @author Anna Bulenkova
*/
public class DemoInspectionToolProvider implements InspectionToolProvider {
public Class[] getInspectionClasses() {
return new Class[] { DemoCodeInspection.class};
}
public Class[] getInspectionClasses() {
return new Class[]{DemoCodeInspection.class};
}
}

View File

@ -8,13 +8,13 @@ import com.intellij.psi.PsiPlainTextFile;
* @author Anna Bulenkova
*/
public class DemoInspectionVisitor extends PsiElementVisitor {
@Override
public void visitElement(PsiElement element) {
super.visitElement(element);
}
@Override
public void visitElement(PsiElement element) {
super.visitElement(element);
}
@Override
public void visitPlainTextFile(PsiPlainTextFile file) {
super.visitPlainTextFile(file);
}
@Override
public void visitPlainTextFile(PsiPlainTextFile file) {
super.visitPlainTextFile(file);
}
}

View File

@ -30,8 +30,8 @@
<actions>
<group id="MyPlugin.TestMeu" text="Greeting" description="Greeting menu">
<add-to-group group-id="MainMenu" anchor="last" />
<action id="Myplugin.Textboxes" class="HelloAction" text="Hello" description="Says hello" />
<add-to-group group-id="MainMenu" anchor="last"/>
<action id="Myplugin.Textboxes" class="HelloAction" text="Hello" description="Says hello"/>
</group>
</actions>

View File

@ -1,9 +1,13 @@
<templateSet group="Markdown">
<template name="[" value="[$TEXT$]($LINK$)$END$" description="New link reference." toReformat="false" toShortenFQNames="false">
<variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true" />
<variable name="LINK" expression="complete()" defaultValue="" alwaysStopAt="true" />
<context>
<option name="MARKDOWN" value="true" />
</context>
</template>
<template name="["
value="[$TEXT$]($LINK$)$END$"
description="New link reference."
toReformat="false"
toShortenFQNames="false">
<variable name="TEXT" expression="" defaultValue="" alwaysStopAt="true"/>
<variable name="LINK" expression="complete()" defaultValue="" alwaysStopAt="true"/>
<context>
<option name="MARKDOWN" value="true"/>
</context>
</template>
</templateSet>

View File

@ -1,17 +1,14 @@
import com.intellij.codeInsight.template.EverywhereContextType;
import com.intellij.codeInsight.template.TemplateContextType;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MarkdownContext extends TemplateContextType {
protected MarkdownContext() {
super("MARKDOWN", "Markdown");
}
protected MarkdownContext() {
super("MARKDOWN", "Markdown");
}
@Override
public boolean isInContext(@NotNull PsiFile file, int offset) {
return file.getName().endsWith(".md");
}
@Override
public boolean isInContext(@NotNull PsiFile file, int offset) {
return file.getName().endsWith(".md");
}
}

View File

@ -2,15 +2,14 @@ import com.intellij.codeInsight.template.impl.DefaultLiveTemplatesProvider;
import org.jetbrains.annotations.Nullable;
public class MarkdownTemplateProvider implements DefaultLiveTemplatesProvider {
@Override
public String[] getDefaultLiveTemplateFiles()
{
return new String[] {"liveTemplates/Markdown"};
}
@Override
public String[] getDefaultLiveTemplateFiles() {
return new String[]{"liveTemplates/Markdown"};
}
@Nullable
@Override
public String[] getHiddenLiveTemplateFiles() {
return new String[0];
}
@Nullable
@Override
public String[] getHiddenLiveTemplateFiles() {
return new String[0];
}
}

View File

@ -11,9 +11,9 @@
<project-components>
<!-- Add your project components here -->
<component>
<implementation-class>MyPackage.MaxProject</implementation-class>
</component>
<component>
<implementation-class>MyPackage.MaxProject</implementation-class>
</component>
</project-components>
<actions>
@ -22,8 +22,8 @@
<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
<applicationService serviceInterface="MyPackage.MyCounter" serviceImplementation="MyPackage.MyCounter">
<applicationService serviceInterface="MyPackage.MyCounter" serviceImplementation="MyPackage.MyCounter">
</applicationService>
</applicationService>
</extensions>
</idea-plugin>

View File

@ -15,40 +15,41 @@ import org.jetbrains.annotations.NotNull;
* To change this template use File | Settings | File Templates.
*/
public class MaxProject implements ProjectComponent {
public MaxProject(Project project) {
public MaxProject(Project project) {
}
public void initComponent() {
// TODO: insert component initialization logic here
}
public void disposeComponent() {
// TODO: insert component disposal logic here
}
@NotNull
public String getComponentName() {
return "MaxProject";
}
public void projectOpened() {
// called when project is opened
MyCounter CommandCounter = ServiceManager.getService(MyCounter.class);
if (CommandCounter.IncreaseCounter() == -1) {
Messages.showMessageDialog(
"The maximum number of opened projects exceeds " + String.valueOf(CommandCounter.MaxCount) +
" projects!", "Error", Messages.getErrorIcon());
ProjectManager PM = ProjectManager.getInstance();
Project[] AllProjects = PM.getOpenProjects();
Project project = AllProjects[AllProjects.length - 1];
PM.closeProject(project);
}
public void initComponent() {
// TODO: insert component initialization logic here
}
public void disposeComponent() {
// TODO: insert component disposal logic here
}
@NotNull
public String getComponentName() {
return "MaxProject";
}
public void projectOpened() {
// called when project is opened
MyCounter CommandCounter = ServiceManager.getService(MyCounter.class);
if (CommandCounter.IncreaseCounter() == -1) {
Messages.showMessageDialog("The maximum number of opened projects exceeds " + String.valueOf(CommandCounter.MaxCount) +
" projects!", "Error", Messages.getErrorIcon());
ProjectManager PM=ProjectManager.getInstance();
Project[] AllProjects = PM.getOpenProjects();
Project project = AllProjects[AllProjects.length-1];
PM.closeProject(project);
}
}
}
public void projectClosed() {
// called when project is being closed
MyCounter CommandCounter = ServiceManager.getService(MyCounter.class);
CommandCounter.DecreaseCounter();
}
public void projectClosed() {
// called when project is being closed
MyCounter CommandCounter = ServiceManager.getService(MyCounter.class);
CommandCounter.DecreaseCounter();
}
}

View File

@ -8,22 +8,23 @@ package MyPackage;
* To change this template use File | Settings | File Templates.
*/
public class MyCounter {
private int Count = 0;
// Sets the maximum allowed number of opened projects.
public final int MaxCount = 3;
public MyCounter(){
private int Count = 0;
// Sets the maximum allowed number of opened projects.
public final int MaxCount = 3;
public MyCounter() {
}
}
public int IncreaseCounter() {
Count++;
return (Count > MaxCount) ? -1:Count;
}
public int IncreaseCounter() {
Count++;
return (Count > MaxCount) ? -1 : Count;
}
public int DecreaseCounter() {
Count--;
return (Count > MaxCount) ? -1:Count;
}
public int DecreaseCounter() {
Count--;
return (Count > MaxCount) ? -1 : Count;
}
}

View File

@ -1,36 +1,36 @@
<idea-plugin version="2">
<id>com.intellij.tutorials.module</id>
<name>Module Type Demo</name>
<version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<id>com.intellij.tutorials.module</id>
<name>Module Type Demo</name>
<version>1.0</version>
<vendor email="support@jrtbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Basic example of working with module types</description>
<description>Basic example of working with module types</description>
<change-notes>Initial commit</change-notes>
<change-notes>Initial commit</change-notes>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products -->
<!-- uncomment to enable plugin in all products
<depends>com.intellij.modules.lang</depends>
-->
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products -->
<!-- uncomment to enable plugin in all products
<depends>com.intellij.modules.lang</depends>
-->
<extensions defaultExtensionNs="com.intellij">
<moduleType id="DEMO_MODULE_TYPE" implementationClass="com.intellij.tutorials.module.DemoModuleType"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<moduleType id="DEMO_MODULE_TYPE" implementationClass="com.intellij.tutorials.module.DemoModuleType"/>
</extensions>
<application-components>
<!-- Add your application components here -->
</application-components>
<application-components>
<!-- Add your application components here -->
</application-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<actions>
<!-- Add your actions here -->
</actions>
<actions>
<!-- Add your actions here -->
</actions>
</idea-plugin>

View File

@ -13,19 +13,19 @@ import org.jetbrains.annotations.Nullable;
* @author Anna Bulenkova
*/
public class DemoModuleBuilder extends ModuleBuilder {
@Override
public void setupRootModel(ModifiableRootModel model) throws ConfigurationException {
@Override
public void setupRootModel(ModifiableRootModel model) throws ConfigurationException {
}
}
@Override
public ModuleType getModuleType() {
return DemoModuleType.getInstance();
}
@Override
public ModuleType getModuleType() {
return DemoModuleType.getInstance();
}
@Nullable
@Override
public ModuleWizardStep getCustomOptionsStep(WizardContext context, Disposable parentDisposable) {
return new DemoModuleWizardStep();
}
@Nullable
@Override
public ModuleWizardStep getCustomOptionsStep(WizardContext context, Disposable parentDisposable) {
return new DemoModuleWizardStep();
}
}

View File

@ -14,47 +14,49 @@ import javax.swing.*;
* @author Anna Bulenkova
*/
public class DemoModuleType extends ModuleType<DemoModuleBuilder> {
private static final String ID = "DEMO_MODULE_TYPE";
private static final String ID = "DEMO_MODULE_TYPE";
public DemoModuleType() {
super(ID);
}
public DemoModuleType() {
super(ID);
}
public static DemoModuleType getInstance() {
return (DemoModuleType) ModuleTypeManager.getInstance().findByID(ID);
}
public static DemoModuleType getInstance() {
return (DemoModuleType) ModuleTypeManager.getInstance().findByID(ID);
}
@NotNull
@Override
public DemoModuleBuilder createModuleBuilder() {
return new DemoModuleBuilder();
}
@NotNull
@Override
public DemoModuleBuilder createModuleBuilder() {
return new DemoModuleBuilder();
}
@NotNull
@Override
public String getName() {
return "Demo Module Type";
}
@NotNull
@Override
public String getName() {
return "Demo Module Type";
}
@NotNull
@Override
public String getDescription() {
return "Demo Module Type";
}
@NotNull
@Override
public String getDescription() {
return "Demo Module Type";
}
@Override
public Icon getBigIcon() {
return AllIcons.General.Information;
}
@Override
public Icon getBigIcon() {
return AllIcons.General.Information;
}
@Override
public Icon getNodeIcon(@Deprecated boolean b) {
return AllIcons.General.Information;
}
@Override
public Icon getNodeIcon(@Deprecated boolean b) {
return AllIcons.General.Information;
}
@NotNull
@Override
public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull DemoModuleBuilder moduleBuilder, @NotNull ModulesProvider modulesProvider) {
return super.createWizardSteps(wizardContext, moduleBuilder, modulesProvider);
}
@NotNull
@Override
public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext,
@NotNull DemoModuleBuilder moduleBuilder,
@NotNull ModulesProvider modulesProvider) {
return super.createWizardSteps(wizardContext, moduleBuilder, modulesProvider);
}
}

View File

@ -8,13 +8,13 @@ import javax.swing.*;
* @author Anna Bulenkova
*/
public class DemoModuleWizardStep extends ModuleWizardStep {
@Override
public JComponent getComponent() {
return new JLabel("Provide some setting here");
}
@Override
public JComponent getComponent() {
return new JLabel("Provide some setting here");
}
@Override
public void updateDataModel() {
//todo update model according to UI
}
@Override
public void updateDataModel() {
//todo update model according to UI
}
}

View File

@ -1,140 +1,143 @@
<idea-plugin version="2" url="www.jetbrains.com" use-idea-classloader="true">
<id>org.jetbrains.plugins.sample.PluginSample</id>
<name>Basic plugin example</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<category>Samples</category>
<description><![CDATA[
<id>org.jetbrains.plugins.sample.PluginSample</id>
<name>Basic plugin example</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<category>Samples</category>
<description><![CDATA[
Illustration of configuration options.<br>
<em>most HTML tags may be used</em>
]]></description>
<change-notes><![CDATA[
<change-notes><![CDATA[
Initial release.<br>
<em>most HTML tags may be used</em>
]]>
</change-notes>
</change-notes>
<!-- http://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products -->
<!-- The unique identifiers of the plugins on which this plugin depends -->
<!-- com.intellij.modules.lang is included in every IntelliJ-based IDE, plugin will be available as well -->
<depends>com.intellij.modules.lang</depends>
<!-- Optional dependency on another plugin. If the plugin with the "MySecondPlugin" ID is installed, the contents of mysecondplugin.xml (the format of this file conforms to the format of plugin.xml) will be loaded. -->
<!--<depends optional="true" config-file="custom-plugin.xml">CustomPlugin</depends>-->
<!-- http://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products -->
<!-- The unique identifiers of the plugins on which this plugin depends -->
<!-- com.intellij.modules.lang is included in every IntelliJ-based IDE, plugin will be available as well -->
<depends>com.intellij.modules.lang</depends>
<!-- Optional dependency on another plugin. If the plugin with the "MySecondPlugin" ID is installed, the contents of mysecondplugin.xml (the format of this file conforms to the format of plugin.xml) will be loaded. -->
<!--<depends optional="true" config-file="custom-plugin.xml">CustomPlugin</depends>-->
<!-- Allows a plugin to integrate its help system (in JavaHelp format) with the IDEA help system. The "file" attribute specifies the name of the JAR file
in the "help" subdirectory of the plugin directory. The "path" attribute specifies the name of the helpset file within the JAR file.-->
<helpset file="plugin-help.jar" path="/Help.hs"/>
<!-- Allows a plugin to integrate its help system (in JavaHelp format) with the IDEA help system. The "file" attribute specifies the name of the JAR file
in the "help" subdirectory of the plugin directory. The "path" attribute specifies the name of the helpset file within the JAR file.-->
<helpset file="plugin-help.jar" path="/Help.hs"/>
<!-- Minimum and maximum build of IDEA compatible with the plugin -->
<idea-version since-build="139.000" until-build="999"/>
<!-- Minimum and maximum build of IDEA compatible with the plugin -->
<idea-version since-build="139.000" until-build="999"/>
<!-- Resource bundle from which the text of plugin descriptions, action names and etc. will be loaded -->
<resource-bundle>org.jetbrains.tutorials.sample.PluginSampleBundle</resource-bundle>
<!-- Resource bundle from which the text of plugin descriptions, action names and etc. will be loaded -->
<resource-bundle>org.jetbrains.tutorials.sample.PluginSampleBundle</resource-bundle>
<!-- Plugin's application components -->
<application-components>
<component>
<!-- Component's interface class -->
<interface-class>org.jetbrains.tutorials.sample.DummyApplicationComponent</interface-class>
<!-- Component's implementation class -->
<implementation-class>org.jetbrains.tutorials.sample.DummyApplicationComponentImpl</implementation-class>
</component>
</application-components>
<!-- Plugin's application components -->
<application-components>
<component>
<!-- Component's interface class -->
<interface-class>org.jetbrains.tutorials.sample.DummyApplicationComponent</interface-class>
<!-- Component's implementation class -->
<implementation-class>org.jetbrains.tutorials.sample.DummyApplicationComponentImpl</implementation-class>
</component>
</application-components>
<!-- Plugin's project components -->
<project-components>
<component>
<!-- Interface and implementation classes are the same -->
<interface-class>org.jetbrains.tutorials.sample.DummyProjectComponent</interface-class>
<implementation-class>org.jetbrains.tutorials.sample.DummyProjectComponentImpl</implementation-class>
<!-- If the "workspace" option is set "true", the component saves its state to the .iws file
instead of the .ipr file. Note that the <option> element is used only if the component implements the JDOMExternalizable interface. Otherwise, the use of the <option> element takes no effect.-->
<!-- Plugin's project components -->
<project-components>
<component>
<!-- Interface and implementation classes are the same -->
<interface-class>org.jetbrains.tutorials.sample.DummyProjectComponent</interface-class>
<implementation-class>org.jetbrains.tutorials.sample.DummyProjectComponentImpl</implementation-class>
<!-- If the "workspace" option is set "true", the component saves its state to the .iws file
instead of the .ipr file. Note that the <option> element is used only if the component implements the JDOMExternalizable interface. Otherwise, the use of the <option> element takes no effect.-->
<option name="workspace" value="true"/>
<!-- If the "loadForDefaultProject" tag is present, the project component is instantiated also for the default project. -->
<loadForDefaultProject/>
</component>
</project-components>
<option name="workspace" value="true"/>
<!-- If the "loadForDefaultProject" tag is present, the project component is instantiated also for the default project. -->
<loadForDefaultProject/>
</component>
</project-components>
<!-- Plugin's module components -->
<module-components>
<component>
<interface-class>org.jetbrains.tutorials.sample.DummyModuleComponent</interface-class>
<implementation-class>org.jetbrains.tutorials.sample.DummyModuleComponentImpl</implementation-class>
</component>
</module-components>
<!-- Plugin's module components -->
<module-components>
<component>
<interface-class>org.jetbrains.tutorials.sample.DummyModuleComponent</interface-class>
<implementation-class>org.jetbrains.tutorials.sample.DummyModuleComponentImpl</implementation-class>
</component>
</module-components>
<!-- Actions -->
<actions>
<!-- The <action> element defines an action to register.
The mandatory "id" attribute specifies an unique identifier for the action.
The mandatory "class" attribute specifies the full-qualified name of the class implementing the action.
The mandatory "text" attribute specifies the text of the action (tooltip for toolbar button or text for menu item).
The optional "use-shortcut-of" attribute specifies the ID of the action whose keyboard shortcut this action will use.
The optional "description" attribute specifies the text which is displayed in the status bar when the action is focused.
The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the menu item. -->
<action id="PluginSample.DummyAction" class="org.jetbrains.tutorials.sample.actions.SimpleAction" text="Dummy Action"
description="Illustrates how to plug an action in">
<!-- The <keyboard-shortcut> node specifies the keyboard shortcut for the action. An action can have several keyboard shortcuts.
The mandatory "first-keystroke" attribute specifies the first keystroke of the action. The key strokes are specified according to the regular Swing rules.
The optional "second-keystroke" attribute specifies the second keystroke of the action.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<keyboard-shortcut first-keystroke="control alt A" second-keystroke="C" keymap="$default"/>
<!-- The <mouse-shortcut> node specifies the mouse shortcut for the action. An action can have several mouse shortcuts.
The mandatory "keystroke" attribute specifies the clicks and modifiers for the action. It is defined as a sequence of words separated by spaces:
"button1", "button2", "button3" for the mouse buttons; "shift", "control", "meta", "alt", "altGraph" for the modifier keys;
"doubleClick" if the action is activated by a double-click of the button.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<mouse-shortcut keystroke="control button3 doubleClick" keymap="$default"/>
<!-- The <add-to-group> node specifies that the action should be added to an existing group. An action can be added to several groups.
The mandatory "group-id" attribute specifies the ID of the group to which the action is added.
The group must be implemented by an instance of the DefaultActionGroup class.
The mandatory "anchor" attribute specifies the position of the action in the group relative to other actions. It can have the values
"first", "last", "before" and "after".
The "relative-to-action" attribute is mandatory if the anchor is set to "before" and "after", and specifies the action before or after which
the current action is inserted. -->
<add-to-group group-id="ToolsMenu" anchor="after"/>
</action>
<!-- The <group> element defines an action group. <action>, <group> and <separator> elements defined within it are automatically included in the group.
The mandatory "id" attribute specifies an unique identifier for the action.
The optional "class" attribute specifies the full-qualified name of the class implementing the group. If not specified,
com.intellij.openapi.actionSystem.DefaultActionGroup is used.
The optional "text" attribute specifies the text of the group (text for the menu item showing the submenu).
The optional "description" attribute specifies the text which is displayed in the status bar when the group is focused.
The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the group.
The optional "popup" attribute specifies how the group is presented in the menu. If a group has popup="true", actions in it
are placed in a submenu; for popup="false", actions are displayed as a section of the same menu delimited by separators. -->
<group id="DummyDefaultActionGroup" text="Default action group">
<action class="org.jetbrains.tutorials.sample.actions.GroupedToDefaultAction" id="PluginSample.GroupedToDefaultAction"/>
</group>
<group class="org.jetbrains.tutorials.sample.actions.DummyActionGroup" id="DummyActionGroup" text="Action Group"
description="Illustration of an action group"
icon="icons/testgroup.png" popup="true">
<action id="PluginSample.GroupedAction" class="org.jetbrains.tutorials.sample.actions.GroupedAction"
text="Grouped Action" description="An action in the group"/>
<!-- The <separator> element defines a separator between actions. It can also have an <add-to-group> child element. -->
<separator/>
<group id="ActionSubGroup"/>
<!-- The <reference> element allows to add an existing action to the group. The mandatory "ref" attribute specifies the ID of the action to add. -->
<reference ref="EditorCopy"/>
<add-to-group group-id="MainMenu" relative-to-action="HelpMenu" anchor="before"/>
</group>
<!-- Actions -->
<actions>
<!-- The <action> element defines an action to register.
The mandatory "id" attribute specifies an unique identifier for the action.
The mandatory "class" attribute specifies the full-qualified name of the class implementing the action.
The mandatory "text" attribute specifies the text of the action (tooltip for toolbar button or text for menu item).
The optional "use-shortcut-of" attribute specifies the ID of the action whose keyboard shortcut this action will use.
The optional "description" attribute specifies the text which is displayed in the status bar when the action is focused.
The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the menu item. -->
<action id="PluginSample.DummyAction"
class="org.jetbrains.tutorials.sample.actions.SimpleAction"
text="Dummy Action"
description="Illustrates how to plug an action in">
<!-- The <keyboard-shortcut> node specifies the keyboard shortcut for the action. An action can have several keyboard shortcuts.
The mandatory "first-keystroke" attribute specifies the first keystroke of the action. The key strokes are specified according to the regular Swing rules.
The optional "second-keystroke" attribute specifies the second keystroke of the action.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<keyboard-shortcut first-keystroke="control alt A" second-keystroke="C" keymap="$default"/>
<!-- The <mouse-shortcut> node specifies the mouse shortcut for the action. An action can have several mouse shortcuts.
The mandatory "keystroke" attribute specifies the clicks and modifiers for the action. It is defined as a sequence of words separated by spaces:
"button1", "button2", "button3" for the mouse buttons; "shift", "control", "meta", "alt", "altGraph" for the modifier keys;
"doubleClick" if the action is activated by a double-click of the button.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<mouse-shortcut keystroke="control button3 doubleClick" keymap="$default"/>
<!-- The <add-to-group> node specifies that the action should be added to an existing group. An action can be added to several groups.
The mandatory "group-id" attribute specifies the ID of the group to which the action is added.
The group must be implemented by an instance of the DefaultActionGroup class.
The mandatory "anchor" attribute specifies the position of the action in the group relative to other actions. It can have the values
"first", "last", "before" and "after".
The "relative-to-action" attribute is mandatory if the anchor is set to "before" and "after", and specifies the action before or after which
the current action is inserted. -->
<add-to-group group-id="ToolsMenu" anchor="after"/>
</action>
<!-- The <group> element defines an action group. <action>, <group> and <separator> elements defined within it are automatically included in the group.
The mandatory "id" attribute specifies an unique identifier for the action.
The optional "class" attribute specifies the full-qualified name of the class implementing the group. If not specified,
com.intellij.openapi.actionSystem.DefaultActionGroup is used.
The optional "text" attribute specifies the text of the group (text for the menu item showing the submenu).
The optional "description" attribute specifies the text which is displayed in the status bar when the group is focused.
The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the group.
The optional "popup" attribute specifies how the group is presented in the menu. If a group has popup="true", actions in it
are placed in a submenu; for popup="false", actions are displayed as a section of the same menu delimited by separators. -->
<group id="DummyDefaultActionGroup" text="Default action group">
<action class="org.jetbrains.tutorials.sample.actions.GroupedToDefaultAction"
id="PluginSample.GroupedToDefaultAction"/>
</group>
<group class="org.jetbrains.tutorials.sample.actions.DummyActionGroup" id="DummyActionGroup" text="Action Group"
description="Illustration of an action group"
icon="icons/testgroup.png" popup="true">
<action id="PluginSample.GroupedAction" class="org.jetbrains.tutorials.sample.actions.GroupedAction"
text="Grouped Action" description="An action in the group"/>
<!-- The <separator> element defines a separator between actions. It can also have an <add-to-group> child element. -->
<separator/>
<group id="ActionSubGroup"/>
<!-- The <reference> element allows to add an existing action to the group. The mandatory "ref" attribute specifies the ID of the action to add. -->
<reference ref="EditorCopy"/>
<add-to-group group-id="MainMenu" relative-to-action="HelpMenu" anchor="before"/>
</group>
</actions>
</actions>
<!-- Extension points defined by the plugin. Extension points are registered by a plugin so that other plugins can provide this plugin
with certain data. The "beanClass" attribute specifies the class the implementations of which can be used for the extension point. -->
<!--<extensionPoints>-->
<!--<extensionPoint name="testExtensionPoint" beanClass="com.foo.impl.MyExtensionBean"/>-->
<!--</extensionPoints>-->
<!-- Extension points defined by the plugin. Extension points are registered by a plugin so that other plugins can provide this plugin
with certain data. The "beanClass" attribute specifies the class the implementations of which can be used for the extension point. -->
<!--<extensionPoints>-->
<!--<extensionPoint name="testExtensionPoint" beanClass="com.foo.impl.MyExtensionBean"/>-->
<!--</extensionPoints>-->
<!-- Extensions which the plugin adds to extension points defined by the IDEA core or by other plugins. The "defaultExtensionNs " attribute must be set to the ID of the plugin defining the extension point,
or to "com.intellij" if the extension point is defined by the IDEA core. The name of the
tag within the <extensions> tag matches the name of the extension point, and the "implementation" class specifies the name of the
class added to the extension point. -->
<extensions>
<!--<testExtensionPoint implementation="com.foo.impl.MyExtensionImpl"/>-->
</extensions>
<!-- Extensions which the plugin adds to extension points defined by the IDEA core or by other plugins. The "defaultExtensionNs " attribute must be set to the ID of the plugin defining the extension point,
or to "com.intellij" if the extension point is defined by the IDEA core. The name of the
tag within the <extensions> tag matches the name of the extension point, and the "implementation" class specifies the name of the
class added to the extension point. -->
<extensions>
<!--<testExtensionPoint implementation="com.foo.impl.MyExtensionImpl"/>-->
</extensions>
</idea-plugin>

View File

@ -5,5 +5,5 @@ import com.intellij.openapi.components.ApplicationComponent;
/**
* @author Anna Bulenkova
*/
interface DummyApplicationComponent extends ApplicationComponent{
interface DummyApplicationComponent extends ApplicationComponent {
}

View File

@ -6,19 +6,19 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class DummyApplicationComponentImpl implements DummyApplicationComponent {
@Override
public void initComponent() {
@Override
public void initComponent() {
}
}
@Override
public void disposeComponent() {
@Override
public void disposeComponent() {
}
}
@NotNull
@Override
public String getComponentName() {
return "DummyApplicationComponent";
}
@NotNull
@Override
public String getComponentName() {
return "DummyApplicationComponent";
}
}

View File

@ -5,5 +5,5 @@ import com.intellij.openapi.module.ModuleComponent;
/**
* @author Anna Bulenkova
*/
public interface DummyModuleComponent extends ModuleComponent{
public interface DummyModuleComponent extends ModuleComponent {
}

View File

@ -6,34 +6,34 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class DummyModuleComponentImpl implements DummyModuleComponent {
@Override
public void projectOpened() {
@Override
public void projectOpened() {
}
}
@Override
public void projectClosed() {
@Override
public void projectClosed() {
}
}
@Override
public void moduleAdded() {
@Override
public void moduleAdded() {
}
}
@Override
public void initComponent() {
@Override
public void initComponent() {
}
}
@Override
public void disposeComponent() {
@Override
public void disposeComponent() {
}
}
@NotNull
@Override
public String getComponentName() {
return "DummyModuleComponent";
}
@NotNull
@Override
public String getComponentName() {
return "DummyModuleComponent";
}
}

View File

@ -5,5 +5,5 @@ import com.intellij.openapi.components.ProjectComponent;
/**
* @author Anna Bulenkova
*/
public interface DummyProjectComponent extends ProjectComponent{
public interface DummyProjectComponent extends ProjectComponent {
}

View File

@ -6,29 +6,29 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class DummyProjectComponentImpl implements DummyProjectComponent {
@Override
public void projectOpened() {
@Override
public void projectOpened() {
}
}
@Override
public void projectClosed() {
@Override
public void projectClosed() {
}
}
@Override
public void initComponent() {
@Override
public void initComponent() {
}
}
@Override
public void disposeComponent() {
@Override
public void disposeComponent() {
}
}
@NotNull
@Override
public String getComponentName() {
return "DummyProjectComponent";
}
@NotNull
@Override
public String getComponentName() {
return "DummyProjectComponent";
}
}

View File

@ -9,9 +9,9 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class DummyActionGroup extends ActionGroup {
@NotNull
@Override
public AnAction[] getChildren(AnActionEvent anActionEvent) {
return new GroupedAction[0];
}
@NotNull
@Override
public AnAction[] getChildren(AnActionEvent anActionEvent) {
return new GroupedAction[0];
}
}

View File

@ -8,8 +8,8 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class GroupedAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
}
}
}

View File

@ -8,8 +8,8 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class GroupedToDefaultAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
}
}
}

View File

@ -9,16 +9,16 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class SimpleAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
}
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
}
@Override
public void update(@NotNull AnActionEvent e) {
//Make action visible and available only when project is defined
final Project project = e.getProject();
boolean isAvailable = project != null;
e.getPresentation().setVisible(isAvailable);
e.getPresentation().setEnabled(isAvailable);
}
@Override
public void update(@NotNull AnActionEvent e) {
//Make action visible and available only when project is defined
final Project project = e.getProject();
boolean isAvailable = project != null;
e.getPresentation().setVisible(isAvailable);
e.getPresentation().setEnabled(isAvailable);
}
}

View File

@ -1,55 +1,55 @@
<idea-plugin version="2" url="www.jetbrains.com">
<id>org.jetbrains.plugins.sample.ProjectModel</id>
<name>Editor basics</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<id>org.jetbrains.plugins.sample.ProjectModel</id>
<name>Editor basics</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Project model illustration</description>
<description>Project model illustration</description>
<change-notes>Initial commit</change-notes>
<change-notes>Initial commit</change-notes>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends>
<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
</extensions>
<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
</extensions>
<application-components>
<!-- Add your application components here -->
</application-components>
<application-components>
<!-- Add your application components here -->
</application-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<actions>
<action id="ProjectModel.SourceRoots" class="com.intellij.tutorials.project.model.ShowSourceRootsActions"
text="Show Source Roots"
description="Illustrates how to get source roots">
<add-to-group group-id="ToolsMenu" anchor="after"/>
</action>
<action id="ProjectModel.ProjectSdk" class="com.intellij.tutorials.project.model.ProjectSdkAction"
text="Show Sdk Info"
description="Illustrates how to get source roots">
<add-to-group group-id="ToolsMenu" anchor="after"/>
</action>
<action id="ProjectModel.ProjectFileIndex"
class="com.intellij.tutorials.project.model.ProjectFileIndexSampleAction"
text="FileProjectIndex in Action"
description="Illustrates how to get source roots">
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
<action id="ProjectModel.ModificationAction" class="com.intellij.tutorials.project.model.ModificationAction"
text="Project Modification in Action"
description="Illustrates how to get source roots">
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
<action id="ProjectModel.LibrariesAction" class="com.intellij.tutorials.project.model.LibrariesAction"
text="Libraries for file"
description="Illustrates accessing libraries">
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
</actions>
<actions>
<action id="ProjectModel.SourceRoots" class="com.intellij.tutorials.project.model.ShowSourceRootsActions"
text="Show Source Roots"
description="Illustrates how to get source roots">
<add-to-group group-id="ToolsMenu" anchor="after"/>
</action>
<action id="ProjectModel.ProjectSdk" class="com.intellij.tutorials.project.model.ProjectSdkAction"
text="Show Sdk Info"
description="Illustrates how to get source roots">
<add-to-group group-id="ToolsMenu" anchor="after"/>
</action>
<action id="ProjectModel.ProjectFileIndex"
class="com.intellij.tutorials.project.model.ProjectFileIndexSampleAction"
text="FileProjectIndex in Action"
description="Illustrates how to get source roots">
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
<action id="ProjectModel.ModificationAction" class="com.intellij.tutorials.project.model.ModificationAction"
text="Project Modification in Action"
description="Illustrates how to get source roots">
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
<action id="ProjectModel.LibrariesAction" class="com.intellij.tutorials.project.model.LibrariesAction"
text="Libraries for file"
description="Illustrates accessing libraries">
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
</actions>
</idea-plugin>

View File

@ -17,47 +17,48 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class LibrariesAction extends AnAction {
@Override
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) {
PsiFile psiFile = ((PsiClass) element).getContainingFile();
if (psiFile == null) return;
VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) return;
event.getPresentation().setEnabledAndVisible(true);
}
@Override
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) {
PsiFile psiFile = ((PsiClass) element).getContainingFile();
if (psiFile == null) return;
VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) return;
event.getPresentation().setEnabledAndVisible(true);
}
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
Project project = event.getProject();
if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) {
PsiFile psiFile = ((PsiClass) element).getContainingFile();
if (psiFile == null) return;
VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) return;
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
StringBuilder jars = new StringBuilder();
for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) {
if (orderEntry instanceof LibraryOrderEntry) {
final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry;
final Library library = libraryEntry.getLibrary();
if (library == null) continue;
VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
if (files.length == 0) continue;
for (VirtualFile jar : files) {
jars.append(jar.getName()).append(", ");
}
}
}
if (jars.length() > 0) {
Messages.showInfoMessage("Libraries for file " + virtualFile.getName() + ": " + jars.toString(), "Libraries Info");
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
Project project = event.getProject();
if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) {
PsiFile psiFile = ((PsiClass) element).getContainingFile();
if (psiFile == null) return;
VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) return;
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
StringBuilder jars = new StringBuilder();
for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) {
if (orderEntry instanceof LibraryOrderEntry) {
final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry;
final Library library = libraryEntry.getLibrary();
if (library == null) continue;
VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
if (files.length == 0) continue;
for (VirtualFile jar : files) {
jars.append(jar.getName()).append(", ");
}
}
}
if (jars.length() > 0) {
Messages.showInfoMessage("Libraries for file " + virtualFile.getName() + ": " + jars.toString(),
"Libraries Info");
}
}
}
}

View File

@ -19,30 +19,30 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class ModificationAction extends AnAction {
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) {
PsiFile file = ((PsiClass) element).getContainingFile();
if (file == null) return;
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return;
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
final Module module = fileIndex.getModuleForFile(virtualFile);
if (module == null) return;
if (!ModuleRootManager.getInstance(module).getFileIndex().isInContent(virtualFile)) {
ModuleRootModificationUtil.addModuleLibrary(module, virtualFile.getUrl());
}
}
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project == null) return;
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
if (element instanceof PsiClass) {
PsiFile file = ((PsiClass) element).getContainingFile();
if (file == null) return;
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return;
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
final Module module = fileIndex.getModuleForFile(virtualFile);
if (module == null) return;
if (!ModuleRootManager.getInstance(module).getFileIndex().isInContent(virtualFile)) {
ModuleRootModificationUtil.addModuleLibrary(module, virtualFile.getUrl());
}
}
@Override
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject();
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
event.getPresentation().setEnabledAndVisible(project != null && element != null);
}
}
@Override
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject();
Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
event.getPresentation().setEnabledAndVisible(project != null && element != null);
}
}

View File

@ -18,38 +18,38 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class ProjectFileIndexSampleAction extends AnAction {
@Override
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject();
final Editor editor = event.getData(CommonDataKeys.EDITOR);
boolean visibility = project != null && editor != null;
event.getPresentation().setEnabledAndVisible(visibility);
}
@Override
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject();
final Editor editor = event.getData(CommonDataKeys.EDITOR);
boolean visibility = project != null && editor != null;
event.getPresentation().setEnabledAndVisible(visibility);
}
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject();
final Editor editor = event.getData(CommonDataKeys.EDITOR);
if (project == null || editor == null) return;
Document document = editor.getDocument();
FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
VirtualFile virtualFile = fileDocumentManager.getFile(document);
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
if (virtualFile != null) {
Module module = projectFileIndex.getModuleForFile(virtualFile);
String moduleName;
moduleName = module != null ? module.getName() : "No module defined for file";
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject();
final Editor editor = event.getData(CommonDataKeys.EDITOR);
if (project == null || editor == null) return;
Document document = editor.getDocument();
FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
VirtualFile virtualFile = fileDocumentManager.getFile(document);
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
if (virtualFile != null) {
Module module = projectFileIndex.getModuleForFile(virtualFile);
String moduleName;
moduleName = module != null ? module.getName() : "No module defined for file";
VirtualFile moduleContentRoot = projectFileIndex.getContentRootForFile(virtualFile);
boolean isLibraryFile = projectFileIndex.isLibraryClassFile(virtualFile);
boolean isInLibraryClasses = projectFileIndex.isInLibraryClasses(virtualFile);
boolean isInLibrarySource = projectFileIndex.isInLibrarySource(virtualFile);
Messages.showInfoMessage("Module: " + moduleName + "\n" +
"Module content root: " + moduleContentRoot + "\n" +
"Is library file: " + isLibraryFile + "\n" +
"Is in library classes" + isInLibraryClasses +
"Is in library source" + isInLibrarySource,
"Main File Info for" + virtualFile.getName());
}
VirtualFile moduleContentRoot = projectFileIndex.getContentRootForFile(virtualFile);
boolean isLibraryFile = projectFileIndex.isLibraryClassFile(virtualFile);
boolean isInLibraryClasses = projectFileIndex.isInLibraryClasses(virtualFile);
boolean isInLibrarySource = projectFileIndex.isInLibrarySource(virtualFile);
Messages.showInfoMessage("Module: " + moduleName + "\n" +
"Module content root: " + moduleContentRoot + "\n" +
"Is library file: " + isLibraryFile + "\n" +
"Is in library classes" + isInLibraryClasses +
"Is in library source" + isInLibrarySource,
"Main File Info for" + virtualFile.getName());
}
}
}

View File

@ -12,23 +12,23 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class ProjectSdkAction extends AnAction {
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project != null) {
String projectSDKName = ProjectRootManager.getInstance(project).getProjectSdkName();
String newProjectSdkName = "New Sdk Name";
ProjectRootManager.getInstance(project).setProjectSdkName(newProjectSdkName);
Messages.showInfoMessage(projectSDKName + " has changed to " + newProjectSdkName, "Project Sdk Info");
}
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project != null) {
String projectSDKName = ProjectRootManager.getInstance(project).getProjectSdkName();
String newProjectSdkName = "New Sdk Name";
ProjectRootManager.getInstance(project).setProjectSdkName(newProjectSdkName);
Messages.showInfoMessage(projectSDKName + " has changed to " + newProjectSdkName, "Project Sdk Info");
}
}
@Override
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project != null) {
Sdk sdk = ProjectRootManager.getInstance(project).getProjectSdk();
event.getPresentation().setEnabledAndVisible(sdk != null);
}
@Override
public void update(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project != null) {
Sdk sdk = ProjectRootManager.getInstance(project).getProjectSdk();
event.getPresentation().setEnabledAndVisible(sdk != null);
}
}
}

View File

@ -12,23 +12,24 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class ShowSourceRootsActions extends AnAction {
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project == null) return;
String projectName = project.getName();
StringBuilder sourceRootsList = new StringBuilder();
VirtualFile[] vFiles = ProjectRootManager.getInstance(project).getContentSourceRoots();
for (VirtualFile file : vFiles) {
sourceRootsList.append(file.getUrl()).append("\n");
}
Messages.showInfoMessage("Source roots for the " + projectName + " plugin:\n" + sourceRootsList, "Project Properties");
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
Project project = event.getProject();
if (project == null) return;
String projectName = project.getName();
StringBuilder sourceRootsList = new StringBuilder();
VirtualFile[] vFiles = ProjectRootManager.getInstance(project).getContentSourceRoots();
for (VirtualFile file : vFiles) {
sourceRootsList.append(file.getUrl()).append("\n");
}
Messages.showInfoMessage("Source roots for the " + projectName + " plugin:\n" + sourceRootsList,
"Project Properties");
}
@Override
public void update(@NotNull final AnActionEvent event) {
boolean visibility = event.getProject() != null;
event.getPresentation().setEnabled(visibility);
event.getPresentation().setVisible(visibility);
}
@Override
public void update(@NotNull final AnActionEvent event) {
boolean visibility = event.getProject() != null;
event.getPresentation().setEnabled(visibility);
event.getPresentation().setVisible(visibility);
}
}

View File

@ -1,30 +1,30 @@
<idea-plugin version="2" url="www.jetbrains.com">
<id>org.jetbrains.plugins.sample.ProjectViewPane</id>
<name>Project View Pain Demo</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<id>org.jetbrains.plugins.sample.ProjectViewPane</id>
<name>Project View Pain Demo</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Project View Pain Demo</description>
<description>Project View Pain Demo</description>
<change-notes>Initial commit</change-notes>
<change-notes>Initial commit</change-notes>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends>
<extensions defaultExtensionNs="com.intellij">
<projectViewPane implementation="org.jetbrains.tutorials.view.pane.ImagesProjectViewPane"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<projectViewPane implementation="org.jetbrains.tutorials.view.pane.ImagesProjectViewPane"/>
</extensions>
<application-components>
<!-- Add your application components here -->
</application-components>
<application-components>
<!-- Add your application components here -->
</application-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<actions>
<!-- Add your actions here -->
</actions>
<actions>
<!-- Add your actions here -->
</actions>
</idea-plugin>

View File

@ -26,146 +26,148 @@ import java.util.*;
* @author Anna Bulenkova
*/
public class ImagesProjectNode extends AbstractTreeNode<VirtualFile> {
private static final Key<Set<VirtualFile>> IMAGES_PROJECT_DIRS = Key.create("images.files.or.directories");
private static final Key<Set<VirtualFile>> IMAGES_PROJECT_DIRS = Key.create("images.files.or.directories");
public ImagesProjectNode(final Project project) {
super(project, project.getBaseDir());
scanImages(project);
public ImagesProjectNode(final Project project) {
super(project, project.getBaseDir());
scanImages(project);
subscribeToVFS(project);
subscribeToVFS(project);
}
public ImagesProjectNode(Project project, VirtualFile file) {
super(project, file);
}
private void scanImages(Project project) {
addAllByExt(project, "png");
addAllByExt(project, "jpg");
}
private void addAllByExt(Project project, String ext) {
final Set<VirtualFile> imagesFiles = getImagesFiles(project);
final VirtualFile projectDir = project.getBaseDir();
for (VirtualFile file : FilenameIndex.getAllFilesByExt(project, ext)) {
while (file != null && !file.equals(projectDir)) {
imagesFiles.add(file);
file = file.getParent();
}
}
}
public ImagesProjectNode(Project project, VirtualFile file) {
super(project, file);
@NotNull
private Set<VirtualFile> getImagesFiles(Project project) {
Set<VirtualFile> files = project.getUserData(IMAGES_PROJECT_DIRS);
if (files == null) {
files = new HashSet<VirtualFile>();
project.putUserData(IMAGES_PROJECT_DIRS, files);
}
return files;
}
private void scanImages(Project project) {
addAllByExt(project, "png");
addAllByExt(project, "jpg");
@Override
protected VirtualFile getVirtualFile() {
return getValue();
}
@NotNull
@Override
public Collection<? extends AbstractTreeNode> getChildren() {
final List<VirtualFile> files = new ArrayList<VirtualFile>(0);
for (VirtualFile file : getValue().getChildren()) {
if (getImagesFiles(myProject).contains(file)) {
files.add(file);
}
}
private void addAllByExt(Project project, String ext) {
final Set<VirtualFile> imagesFiles = getImagesFiles(project);
final VirtualFile projectDir = project.getBaseDir();
for (VirtualFile file : FilenameIndex.getAllFilesByExt(project, ext)) {
while (file != null && !file.equals(projectDir)) {
imagesFiles.add(file);
file = file.getParent();
}
if (files.isEmpty()) return Collections.emptyList();
final List<AbstractTreeNode> nodes = new ArrayList<AbstractTreeNode>(files.size());
final boolean alwaysOnTop = ((ProjectViewImpl) ProjectView.getInstance(myProject)).isFoldersAlwaysOnTop();
Collections.sort(files, new Comparator<VirtualFile>() {
@Override
public int compare(VirtualFile o1, VirtualFile o2) {
if (alwaysOnTop) {
final boolean d1 = o1.isDirectory();
final boolean d2 = o2.isDirectory();
if (d1 && !d2) return -1;
if (!d1 && d2) return 1;
}
return StringUtil.naturalCompare(o1.getName(), o2.getName());
}
});
for (VirtualFile file : files) {
nodes.add(new ImagesProjectNode(myProject, file));
}
return nodes;
}
@NotNull
private Set<VirtualFile> getImagesFiles(Project project) {
Set<VirtualFile> files = project.getUserData(IMAGES_PROJECT_DIRS);
if (files == null) {
files = new HashSet<VirtualFile>();
project.putUserData(IMAGES_PROJECT_DIRS, files);
}
return files;
}
@Override
protected void update(PresentationData data) {
data.setIcon(getValue().isDirectory() ? AllIcons.Nodes.Folder : getValue().getFileType().getIcon());
data.setPresentableText(getValue().getName());
}
@Override
protected VirtualFile getVirtualFile() {
return getValue();
}
@NotNull
@Override
public Collection<? extends AbstractTreeNode> getChildren() {
final List<VirtualFile> files = new ArrayList<VirtualFile>(0);
for (VirtualFile file : getValue().getChildren()) {
if (getImagesFiles(myProject).contains(file)) {
files.add(file);
}
}
if (files.isEmpty()) return Collections.emptyList();
final List<AbstractTreeNode> nodes = new ArrayList<AbstractTreeNode>(files.size());
final boolean alwaysOnTop = ((ProjectViewImpl) ProjectView.getInstance(myProject)).isFoldersAlwaysOnTop();
Collections.sort(files, new Comparator<VirtualFile>() {
@Override
public int compare(VirtualFile o1, VirtualFile o2) {
if (alwaysOnTop) {
final boolean d1 = o1.isDirectory();
final boolean d2 = o2.isDirectory();
if (d1 && !d2) return -1;
if (!d1 && d2) return 1;
}
@Override
public boolean canNavigate() {
return !getValue().isDirectory();
}
return StringUtil.naturalCompare(o1.getName(), o2.getName());
}
@Override
public boolean canNavigateToSource() {
return canNavigate();
}
@Override
public void navigate(boolean requestFocus) {
FileEditorManager.getInstance(myProject).openFile(getValue(), false);
}
private void subscribeToVFS(final Project project) {
final Alarm alarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, project);
LocalFileSystem.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
{
final VirtualFileAdapter me = this;
Disposer.register(project, new Disposable() {
@Override
public void dispose() {
LocalFileSystem.getInstance().removeVirtualFileListener(me);
}
});
for (VirtualFile file : files) {
nodes.add(new ImagesProjectNode(myProject, file));
}
return nodes;
}
}
@Override
protected void update(PresentationData data) {
data.setIcon(getValue().isDirectory() ? AllIcons.Nodes.Folder : getValue().getFileType().getIcon());
data.setPresentableText(getValue().getName());
}
@Override
public void fileCreated(@NotNull VirtualFileEvent event) {
handle(event);
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
handle(event);
}
@Override
public boolean canNavigate() {
return !getValue().isDirectory();
}
@Override
public boolean canNavigateToSource() {
return canNavigate();
}
@Override
public void navigate(boolean requestFocus) {
FileEditorManager.getInstance(myProject).openFile(getValue(), false);
}
private void subscribeToVFS(final Project project) {
final Alarm alarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, project);
LocalFileSystem.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
{
final VirtualFileAdapter me = this;
Disposer.register(project, new Disposable() {
@Override
public void dispose() {
LocalFileSystem.getInstance().removeVirtualFileListener(me);
}
});
}
@Override
public void fileCreated(@NotNull VirtualFileEvent event) {
handle(event);
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
handle(event);
}
void handle(VirtualFileEvent event) {
final String filename = event.getFileName().toLowerCase();
if (filename.endsWith(".png") || filename.endsWith(".jpg")) {
alarm.cancelAllRequests();
alarm.addRequest(new Runnable() {
public void run() {
getImagesFiles(project).clear();
scanImages(project);
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ProjectView.getInstance(myProject).getProjectViewPaneById(ImagesProjectViewPane.ID).updateFromRoot(true);
}
});
}
}, 1000);
void handle(VirtualFileEvent event) {
final String filename = event.getFileName().toLowerCase();
if (filename.endsWith(".png") || filename.endsWith(".jpg")) {
alarm.cancelAllRequests();
alarm.addRequest(new Runnable() {
public void run() {
getImagesFiles(project).clear();
scanImages(project);
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ProjectView.getInstance(myProject)
.getProjectViewPaneById(ImagesProjectViewPane.ID)
.updateFromRoot(true);
}
});
}
});
}
}, 1000);
}
}
});
}
}

View File

@ -22,88 +22,88 @@ import javax.swing.tree.DefaultTreeModel;
* @author Anna Bulenkova
*/
public class ImagesProjectViewPane extends AbstractProjectViewPSIPane {
public static final String ID = "IMAGES";
public static final String ID = "IMAGES";
protected ImagesProjectViewPane(Project project) {
super(project);
}
protected ImagesProjectViewPane(Project project) {
super(project);
}
@Override
public String getTitle() {
return "Images";
}
@Override
public String getTitle() {
return "Images";
}
@Override
public javax.swing.Icon getIcon() {
return AllIcons.FileTypes.Custom;
}
@Override
public javax.swing.Icon getIcon() {
return AllIcons.FileTypes.Custom;
}
@NotNull
@Override
public String getId() {
return ID;
}
@NotNull
@Override
public String getId() {
return ID;
}
@Override
public int getWeight() {
@Override
public int getWeight() {
return 10;
}
@Override
public SelectInTarget createSelectInTarget() {
return new ProjectViewSelectInTarget(myProject) {
@Override
public String toString() {
return "images";
}
@Nullable
@Override
public String getMinorViewId() {
return "images";
}
@Override
public float getWeight() {
return 10;
}
}
};
}
@Override
public SelectInTarget createSelectInTarget() {
return new ProjectViewSelectInTarget(myProject) {
@Override
protected ProjectAbstractTreeStructureBase createStructure() {
return new ProjectTreeStructure(myProject, ID) {
@Override
protected AbstractTreeNode createRoot(Project project, ViewSettings settings) {
return new ImagesProjectNode(project);
}
@Override
public String toString() {
return "images";
}
@Override
public Object[] getChildElements(Object element) {
return super.getChildElements(element);
}
};
}
@Nullable
@Override
public String getMinorViewId() {
return "images";
}
@Override
protected ProjectViewTree createTree(DefaultTreeModel model) {
return new ProjectViewTree(myProject, model) {
@Override
public DefaultMutableTreeNode getSelectedNode() {
return ImagesProjectViewPane.this.getSelectedNode();
}
@Override
public float getWeight() {
return 10;
}
};
}
@Override
public boolean isRootVisible() {
return true;
}
};
}
@Override
protected ProjectAbstractTreeStructureBase createStructure() {
return new ProjectTreeStructure(myProject, ID) {
@Override
protected AbstractTreeNode createRoot(Project project, ViewSettings settings) {
return new ImagesProjectNode(project);
}
@Override
public Object[] getChildElements(Object element) {
return super.getChildElements(element);
}
};
}
@Override
protected ProjectViewTree createTree(DefaultTreeModel model) {
return new ProjectViewTree(myProject, model) {
@Override
public DefaultMutableTreeNode getSelectedNode() {
return ImagesProjectViewPane.this.getSelectedNode();
}
@Override
public boolean isRootVisible() {
return true;
}
};
}
@Override
protected AbstractTreeUpdater createTreeUpdater(AbstractTreeBuilder builder) {
return new AbstractTreeUpdater(builder);
}
@Override
protected AbstractTreeUpdater createTreeUpdater(AbstractTreeBuilder builder) {
return new AbstractTreeUpdater(builder);
}
}

View File

@ -14,7 +14,9 @@
<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
<moduleBuilder builderClass="org.jetbrains.tutorials.project.wizard.DemoModuleWizardStep" id="DEMO_STEP" order="first"/>
<moduleBuilder builderClass="org.jetbrains.tutorials.project.wizard.DemoModuleWizardStep"
id="DEMO_STEP"
order="first"/>
</extensions>
<application-components>

View File

@ -15,26 +15,27 @@ import javax.swing.*;
* @author Anna Bulenkova
*/
public class DemoModuleWizardStep extends ModuleBuilder {
public void setupRootModel(ModifiableRootModel modifiableRootModel) throws ConfigurationException {
public void setupRootModel(ModifiableRootModel modifiableRootModel) throws ConfigurationException {
}
}
public ModuleType getModuleType() {
return ModuleType.EMPTY; //or it could be other module type
}
public ModuleType getModuleType() {
return ModuleType.EMPTY; //or it could be other module type
}
@Override
public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull ModulesProvider modulesProvider) {
return new ModuleWizardStep[]{new ModuleWizardStep() {
@Override
public JComponent getComponent() {
return new JLabel("Put your content here");
}
@Override
public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext,
@NotNull ModulesProvider modulesProvider) {
return new ModuleWizardStep[]{new ModuleWizardStep() {
@Override
public JComponent getComponent() {
return new JLabel("Put your content here");
}
@Override
public void updateDataModel() {
@Override
public void updateDataModel() {
}
}};
}
}
}};
}
}

View File

@ -2,15 +2,15 @@
<id>org.jetbrains.plugins.sample.RegisterActions</id>
<name>Sample plugin for working with IntelliJ Action System</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Illustration of Action System</description>
<description>Illustration of Action System</description>
<change-notes>Initial commit</change-notes>
<change-notes>Initial commit</change-notes>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends>
<!-- please see https://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products -->
@ -39,45 +39,45 @@
The optional "use-shortcut-of" attribute specifies the ID of the action whose keyboard shortcut this action will use.
The optional "description" attribute specifies the text which is displayed in the status bar when the action is focused.
The optional "icon" attribute specifies the icon which is displayed on the toolbar button or next to the menu item. -->
<action id="org.jetbrains.tutorials.actions.SimpleAction" class="org.jetbrains.tutorials.actions.SimpleAction"
text="Simple Action" description="IntelliJ Action System Demo">
<!-- The <keyboard-shortcut> node specifies the keyboard shortcut for the action. An action can have several keyboard shortcuts.
The mandatory "first-keystroke" attribute specifies the first keystroke of the action. The key strokes are specified according to the regular Swing rules.
The optional "second-keystroke" attribute specifies the second keystroke of the action.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<keyboard-shortcut first-keystroke="control alt A" second-keystroke="C" keymap="$default"/>
<!-- The <mouse-shortcut> node specifies the mouse shortcut for the action. An action can have several mouse shortcuts.
The mandatory "keystroke" attribute specifies the clicks and modifiers for the action. It is defined as a sequence of words separated by spaces:
"button1", "button2", "button3" for the mouse buttons; "shift", "control", "meta", "alt", "altGraph" for the modifier keys;
"doubleClick" if the action is activated by a double-click of the button.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<mouse-shortcut keystroke="control button3 doubleClick" keymap="$default"/>
<!-- The <add-to-group> node specifies that the action should be added to an existing group. An action can be added to several groups.
The mandatory "group-id" attribute specifies the ID of the group to which the action is added.
The group must be implemented by an instance of the DefaultActionGroup class.
The mandatory "anchor" attribute specifies the position of the action in the group relative to other actions. It can have the values
"first", "last", "before" and "after".
The "relative-to-action" attribute is mandatory if the anchor is set to "before" and "after", and specifies the action before or after which
the current action is inserted. -->
<add-to-group group-id="ToolsMenu" anchor="first"/>
</action>
<group id="SimpleGroup" text="Custom Action Group" popup="true">
<action id="org.jetbrains.tutorials.actions.SimpleAction" class="org.jetbrains.tutorials.actions.SimpleAction"
text="Simple Action" description="IntelliJ Action System Demo">
<!-- The <keyboard-shortcut> node specifies the keyboard shortcut for the action. An action can have several keyboard shortcuts.
The mandatory "first-keystroke" attribute specifies the first keystroke of the action. The key strokes are specified according to the regular Swing rules.
The optional "second-keystroke" attribute specifies the second keystroke of the action.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<keyboard-shortcut first-keystroke="control alt A" second-keystroke="C" keymap="$default"/>
<!-- The <mouse-shortcut> node specifies the mouse shortcut for the action. An action can have several mouse shortcuts.
The mandatory "keystroke" attribute specifies the clicks and modifiers for the action. It is defined as a sequence of words separated by spaces:
"button1", "button2", "button3" for the mouse buttons; "shift", "control", "meta", "alt", "altGraph" for the modifier keys;
"doubleClick" if the action is activated by a double-click of the button.
The mandatory "keymap" attribute specifies the keymap for which the action is active. IDs of the standard keymaps are defined as
constants in the com.intellij.openapi.keymap.KeymapManager class. -->
<mouse-shortcut keystroke="control button3 doubleClick" keymap="$default"/>
<!-- The <add-to-group> node specifies that the action should be added to an existing group. An action can be added to several groups.
The mandatory "group-id" attribute specifies the ID of the group to which the action is added.
The group must be implemented by an instance of the DefaultActionGroup class.
The mandatory "anchor" attribute specifies the position of the action in the group relative to other actions. It can have the values
"first", "last", "before" and "after".
The "relative-to-action" attribute is mandatory if the anchor is set to "before" and "after", and specifies the action before or after which
the current action is inserted. -->
<add-to-group group-id="ToolsMenu" anchor="first"/>
</action>
<group id="SimpleGroup" text="Custom Action Group" popup="true">
<add-to-group group-id="EditorPopupMenu" anchor="first"/>
<action class="org.jetbrains.tutorials.actions.GroupedAction" id="org.jetbrains.tutorials.actions.GroupedAction"
text="Grouped Action" description="Grouped Action Demo">
</action>
</group>
<group id="CustomDefaultActionGroup" class="org.jetbrains.tutorials.actions.CustomDefaultActionGroup" popup="true"
text="DefaultActionGroup Inheritor" description="Default Action Group Demo">
<add-to-group group-id="ToolsMenu" anchor="last"/>
<action class="org.jetbrains.tutorials.actions.CustomGroupedAction" id="CustomGroupedAction"
text="Custom Grouped Action" description="Custom Grouped Action Demo"/>
</group>
<group id="BaseActionGroup" class="org.jetbrains.tutorials.actions.BaseActionGroup" popup="true"
text="ActionGroup Demo" description="Extending AnAction Demo">
<add-to-group group-id="ToolsMenu" anchor="first"/>
</group>
<action class="org.jetbrains.tutorials.actions.GroupedAction" id="org.jetbrains.tutorials.actions.GroupedAction"
text="Grouped Action" description="Grouped Action Demo">
</action>
</group>
<group id="CustomDefaultActionGroup" class="org.jetbrains.tutorials.actions.CustomDefaultActionGroup" popup="true"
text="DefaultActionGroup Inheritor" description="Default Action Group Demo">
<add-to-group group-id="ToolsMenu" anchor="last"/>
<action class="org.jetbrains.tutorials.actions.CustomGroupedAction" id="CustomGroupedAction"
text="Custom Grouped Action" description="Custom Grouped Action Demo"/>
</group>
<group id="BaseActionGroup" class="org.jetbrains.tutorials.actions.BaseActionGroup" popup="true"
text="ActionGroup Demo" description="Extending AnAction Demo">
<add-to-group group-id="ToolsMenu" anchor="first"/>
</group>
</actions>
</idea-plugin>

View File

@ -9,18 +9,20 @@ import org.jetbrains.annotations.NotNull;
* @author Anna Bulenkova
*/
public class BaseActionGroup extends ActionGroup {
@NotNull
@NotNull
@Override
public AnAction[] getChildren(AnActionEvent anActionEvent) {
return new AnAction[]{new MyAction()};
}
class MyAction extends AnAction {
public MyAction() {
super("Dynamically Added Action");
}
@Override
public AnAction[] getChildren(AnActionEvent anActionEvent) {
return new AnAction[]{new MyAction()};
}
class MyAction extends AnAction {
public MyAction() {
super("Dynamically Added Action");
}
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
//does nothing
}
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
//does nothing
}
}
}

View File

@ -10,11 +10,11 @@ import com.intellij.openapi.editor.Editor;
* @author Anna Bulenkova
*/
public class CustomDefaultActionGroup extends DefaultActionGroup {
@Override
public void update(AnActionEvent event) {
Editor editor = event.getData(CommonDataKeys.EDITOR);
event.getPresentation().setVisible(true);
event.getPresentation().setEnabled(editor != null);
event.getPresentation().setIcon(AllIcons.General.Error);
}
@Override
public void update(AnActionEvent event) {
Editor editor = event.getData(CommonDataKeys.EDITOR);
event.getPresentation().setVisible(true);
event.getPresentation().setEnabled(editor != null);
event.getPresentation().setIcon(AllIcons.General.Error);
}
}

View File

@ -7,8 +7,8 @@ import com.intellij.openapi.actionSystem.AnActionEvent;
* @author Anna Bulenkova
*/
public class CustomGroupedAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
//Does nothing
}
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
//Does nothing
}
}

View File

@ -7,13 +7,13 @@ import com.intellij.openapi.actionSystem.AnActionEvent;
* @author Anna Bulenkova
*/
public class GroupedAction extends AnAction {
@Override
public void update(AnActionEvent event) {
event.getPresentation().setEnabledAndVisible(true);
}
@Override
public void update(AnActionEvent event) {
event.getPresentation().setEnabledAndVisible(true);
}
@Override
public void actionPerformed(AnActionEvent event) {
//Does nothing
}
@Override
public void actionPerformed(AnActionEvent event) {
//Does nothing
}
}

View File

@ -10,20 +10,20 @@ import com.intellij.openapi.ui.Messages;
* @author Anna Bulenkova
*/
public class SimpleAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
Object navigatable = anActionEvent.getData(CommonDataKeys.NAVIGATABLE);
if (navigatable != null) {
Messages.showDialog(navigatable.toString(), "Selected Element:", new String[]{"OK"}, -1, null);
}
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
Object navigatable = anActionEvent.getData(CommonDataKeys.NAVIGATABLE);
if (navigatable != null) {
Messages.showDialog(navigatable.toString(), "Selected Element:", new String[]{"OK"}, -1, null);
}
}
@Override
public void update(AnActionEvent anActionEvent) {
final Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
if (project != null)
return;
Object navigatable = anActionEvent.getData(CommonDataKeys.NAVIGATABLE);
anActionEvent.getPresentation().setVisible(navigatable != null);
}
@Override
public void update(AnActionEvent anActionEvent) {
final Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
if (project != null)
return;
Object navigatable = anActionEvent.getData(CommonDataKeys.NAVIGATABLE);
anActionEvent.getPresentation().setVisible(navigatable != null);
}
}

View File

@ -1,30 +1,30 @@
<idea-plugin version="2" url="www.jetbrains.com">
<id>org.jetbrains.tutorials.run.configuration</id>
<name>Run Configuration</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<id>org.jetbrains.tutorials.run.configuration</id>
<name>Run Configuration</name>
<version>1.0</version>
<vendor email="support@jetbrains.com" url="http://www.jetbrains.com">JetBrains</vendor>
<description>Illustration of working with run configurations</description>
<description>Illustration of working with run configurations</description>
<change-notes>Initial commit</change-notes>
<change-notes>Initial commit</change-notes>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<depends>com.intellij.modules.lang</depends>
<extensions defaultExtensionNs="com.intellij">
<configurationType implementation="org.jetbrains.tutorials.run.configuration.DemoRunConfigurationType"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<configurationType implementation="org.jetbrains.tutorials.run.configuration.DemoRunConfigurationType"/>
</extensions>
<application-components>
<!-- Add your application components here -->
</application-components>
<application-components>
<!-- Add your application components here -->
</application-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<actions>
</actions>
<actions>
</actions>
</idea-plugin>

View File

@ -9,19 +9,19 @@ import com.intellij.openapi.project.Project;
* @author Anna Bulenkova
*/
public class DemoConfigurationFactory extends ConfigurationFactory {
private static final String FACTORY_NAME = "Demo configuration factory";
private static final String FACTORY_NAME = "Demo configuration factory";
protected DemoConfigurationFactory(ConfigurationType type) {
super(type);
}
protected DemoConfigurationFactory(ConfigurationType type) {
super(type);
}
@Override
public RunConfiguration createTemplateConfiguration(Project project) {
return new DemoRunConfiguration(project, this, "Demo");
}
@Override
public RunConfiguration createTemplateConfiguration(Project project) {
return new DemoRunConfiguration(project, this, "Demo");
}
@Override
public String getName() {
return FACTORY_NAME;
}
@Override
public String getName() {
return FACTORY_NAME;
}
}

View File

@ -13,24 +13,25 @@ import org.jetbrains.annotations.Nullable;
* @author Anna Bulenkova
*/
public class DemoRunConfiguration extends RunConfigurationBase {
protected DemoRunConfiguration(Project project, ConfigurationFactory factory, String name) {
super(project, factory, name);
}
protected DemoRunConfiguration(Project project, ConfigurationFactory factory, String name) {
super(project, factory, name);
}
@NotNull
@Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new DemoSettingsEditor();
}
@NotNull
@Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new DemoSettingsEditor();
}
@Override
public void checkConfiguration() throws RuntimeConfigurationException {
@Override
public void checkConfiguration() throws RuntimeConfigurationException {
}
}
@Nullable
@Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException {
return null;
}
@Nullable
@Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws
ExecutionException {
return null;
}
}

View File

@ -11,29 +11,29 @@ import javax.swing.*;
* @author Anna Bulenkova
*/
public class DemoRunConfigurationType implements ConfigurationType {
@Override
public String getDisplayName() {
return "Demo";
}
@Override
public String getDisplayName() {
return "Demo";
}
@Override
public String getConfigurationTypeDescription() {
return "Demo Run Configuration Type";
}
@Override
public String getConfigurationTypeDescription() {
return "Demo Run Configuration Type";
}
@Override
public Icon getIcon() {
return AllIcons.General.Information;
}
@Override
public Icon getIcon() {
return AllIcons.General.Information;
}
@NotNull
@Override
public String getId() {
return "DEMO_RUN_CONFIGURATION";
}
@NotNull
@Override
public String getId() {
return "DEMO_RUN_CONFIGURATION";
}
@Override
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{new DemoConfigurationFactory(this)};
}
@Override
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{new DemoConfigurationFactory(this)};
}
}

View File

@ -17,28 +17,28 @@ import javax.swing.*;
* @author Anna Bulenkova
*/
public class DemoSettingsEditor extends SettingsEditor<DemoRunConfiguration> {
private JPanel myPanel;
private LabeledComponent<ComponentWithBrowseButton> myMainClass;
private JPanel myPanel;
private LabeledComponent<ComponentWithBrowseButton> myMainClass;
@Override
protected void resetEditorFrom(DemoRunConfiguration demoRunConfiguration) {
@Override
protected void resetEditorFrom(DemoRunConfiguration demoRunConfiguration) {
}
}
@Override
protected void applyEditorTo(DemoRunConfiguration demoRunConfiguration) throws ConfigurationException {
@Override
protected void applyEditorTo(DemoRunConfiguration demoRunConfiguration) throws ConfigurationException {
}
}
@NotNull
@Override
protected JComponent createEditor() {
return myPanel;
}
@NotNull
@Override
protected JComponent createEditor() {
return myPanel;
}
private void createUIComponents() {
myMainClass = new LabeledComponent<ComponentWithBrowseButton>();
myMainClass.setComponent(new TextFieldWithBrowseButton());
}
private void createUIComponents() {
myMainClass = new LabeledComponent<ComponentWithBrowseButton>();
myMainClass.setComponent(new TextFieldWithBrowseButton());
}
}

View File

@ -1,15 +1,15 @@
// This is a generated file. Not intended for manual editing.
package com.simpleplugin.parser;
import com.intellij.lang.ASTNode;
import com.intellij.lang.LightPsiParser;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiBuilder.Marker;
import static com.simpleplugin.psi.SimpleTypes.*;
import static com.intellij.lang.parser.GeneratedParserUtilBase.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.lang.ASTNode;
import com.intellij.psi.tree.TokenSet;
import com.intellij.lang.PsiParser;
import com.intellij.lang.LightPsiParser;
import com.intellij.psi.tree.IElementType;
import static com.intellij.lang.parser.GeneratedParserUtilBase.*;
import static com.simpleplugin.psi.SimpleTypes.*;
@SuppressWarnings({"SimplifiableIfStatement", "UnusedAssignment"})
public class SimpleParser implements PsiParser, LightPsiParser {
@ -25,8 +25,7 @@ public class SimpleParser implements PsiParser, LightPsiParser {
Marker m = enter_section_(b, 0, _COLLAPSE_, null);
if (t == PROPERTY) {
r = property(b, 0);
}
else {
} else {
r = parse_root_(t, b, 0);
}
exit_section_(b, 0, m, t, r, true, TRUE_CONDITION);

View File

@ -1,10 +1,8 @@
// This is a generated file. Not intended for manual editing.
package com.simpleplugin.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement;
public interface SimpleProperty extends SimpleNamedElement {

View File

@ -1,10 +1,10 @@
// This is a generated file. Not intended for manual editing.
package com.simpleplugin.psi;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.PsiElement;
import com.intellij.lang.ASTNode;
import com.simpleplugin.psi.impl.*;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.simpleplugin.psi.impl.SimplePropertyImpl;
public interface SimpleTypes {
@ -19,7 +19,7 @@ public interface SimpleTypes {
class Factory {
public static PsiElement createElement(ASTNode node) {
IElementType type = node.getElementType();
if (type == PROPERTY) {
if (type == PROPERTY) {
return new SimplePropertyImpl(node);
}
throw new AssertionError("Unknown element type: " + type);

View File

@ -1,9 +1,9 @@
// This is a generated file. Not intended for manual editing.
package com.simpleplugin.psi;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import org.jetbrains.annotations.NotNull;
public class SimpleVisitor extends PsiElementVisitor {

View File

@ -1,15 +1,13 @@
// This is a generated file. Not intended for manual editing.
package com.simpleplugin.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.simpleplugin.psi.SimpleTypes.*;
import com.simpleplugin.psi.*;
import com.intellij.navigation.ItemPresentation;
import com.simpleplugin.psi.SimpleProperty;
import com.simpleplugin.psi.SimpleVisitor;
import org.jetbrains.annotations.NotNull;
public class SimplePropertyImpl extends SimpleNamedElementImpl implements SimpleProperty {
@ -18,7 +16,7 @@ public class SimplePropertyImpl extends SimpleNamedElementImpl implements Simple
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof SimpleVisitor) ((SimpleVisitor)visitor).visitProperty(this);
if (visitor instanceof SimpleVisitor) ((SimpleVisitor) visitor).visitProperty(this);
else super.accept(visitor);
}

View File

@ -38,23 +38,25 @@
<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
<fileTypeFactory implementation="com.simpleplugin.SimpleFileTypeFactory"/>
<lang.parserDefinition language="Simple" implementationClass="com.simpleplugin.SimpleParserDefinition"/>
<lang.syntaxHighlighterFactory key="Simple" language="Simple" implementationClass="com.simpleplugin.SimpleSyntaxHighlighterFactory"/>
<colorSettingsPage implementation="com.simpleplugin.SimpleColorSettingsPage"/>
<annotator language="JAVA" implementationClass="com.simpleplugin.SimpleAnnotator"/>
<codeInsight.lineMarkerProvider language="JAVA" implementationClass="com.simpleplugin.SimpleLineMarkerProvider"/>
<completion.contributor language="Simple" implementationClass="com.simpleplugin.SimpleCompletionContributor"/>
<psi.referenceContributor implementation="com.simpleplugin.SimpleReferenceContributor"/>
<lang.findUsagesProvider language="Simple" implementationClass="com.simpleplugin.SimpleFindUsagesProvider"/>
<lang.refactoringSupport language="Simple" implementationClass="com.simpleplugin.SimpleRefactoringSupportProvider"/>
<lang.foldingBuilder language="JAVA" implementationClass="com.simpleplugin.SimpleFoldingBuilder"/>
<gotoSymbolContributor implementation="com.simpleplugin.SimpleChooseByNameContributor"/>
<lang.psiStructureViewFactory language="Simple" implementationClass="com.simpleplugin.SimpleStructureViewFactory"/>
<lang.formatter language="Simple" implementationClass="com.simpleplugin.SimpleFormattingModelBuilder"/>
<codeStyleSettingsProvider implementation="com.simpleplugin.SimpleCodeStyleSettingsProvider"/>
<langCodeStyleSettingsProvider implementation="com.simpleplugin.SimpleLanguageCodeStyleSettingsProvider"/>
<lang.commenter language="Simple" implementationClass="com.simpleplugin.SimpleCommenter"/>
<todoIndexer filetype="Simple file" implementationClass="com.simpleplugin.SimpleTodoIndexer"/>
<fileTypeFactory implementation="com.simpleplugin.SimpleFileTypeFactory"/>
<lang.parserDefinition language="Simple" implementationClass="com.simpleplugin.SimpleParserDefinition"/>
<lang.syntaxHighlighterFactory key="Simple"
language="Simple"
implementationClass="com.simpleplugin.SimpleSyntaxHighlighterFactory"/>
<colorSettingsPage implementation="com.simpleplugin.SimpleColorSettingsPage"/>
<annotator language="JAVA" implementationClass="com.simpleplugin.SimpleAnnotator"/>
<codeInsight.lineMarkerProvider language="JAVA" implementationClass="com.simpleplugin.SimpleLineMarkerProvider"/>
<completion.contributor language="Simple" implementationClass="com.simpleplugin.SimpleCompletionContributor"/>
<psi.referenceContributor implementation="com.simpleplugin.SimpleReferenceContributor"/>
<lang.findUsagesProvider language="Simple" implementationClass="com.simpleplugin.SimpleFindUsagesProvider"/>
<lang.refactoringSupport language="Simple" implementationClass="com.simpleplugin.SimpleRefactoringSupportProvider"/>
<lang.foldingBuilder language="JAVA" implementationClass="com.simpleplugin.SimpleFoldingBuilder"/>
<gotoSymbolContributor implementation="com.simpleplugin.SimpleChooseByNameContributor"/>
<lang.psiStructureViewFactory language="Simple" implementationClass="com.simpleplugin.SimpleStructureViewFactory"/>
<lang.formatter language="Simple" implementationClass="com.simpleplugin.SimpleFormattingModelBuilder"/>
<codeStyleSettingsProvider implementation="com.simpleplugin.SimpleCodeStyleSettingsProvider"/>
<langCodeStyleSettingsProvider implementation="com.simpleplugin.SimpleLanguageCodeStyleSettingsProvider"/>
<lang.commenter language="Simple" implementationClass="com.simpleplugin.SimpleCommenter"/>
<todoIndexer filetype="Simple file" implementationClass="com.simpleplugin.SimpleTodoIndexer"/>
</extensions>
</idea-plugin>

View File

@ -4,7 +4,7 @@ import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
@ -27,73 +27,76 @@ import org.jetbrains.annotations.NotNull;
import java.util.Collection;
class CreatePropertyQuickFix extends BaseIntentionAction {
private String key;
private String key;
CreatePropertyQuickFix(String key) {
this.key = key;
}
CreatePropertyQuickFix(String key) {
this.key = key;
}
@NotNull
@Override
public String getText() {
return "Create property";
}
@NotNull
@Override
public String getText() {
return "Create property";
}
@NotNull
@Override
public String getFamilyName() {
return "Simple properties";
}
@NotNull
@Override
public String getFamilyName() {
return "Simple properties";
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return true;
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return true;
}
@Override
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) throws IncorrectOperationException {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, SimpleFileType.INSTANCE,
GlobalSearchScope.allScope(project));
if (virtualFiles.size() == 1) {
createProperty(project, virtualFiles.iterator().next());
} else {
final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileDescriptor(SimpleFileType.INSTANCE);
descriptor.setRoots(project.getBaseDir());
final VirtualFile file = FileChooser.chooseFile(descriptor, project, null);
if (file != null) {
createProperty(project, file);
}
}
}
});
}
@Override
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) throws
IncorrectOperationException {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, SimpleFileType.INSTANCE,
GlobalSearchScope.allScope(project));
if (virtualFiles.size() == 1) {
createProperty(project, virtualFiles.iterator().next());
} else {
final FileChooserDescriptor descriptor =
FileChooserDescriptorFactory.createSingleFileDescriptor(SimpleFileType.INSTANCE);
descriptor.setRoots(project.getBaseDir());
final VirtualFile file = FileChooser.chooseFile(descriptor, project, null);
if (file != null) {
createProperty(project, file);
}
}
}
});
}
private void createProperty(final Project project, final VirtualFile file) {
new WriteCommandAction.Simple(project) {
@Override
public void run() {
SimpleFile simpleFile = (SimpleFile) PsiManager.getInstance(project).findFile(file);
ASTNode lastChildNode = simpleFile.getNode().getLastChildNode();
if (lastChildNode != null && !lastChildNode.getElementType().equals(SimpleTypes.CRLF)) {
simpleFile.getNode().addChild(SimpleElementFactory.createCRLF(project).getNode());
}
// IMPORTANT: change spaces to escaped spaces or the new node will only have the first word for the key
SimpleProperty property = SimpleElementFactory.createProperty(project, key.replaceAll(" ", "\\\\ "), "");
simpleFile.getNode().addChild(property.getNode());
((Navigatable) property.getLastChild().getNavigationElement()).navigate(true);
FileEditorManager.getInstance(project).getSelectedTextEditor().getCaretModel().
moveCaretRelatively(2, 0, false, false, false);
private void createProperty(final Project project, final VirtualFile file) {
new WriteCommandAction.Simple(project) {
@Override
public void run() {
SimpleFile simpleFile = (SimpleFile) PsiManager.getInstance(project).findFile(file);
ASTNode lastChildNode = simpleFile.getNode().getLastChildNode();
if (lastChildNode != null && !lastChildNode.getElementType().equals(SimpleTypes.CRLF)) {
simpleFile.getNode().addChild(SimpleElementFactory.createCRLF(project).getNode());
}
// IMPORTANT: change spaces to escaped spaces or the new node will only have the first word for the key
SimpleProperty property = SimpleElementFactory.createProperty(project, key.replaceAll(" ", "\\\\ "), "");
simpleFile.getNode().addChild(property.getNode());
((Navigatable) property.getLastChild().getNavigationElement()).navigate(true);
FileEditorManager.getInstance(project).getSelectedTextEditor().getCaretModel().
moveCaretRelatively(2, 0, false, false, false);
// almost the same thing but manipulating plain text of the document instead of PSI
// almost the same thing but manipulating plain text of the document instead of PSI
// FileEditorManager.getInstance(project).openFile(file, true);
// final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
// final Document document = editor.getDocument();
// document.insertString(document.getTextLength(), "\n" + key.replaceAll(" ", "\\\\ ") + " = ");
// editor.getCaretModel().getPrimaryCaret().moveToOffset(document.getTextLength());
}
}.execute();
}
}
}.execute();
}
}

View File

@ -14,28 +14,28 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
public class SimpleAnnotator implements Annotator {
@Override
public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof PsiLiteralExpression) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
String value = literalExpression.getValue() instanceof String ? (String)literalExpression.getValue() : null;
@Override
public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof PsiLiteralExpression) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
if (value != null && value.startsWith("simple"+":")) {
Project project = element.getProject();
String key = value.substring(7);
List<SimpleProperty> properties = SimpleUtil.findProperties(project, key);
if (properties.size() == 1) {
TextRange range = new TextRange(element.getTextRange().getStartOffset() + 7,
element.getTextRange().getStartOffset() + 7);
Annotation annotation = holder.createInfoAnnotation(range, null);
annotation.setTextAttributes(DefaultLanguageHighlighterColors.LINE_COMMENT);
} else if (properties.size() == 0) {
TextRange range = new TextRange(element.getTextRange().getStartOffset() + 8,
element.getTextRange().getEndOffset());
holder.createErrorAnnotation(range, "Unresolved property").
registerFix(new CreatePropertyQuickFix(key));
}
}
if (value != null && value.startsWith("simple" + ":")) {
Project project = element.getProject();
String key = value.substring(7);
List<SimpleProperty> properties = SimpleUtil.findProperties(project, key);
if (properties.size() == 1) {
TextRange range = new TextRange(element.getTextRange().getStartOffset() + 7,
element.getTextRange().getStartOffset() + 7);
Annotation annotation = holder.createInfoAnnotation(range, null);
annotation.setTextAttributes(DefaultLanguageHighlighterColors.LINE_COMMENT);
} else if (properties.size() == 0) {
TextRange range = new TextRange(element.getTextRange().getStartOffset() + 8,
element.getTextRange().getEndOffset());
holder.createErrorAnnotation(range, "Unresolved property").
registerFix(new CreatePropertyQuickFix(key));
}
}
}
}
}

View File

@ -12,46 +12,46 @@ import java.util.ArrayList;
import java.util.List;
public class SimpleBlock extends AbstractBlock {
private SpacingBuilder spacingBuilder;
private SpacingBuilder spacingBuilder;
protected SimpleBlock(@NotNull ASTNode node, @Nullable Wrap wrap, @Nullable Alignment alignment,
SpacingBuilder spacingBuilder) {
super(node, wrap, alignment);
this.spacingBuilder = spacingBuilder;
}
protected SimpleBlock(@NotNull ASTNode node, @Nullable Wrap wrap, @Nullable Alignment alignment,
SpacingBuilder spacingBuilder) {
super(node, wrap, alignment);
this.spacingBuilder = spacingBuilder;
}
@Override
protected List<Block> buildChildren() {
List<Block> blocks = new ArrayList<Block>();
ASTNode child = myNode.getFirstChildNode();
ASTNode previousChild = null;
while (child != null) {
if (child.getElementType() != TokenType.WHITE_SPACE &&
(previousChild == null || previousChild.getElementType() != SimpleTypes.CRLF ||
child.getElementType() != SimpleTypes.CRLF)) {
Block block = new SimpleBlock(child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(),
spacingBuilder);
blocks.add(block);
}
previousChild = child;
child = child.getTreeNext();
}
return blocks;
@Override
protected List<Block> buildChildren() {
List<Block> blocks = new ArrayList<Block>();
ASTNode child = myNode.getFirstChildNode();
ASTNode previousChild = null;
while (child != null) {
if (child.getElementType() != TokenType.WHITE_SPACE &&
(previousChild == null || previousChild.getElementType() != SimpleTypes.CRLF ||
child.getElementType() != SimpleTypes.CRLF)) {
Block block = new SimpleBlock(child, Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment(),
spacingBuilder);
blocks.add(block);
}
previousChild = child;
child = child.getTreeNext();
}
return blocks;
}
@Override
public Indent getIndent() {
return Indent.getNoneIndent();
}
@Override
public Indent getIndent() {
return Indent.getNoneIndent();
}
@Nullable
@Override
public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) {
return spacingBuilder.getSpacing(this, child1, child2);
}
@Nullable
@Override
public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) {
return spacingBuilder.getSpacing(this, child1, child2);
}
@Override
public boolean isLeaf() {
return myNode.getFirstChildNode() == null;
}
@Override
public boolean isLeaf() {
return myNode.getFirstChildNode() == null;
}
}

View File

@ -10,24 +10,24 @@ import java.util.ArrayList;
import java.util.List;
public class SimpleChooseByNameContributor implements ChooseByNameContributor {
@NotNull
@Override
public String[] getNames(Project project, boolean includeNonProjectItems) {
List<SimpleProperty> properties = SimpleUtil.findProperties(project);
List<String> names = new ArrayList<String>(properties.size());
for (SimpleProperty property : properties) {
if (property.getKey() != null && property.getKey().length() > 0) {
names.add(property.getKey());
}
}
return names.toArray(new String[names.size()]);
@NotNull
@Override
public String[] getNames(Project project, boolean includeNonProjectItems) {
List<SimpleProperty> properties = SimpleUtil.findProperties(project);
List<String> names = new ArrayList<String>(properties.size());
for (SimpleProperty property : properties) {
if (property.getKey() != null && property.getKey().length() > 0) {
names.add(property.getKey());
}
}
return names.toArray(new String[names.size()]);
}
@NotNull
@Override
public NavigationItem[] getItemsByName(String name, String pattern, Project project, boolean includeNonProjectItems) {
// todo include non project items
List<SimpleProperty> properties = SimpleUtil.findProperties(project, name);
return properties.toArray(new NavigationItem[properties.size()]);
}
@NotNull
@Override
public NavigationItem[] getItemsByName(String name, String pattern, Project project, boolean includeNonProjectItems) {
// todo include non project items
List<SimpleProperty> properties = SimpleUtil.findProperties(project, name);
return properties.toArray(new NavigationItem[properties.size()]);
}
}

View File

@ -4,7 +4,7 @@ import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CustomCodeStyleSettings;
public class SimpleCodeStyleSettings extends CustomCodeStyleSettings {
public SimpleCodeStyleSettings(CodeStyleSettings settings) {
super("SimpleCodeStyleSettings", settings);
}
public SimpleCodeStyleSettings(CodeStyleSettings settings) {
super("SimpleCodeStyleSettings", settings);
}
}

View File

@ -11,37 +11,37 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SimpleCodeStyleSettingsProvider extends CodeStyleSettingsProvider {
@Override
public CustomCodeStyleSettings createCustomSettings(CodeStyleSettings settings) {
return new SimpleCodeStyleSettings(settings);
}
@Override
public CustomCodeStyleSettings createCustomSettings(CodeStyleSettings settings) {
return new SimpleCodeStyleSettings(settings);
}
@Nullable
@Override
public String getConfigurableDisplayName() {
return "Simple";
}
@Nullable
@Override
public String getConfigurableDisplayName() {
return "Simple";
}
@NotNull
@Override
public Configurable createSettingsPage(CodeStyleSettings settings, CodeStyleSettings originalSettings) {
return new CodeStyleAbstractConfigurable(settings, originalSettings, "Simple") {
@Override
protected CodeStyleAbstractPanel createPanel(CodeStyleSettings settings) {
return new SimpleCodeStyleMainPanel(getCurrentSettings(), settings);
}
@NotNull
@Override
public Configurable createSettingsPage(CodeStyleSettings settings, CodeStyleSettings originalSettings) {
return new CodeStyleAbstractConfigurable(settings, originalSettings, "Simple") {
@Override
protected CodeStyleAbstractPanel createPanel(CodeStyleSettings settings) {
return new SimpleCodeStyleMainPanel(getCurrentSettings(), settings);
}
@Nullable
@Override
public String getHelpTopic() {
return null;
}
};
}
@Nullable
@Override
public String getHelpTopic() {
return null;
}
};
}
private static class SimpleCodeStyleMainPanel extends TabbedLanguageCodeStylePanel {
public SimpleCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) {
super(SimpleLanguage.INSTANCE, currentSettings, settings);
}
private static class SimpleCodeStyleMainPanel extends TabbedLanguageCodeStylePanel {
public SimpleCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) {
super(SimpleLanguage.INSTANCE, currentSettings, settings);
}
}
}

View File

@ -12,62 +12,62 @@ import javax.swing.*;
import java.util.Map;
public class SimpleColorSettingsPage implements ColorSettingsPage {
private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{
new AttributesDescriptor("Key", SimpleSyntaxHighlighter.KEY),
new AttributesDescriptor("Separator", SimpleSyntaxHighlighter.SEPARATOR),
new AttributesDescriptor("Value", SimpleSyntaxHighlighter.VALUE),
};
private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{
new AttributesDescriptor("Key", SimpleSyntaxHighlighter.KEY),
new AttributesDescriptor("Separator", SimpleSyntaxHighlighter.SEPARATOR),
new AttributesDescriptor("Value", SimpleSyntaxHighlighter.VALUE),
};
@Nullable
@Override
public Icon getIcon() {
return SimpleIcons.FILE;
}
@Nullable
@Override
public Icon getIcon() {
return SimpleIcons.FILE;
}
@NotNull
@Override
public SyntaxHighlighter getHighlighter() {
return new SimpleSyntaxHighlighter();
}
@NotNull
@Override
public SyntaxHighlighter getHighlighter() {
return new SimpleSyntaxHighlighter();
}
@NotNull
@Override
public String getDemoText() {
return "# You are reading the \".properties\" entry.\n" +
"! The exclamation mark can also mark text as comments.\n" +
"website = http://en.wikipedia.org/\n" +
"language = English\n" +
"# The backslash below tells the application to continue reading\n" +
"# the value onto the next line.\n" +
"message = Welcome to \\\n" +
" Wikipedia!\n" +
"# Add spaces to the key\n" +
"key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" +
"# Unicode\n" +
"tab : \\u0009";
}
@NotNull
@Override
public String getDemoText() {
return "# You are reading the \".properties\" entry.\n" +
"! The exclamation mark can also mark text as comments.\n" +
"website = http://en.wikipedia.org/\n" +
"language = English\n" +
"# The backslash below tells the application to continue reading\n" +
"# the value onto the next line.\n" +
"message = Welcome to \\\n" +
" Wikipedia!\n" +
"# Add spaces to the key\n" +
"key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" +
"# Unicode\n" +
"tab : \\u0009";
}
@Nullable
@Override
public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() {
return null;
}
@Nullable
@Override
public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() {
return null;
}
@NotNull
@Override
public AttributesDescriptor[] getAttributeDescriptors() {
return DESCRIPTORS;
}
@NotNull
@Override
public AttributesDescriptor[] getAttributeDescriptors() {
return DESCRIPTORS;
}
@NotNull
@Override
public ColorDescriptor[] getColorDescriptors() {
return ColorDescriptor.EMPTY_ARRAY;
}
@NotNull
@Override
public ColorDescriptor[] getColorDescriptors() {
return ColorDescriptor.EMPTY_ARRAY;
}
@NotNull
@Override
public String getDisplayName() {
return "Simple";
}
@NotNull
@Override
public String getDisplayName() {
return "Simple";
}
}

View File

@ -4,33 +4,33 @@ import com.intellij.lang.Commenter;
import org.jetbrains.annotations.Nullable;
public class SimpleCommenter implements Commenter {
@Nullable
@Override
public String getLineCommentPrefix() {
return "#";
}
@Nullable
@Override
public String getLineCommentPrefix() {
return "#";
}
@Nullable
@Override
public String getBlockCommentPrefix() {
return "";
}
@Nullable
@Override
public String getBlockCommentPrefix() {
return "";
}
@Nullable
@Override
public String getBlockCommentSuffix() {
return null;
}
@Nullable
@Override
public String getBlockCommentSuffix() {
return null;
}
@Nullable
@Override
public String getCommentedBlockCommentPrefix() {
return null;
}
@Nullable
@Override
public String getCommentedBlockCommentPrefix() {
return null;
}
@Nullable
@Override
public String getCommentedBlockCommentSuffix() {
return null;
}
@Nullable
@Override
public String getCommentedBlockCommentSuffix() {
return null;
}
}

View File

@ -8,16 +8,16 @@ import com.simpleplugin.psi.SimpleTypes;
import org.jetbrains.annotations.NotNull;
public class SimpleCompletionContributor extends CompletionContributor {
public SimpleCompletionContributor() {
extend(CompletionType.BASIC,
PlatformPatterns.psiElement(SimpleTypes.VALUE).withLanguage(SimpleLanguage.INSTANCE),
new CompletionProvider<CompletionParameters>() {
public void addCompletions(@NotNull CompletionParameters parameters,
ProcessingContext context,
@NotNull CompletionResultSet resultSet) {
resultSet.addElement(LookupElementBuilder.create("Hello"));
}
}
);
}
public SimpleCompletionContributor() {
extend(CompletionType.BASIC,
PlatformPatterns.psiElement(SimpleTypes.VALUE).withLanguage(SimpleLanguage.INSTANCE),
new CompletionProvider<CompletionParameters>() {
public void addCompletions(@NotNull CompletionParameters parameters,
ProcessingContext context,
@NotNull CompletionResultSet resultSet) {
resultSet.addElement(LookupElementBuilder.create("Hello"));
}
}
);
}
}

View File

@ -7,33 +7,33 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class SimpleFileType extends LanguageFileType {
public static final SimpleFileType INSTANCE = new SimpleFileType();
public static final SimpleFileType INSTANCE = new SimpleFileType();
private SimpleFileType() {
super(SimpleLanguage.INSTANCE);
}
private SimpleFileType() {
super(SimpleLanguage.INSTANCE);
}
@NotNull
@Override
public String getName() {
return "Simple file";
}
@NotNull
@Override
public String getName() {
return "Simple file";
}
@NotNull
@Override
public String getDescription() {
return "Simple language file";
}
@NotNull
@Override
public String getDescription() {
return "Simple language file";
}
@NotNull
@Override
public String getDefaultExtension() {
return "simple";
}
@NotNull
@Override
public String getDefaultExtension() {
return "simple";
}
@Nullable
@Override
public Icon getIcon() {
return SimpleIcons.FILE;
}
@Nullable
@Override
public Icon getIcon() {
return SimpleIcons.FILE;
}
}

View File

@ -4,9 +4,9 @@ import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import org.jetbrains.annotations.NotNull;
public class SimpleFileTypeFactory extends FileTypeFactory{
@Override
public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(SimpleFileType.INSTANCE, "simple");
}
public class SimpleFileTypeFactory extends FileTypeFactory {
@Override
public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(SimpleFileType.INSTANCE, "simple");
}
}

View File

@ -6,14 +6,14 @@ import com.intellij.psi.impl.cache.impl.OccurrenceConsumer;
import com.intellij.psi.search.UsageSearchContext;
public class SimpleFilterLexer extends BaseFilterLexer {
public SimpleFilterLexer(final Lexer originalLexer, final OccurrenceConsumer table) {
super(originalLexer, table);
}
public SimpleFilterLexer(final Lexer originalLexer, final OccurrenceConsumer table) {
super(originalLexer, table);
}
@Override
public void advance() {
scanWordsInToken(UsageSearchContext.IN_COMMENTS, false, false);
advanceTodoItemCountsInToken();
myDelegate.advance();
}
@Override
public void advance() {
scanWordsInToken(UsageSearchContext.IN_COMMENTS, false, false);
advanceTodoItemCountsInToken();
myDelegate.advance();
}
}

View File

@ -12,51 +12,53 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SimpleFindUsagesProvider implements FindUsagesProvider {
@Nullable
@Override
public WordsScanner getWordsScanner() {
return new DefaultWordsScanner(new SimpleLexerAdapter(),
TokenSet.create(SimpleTypes.KEY), TokenSet.create(SimpleTypes.COMMENT), TokenSet.EMPTY);
}
@Nullable
@Override
public WordsScanner getWordsScanner() {
return new DefaultWordsScanner(new SimpleLexerAdapter(),
TokenSet.create(SimpleTypes.KEY),
TokenSet.create(SimpleTypes.COMMENT),
TokenSet.EMPTY);
}
@Override
public boolean canFindUsagesFor(@NotNull PsiElement psiElement) {
return psiElement instanceof PsiNamedElement;
}
@Override
public boolean canFindUsagesFor(@NotNull PsiElement psiElement) {
return psiElement instanceof PsiNamedElement;
}
@Nullable
@Override
public String getHelpId(@NotNull PsiElement psiElement) {
return null;
}
@Nullable
@Override
public String getHelpId(@NotNull PsiElement psiElement) {
return null;
}
@NotNull
@Override
public String getType(@NotNull PsiElement element) {
if (element instanceof SimpleProperty) {
return "simple property";
} else {
return "";
}
@NotNull
@Override
public String getType(@NotNull PsiElement element) {
if (element instanceof SimpleProperty) {
return "simple property";
} else {
return "";
}
}
@NotNull
@Override
public String getDescriptiveName(@NotNull PsiElement element) {
if (element instanceof SimpleProperty) {
return ((SimpleProperty) element).getKey();
} else {
return "";
}
@NotNull
@Override
public String getDescriptiveName(@NotNull PsiElement element) {
if (element instanceof SimpleProperty) {
return ((SimpleProperty) element).getKey();
} else {
return "";
}
}
@NotNull
@Override
public String getNodeText(@NotNull PsiElement element, boolean useFullName) {
if (element instanceof SimpleProperty) {
return ((SimpleProperty) element).getKey() + ":" + ((SimpleProperty) element).getValue();
} else {
return "";
}
@NotNull
@Override
public String getNodeText(@NotNull PsiElement element, boolean useFullName) {
if (element instanceof SimpleProperty) {
return ((SimpleProperty) element).getKey() + ":" + ((SimpleProperty) element).getValue();
} else {
return "";
}
}
}

View File

@ -19,47 +19,50 @@ import java.util.Collection;
import java.util.List;
public class SimpleFoldingBuilder extends FoldingBuilderEx {
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
FoldingGroup group = FoldingGroup.newGroup("simple");
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
FoldingGroup group = FoldingGroup.newGroup("simple");
List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();
Collection<PsiLiteralExpression> literalExpressions = PsiTreeUtil.findChildrenOfType(root, PsiLiteralExpression.class);
for (final PsiLiteralExpression literalExpression : literalExpressions) {
String value = literalExpression.getValue() instanceof String ? (String)literalExpression.getValue() : null;
List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();
Collection<PsiLiteralExpression> literalExpressions =
PsiTreeUtil.findChildrenOfType(root, PsiLiteralExpression.class);
for (final PsiLiteralExpression literalExpression : literalExpressions) {
String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
if (value != null && value.startsWith("simple:")) {
Project project = literalExpression.getProject();
String key = value.substring(7);
final List<SimpleProperty> properties = SimpleUtil.findProperties(project, key);
if (properties.size() == 1) {
descriptors.add(new FoldingDescriptor(literalExpression.getNode(),
new TextRange(literalExpression.getTextRange().getStartOffset() + 1,
literalExpression.getTextRange().getEndOffset() - 1), group) {
@Nullable
@Override
public String getPlaceholderText() {
// IMPORTANT: keys can come with no values, so a test for null is needed
// IMPORTANT: Convert embedded \n to backslash n, so that the string will look like it has LF embedded in it and embedded " to escaped "
String valueOf = properties.get(0).getValue();
return valueOf == null ? "" : valueOf.replaceAll("\n","\\n").replaceAll("\"","\\\\\"");
}
});
}
if (value != null && value.startsWith("simple:")) {
Project project = literalExpression.getProject();
String key = value.substring(7);
final List<SimpleProperty> properties = SimpleUtil.findProperties(project, key);
if (properties.size() == 1) {
descriptors.add(new FoldingDescriptor(literalExpression.getNode(),
new TextRange(literalExpression.getTextRange().getStartOffset() + 1,
literalExpression.getTextRange().getEndOffset() - 1),
group) {
@Nullable
@Override
public String getPlaceholderText() {
// IMPORTANT: keys can come with no values, so a test for null is needed
// IMPORTANT: Convert embedded \n to backslash n, so that the string will look like it has LF embedded
// in it and embedded " to escaped "
String valueOf = properties.get(0).getValue();
return valueOf == null ? "" : valueOf.replaceAll("\n", "\\n").replaceAll("\"", "\\\\\"");
}
});
}
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
}
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
@Nullable
@Override
public String getPlaceholderText(@NotNull ASTNode node) {
return "...";
}
@Nullable
@Override
public String getPlaceholderText(@NotNull ASTNode node) {
return "...";
}
@Override
public boolean isCollapsedByDefault(@NotNull ASTNode node) {
return true;
}
@Override
public boolean isCollapsedByDefault(@NotNull ASTNode node) {
return true;
}
}

View File

@ -11,23 +11,30 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SimpleFormattingModelBuilder implements FormattingModelBuilder {
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(),
new SimpleBlock(element.getNode(), Wrap.createWrap(WrapType.NONE, false),
Alignment.createAlignment(), createSpaceBuilder(settings)), settings);
}
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(),
new SimpleBlock(element.getNode(),
Wrap.createWrap(WrapType.NONE,
false),
Alignment.createAlignment(),
createSpaceBuilder(settings)),
settings);
}
private static SpacingBuilder createSpaceBuilder(CodeStyleSettings settings) {
return new SpacingBuilder(settings, SimpleLanguage.INSTANCE).
around(SimpleTypes.SEPARATOR).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS).
before(SimpleTypes.PROPERTY).none();
}
private static SpacingBuilder createSpaceBuilder(CodeStyleSettings settings) {
return new SpacingBuilder(settings, SimpleLanguage.INSTANCE).
around(SimpleTypes.SEPARATOR)
.spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS)
.
before(SimpleTypes.PROPERTY)
.none();
}
@Nullable
@Override
public TextRange getRangeAffectingIndent(PsiFile file, int offset, ASTNode elementAtOffset) {
return null;
}
@Nullable
@Override
public TextRange getRangeAffectingIndent(PsiFile file, int offset, ASTNode elementAtOffset) {
return null;
}
}

View File

@ -5,5 +5,5 @@ import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
public class SimpleIcons {
public static final Icon FILE = IconLoader.getIcon("/com/simpleplugin/icons/jar-gray.png");
public static final Icon FILE = IconLoader.getIcon("/com/simpleplugin/icons/jar-gray.png");
}

View File

@ -6,12 +6,12 @@ import com.intellij.psi.impl.cache.impl.id.LexerBasedIdIndexer;
public class SimpleIdIndexer extends LexerBasedIdIndexer {
public static Lexer createIndexingLexer(OccurrenceConsumer consumer) {
return new SimpleFilterLexer(new SimpleLexerAdapter(), consumer);
}
public static Lexer createIndexingLexer(OccurrenceConsumer consumer) {
return new SimpleFilterLexer(new SimpleLexerAdapter(), consumer);
}
@Override
public Lexer createLexer(final OccurrenceConsumer consumer) {
return createIndexingLexer(consumer);
}
@Override
public Lexer createLexer(final OccurrenceConsumer consumer) {
return createIndexingLexer(consumer);
}
}

View File

@ -3,9 +3,9 @@ package com.simpleplugin;
import com.intellij.lang.Language;
public class SimpleLanguage extends Language {
public static final SimpleLanguage INSTANCE = new SimpleLanguage();
public static final SimpleLanguage INSTANCE = new SimpleLanguage();
private SimpleLanguage() {
super("Simple");
}
private SimpleLanguage() {
super("Simple");
}
}

View File

@ -6,38 +6,38 @@ import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider;
import org.jetbrains.annotations.NotNull;
public class SimpleLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider {
@NotNull
@Override
public Language getLanguage() {
return SimpleLanguage.INSTANCE;
}
@NotNull
@Override
public Language getLanguage() {
return SimpleLanguage.INSTANCE;
}
@Override
public void customizeSettings(@NotNull CodeStyleSettingsCustomizable consumer, @NotNull SettingsType settingsType) {
if (settingsType == SettingsType.SPACING_SETTINGS) {
consumer.showStandardOptions("SPACE_AROUND_ASSIGNMENT_OPERATORS");
consumer.renameStandardOption("SPACE_AROUND_ASSIGNMENT_OPERATORS", "Separator");
} else if (settingsType == SettingsType.BLANK_LINES_SETTINGS) {
consumer.showStandardOptions("KEEP_BLANK_LINES_IN_CODE");
}
@Override
public void customizeSettings(@NotNull CodeStyleSettingsCustomizable consumer, @NotNull SettingsType settingsType) {
if (settingsType == SettingsType.SPACING_SETTINGS) {
consumer.showStandardOptions("SPACE_AROUND_ASSIGNMENT_OPERATORS");
consumer.renameStandardOption("SPACE_AROUND_ASSIGNMENT_OPERATORS", "Separator");
} else if (settingsType == SettingsType.BLANK_LINES_SETTINGS) {
consumer.showStandardOptions("KEEP_BLANK_LINES_IN_CODE");
}
}
@Override
public String getCodeSample(@NotNull SettingsType settingsType) {
return "# You are reading the \".properties\" entry.\n" +
"! The exclamation mark can also mark text as comments.\n" +
"website = http://en.wikipedia.org/\n" +
"\n" +
"\n" +
"\n" +
"language = English\n" +
"# The backslash below tells the application to continue reading\n" +
"# the value onto the next line.\n" +
"message = Welcome to \\\n" +
" Wikipedia!\n" +
"# Add spaces to the key\n" +
"key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" +
"# Unicode\n" +
"tab : \\u0009";
}
@Override
public String getCodeSample(@NotNull SettingsType settingsType) {
return "# You are reading the \".properties\" entry.\n" +
"! The exclamation mark can also mark text as comments.\n" +
"website = http://en.wikipedia.org/\n" +
"\n" +
"\n" +
"\n" +
"language = English\n" +
"# The backslash below tells the application to continue reading\n" +
"# the value onto the next line.\n" +
"message = Welcome to \\\n" +
" Wikipedia!\n" +
"# Add spaces to the key\n" +
"key\\ with\\ spaces = This is the value that could be looked up with the key \"key with spaces\".\n" +
"# Unicode\n" +
"tab : \\u0009";
}
}

View File

@ -3,9 +3,9 @@
package com.simpleplugin;
import com.intellij.lexer.FlexLexer;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.simpleplugin.psi.SimpleTypes;
import com.intellij.psi.TokenType;
/**
@ -15,52 +15,56 @@ import com.intellij.psi.TokenType;
* <tt>/Users/vlad/src/SimplePlugin/src/com/simpleplugin/Simple.flex</tt>
*/
class SimpleLexer implements FlexLexer {
/** initial size of the lookahead buffer */
/**
* initial size of the lookahead buffer
*/
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
/**
* lexical states
*/
public static final int WAITING_VALUE = 2;
public static final int YYINITIAL = 0;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {
0, 0, 1, 1
0, 0, 1, 1
};
/**
* Translates characters to character classes
*/
private static final String ZZ_CMAP_PACKED =
"\11\0\1\3\1\1\1\0\1\6\1\2\22\0\1\5\1\7\1\0"+
"\1\7\26\0\1\10\2\0\1\10\36\0\1\4\uffa3\0";
"\11\0\1\3\1\1\1\0\1\6\1\2\22\0\1\5\1\7\1\0" +
"\1\7\26\0\1\10\2\0\1\10\36\0\1\4\uffa3\0";
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
private static final char[] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final int[] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\2\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7"+
"\1\3\1\7\2\0\1\6";
"\2\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7" +
"\1\3\1\7\2\0\1\6";
private static int [] zzUnpackAction() {
int [] result = new int[14];
private static int[] zzUnpackAction() {
int[] result = new int[14];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
private static int zzUnpackAction(String packed, int offset, int[] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
@ -76,20 +80,20 @@ class SimpleLexer implements FlexLexer {
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final int[] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\11\0\22\0\33\0\44\0\55\0\66\0\77"+
"\0\110\0\121\0\132\0\44\0\121\0\143";
"\0\0\0\11\0\22\0\33\0\44\0\55\0\66\0\77" +
"\0\110\0\121\0\132\0\44\0\121\0\143";
private static int [] zzUnpackRowMap() {
int [] result = new int[14];
private static int[] zzUnpackRowMap() {
int[] result = new int[14];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
private static int zzUnpackRowMap(String packed, int offset, int[] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
@ -103,25 +107,25 @@ class SimpleLexer implements FlexLexer {
/**
* The transition table of the DFA
*/
private static final int [] ZZ_TRANS = zzUnpackTrans();
private static final int[] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 =
"\1\3\3\4\1\5\2\4\1\6\1\7\1\10\2\4"+
"\1\11\1\12\2\13\2\10\1\3\3\0\1\14\2\0"+
"\1\3\2\0\3\4\1\0\2\4\7\0\1\3\3\0"+
"\1\6\2\0\6\6\11\0\1\10\2\0\1\10\1\15"+
"\1\10\1\0\3\10\2\4\1\11\1\15\1\11\1\13"+
"\4\10\1\16\6\10\1\0\2\4\1\13\1\0\2\13"+
"\2\0\2\10\1\0\1\10\1\15\1\10\1\0\2\10";
"\1\3\3\4\1\5\2\4\1\6\1\7\1\10\2\4" +
"\1\11\1\12\2\13\2\10\1\3\3\0\1\14\2\0" +
"\1\3\2\0\3\4\1\0\2\4\7\0\1\3\3\0" +
"\1\6\2\0\6\6\11\0\1\10\2\0\1\10\1\15" +
"\1\10\1\0\3\10\2\4\1\11\1\15\1\11\1\13" +
"\4\10\1\16\6\10\1\0\2\4\1\13\1\0\2\13" +
"\2\0\2\10\1\0\1\10\1\15\1\10\1\0\2\10";
private static int [] zzUnpackTrans() {
int [] result = new int[108];
private static int[] zzUnpackTrans() {
int[] result = new int[108];
int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int zzUnpackTrans(String packed, int offset, int [] result) {
private static int zzUnpackTrans(String packed, int offset, int[] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
@ -145,27 +149,27 @@ class SimpleLexer implements FlexLexer {
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unkown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
"Unkown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final int[] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\2\0\4\1\1\11\4\1\2\0\1\1";
"\2\0\4\1\1\11\4\1\2\0\1\1";
private static int [] zzUnpackAttribute() {
int [] result = new int[14];
private static int[] zzUnpackAttribute() {
int[] result = new int[14];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
private static int zzUnpackAttribute(String packed, int offset, int[] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
@ -177,33 +181,51 @@ class SimpleLexer implements FlexLexer {
return j;
}
/** the current state of the DFA */
/**
* the current state of the DFA
*/
private int zzState;
/** the current lexical state */
/**
* the current lexical state
*/
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
/**
* this buffer contains the current text to be matched and is
* the source of the yytext() string
*/
private CharSequence zzBuffer = "";
/** this buffer may contains the current text array to be matched when it is cheap to acquire it */
/**
* this buffer may contains the current text array to be matched when it is cheap to acquire it
*/
private char[] zzBufferArray;
/** the textposition at the last accepting state */
/**
* the textposition at the last accepting state
*/
private int zzMarkedPos;
/** the textposition at the last state to be included in yytext */
/**
* the textposition at the last state to be included in yytext
*/
private int zzPushbackPos;
/** the current text position in the buffer */
/**
* the current text position in the buffer
*/
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
/**
* startRead marks the beginning of the yytext() string in the buffer
*/
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
/**
* endRead marks the last character in the buffer, that has been read
* from input
*/
private int zzEndRead;
/**
@ -211,10 +233,14 @@ class SimpleLexer implements FlexLexer {
*/
private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */
/**
* zzAtEOF == true <=> the scanner is at the EOF
*/
private boolean zzAtEOF;
/** denotes if the user-EOF-code has already been executed */
/**
* denotes if the user-EOF-code has already been executed
*/
private boolean zzEOFDone;
@ -226,7 +252,7 @@ class SimpleLexer implements FlexLexer {
* Creates a new scanner.
* There is also java.io.Reader version of this constructor.
*
* @param in the java.io.Inputstream to read input from.
* @param in the java.io.Inputstream to read input from.
*/
SimpleLexer(java.io.InputStream in) {
this(new java.io.InputStreamReader(in));
@ -235,35 +261,35 @@ class SimpleLexer implements FlexLexer {
/**
* Unpacks the compressed character translation table.
*
* @param packed the packed character translation table
* @return the unpacked character translation table
* @param packed the packed character translation table
* @return the unpacked character translation table
*/
private static char [] zzUnpackCMap(String packed) {
char [] map = new char[0x10000];
private static char[] zzUnpackCMap(String packed) {
char[] map = new char[0x10000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 36) {
int count = packed.charAt(i++);
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
}
return map;
}
public final int getTokenStart(){
public final int getTokenStart() {
return zzStartRead;
}
public final int getTokenEnd(){
public final int getTokenEnd() {
return getTokenStart() + yylength();
}
public void reset(CharSequence buffer, int start, int end,int initialState){
public void reset(CharSequence buffer, int start, int end, int initialState) {
zzBuffer = buffer;
zzBufferArray = com.intellij.util.text.CharArrayUtil.fromSequenceWithoutCopying(buffer);
zzCurrentPos = zzMarkedPos = zzStartRead = start;
zzPushbackPos = 0;
zzAtEOF = false;
zzAtEOF = false;
zzAtBOL = true;
zzEndRead = end;
yybegin(initialState);
@ -272,9 +298,8 @@ class SimpleLexer implements FlexLexer {
/**
* Refills the input buffer.
*
* @return <code>false</code>, iff there was new input.
*
* @exception java.io.IOException if any I/O-Error occurs
* @return <code>false</code>, iff there was new input.
* @throws java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
return true;
@ -310,16 +335,15 @@ class SimpleLexer implements FlexLexer {
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* <p>
* It is equivalent to yytext().charAt(pos), but faster
*
* @param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* @return the character at position pos
*/
public final char yycharat(int pos) {
return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos);
return zzBufferArray != null ? zzBufferArray[zzStartRead + pos] : zzBuffer.charAt(zzStartRead + pos);
}
@ -327,30 +351,29 @@ class SimpleLexer implements FlexLexer {
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
return zzMarkedPos - zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* <p>
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* <p>
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* @param errorCode the code of the errormessage to display
* @param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
} catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
@ -360,14 +383,14 @@ class SimpleLexer implements FlexLexer {
/**
* Pushes the specified amount of characters back into the input stream.
*
* <p>
* They will be read again by then next call of the scanning method
*
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if ( number > yylength() )
public void yypushback(int number) {
if (number > yylength())
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
@ -390,8 +413,8 @@ class SimpleLexer implements FlexLexer {
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* @return the next token
* @exception java.io.IOException if any I/O-Error occurs
* @return the next token
* @throws java.io.IOException if any I/O-Error occurs
*/
public IElementType advance() throws java.io.IOException {
int zzInput;
@ -403,11 +426,11 @@ class SimpleLexer implements FlexLexer {
int zzEndReadL = zzEndRead;
CharSequence zzBufferL = zzBuffer;
char[] zzBufferArrayL = zzBufferArray;
char [] zzCMapL = ZZ_CMAP;
char[] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
int[] zzTransL = ZZ_TRANS;
int[] zzRowMapL = ZZ_ROWMAP;
int[] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
@ -419,7 +442,8 @@ class SimpleLexer implements FlexLexer {
zzState = ZZ_LEXSTATE[zzLexicalState];
zzForAction: {
zzForAction:
{
while (true) {
if (zzCurrentPosL < zzEndReadL)
@ -427,34 +451,32 @@ class SimpleLexer implements FlexLexer {
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
} else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
} else {
zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++));
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
if ((zzAttributes & 1) == 1) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
if ((zzAttributes & 8) == 8) break zzForAction;
}
}
@ -464,41 +486,53 @@ class SimpleLexer implements FlexLexer {
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 6:
{ yybegin(YYINITIAL); return SimpleTypes.VALUE;
}
case 8: break;
case 5:
{ yybegin(WAITING_VALUE); return SimpleTypes.SEPARATOR;
}
case 9: break;
case 4:
{ yybegin(YYINITIAL); return SimpleTypes.COMMENT;
}
case 10: break;
case 3:
{ return TokenType.BAD_CHARACTER;
}
case 11: break;
case 2:
{ yybegin(YYINITIAL); return TokenType.WHITE_SPACE;
}
case 12: break;
case 7:
{ yybegin(WAITING_VALUE); return TokenType.WHITE_SPACE;
}
case 13: break;
case 1:
{ yybegin(YYINITIAL); return SimpleTypes.KEY;
}
case 14: break;
case 6: {
yybegin(YYINITIAL);
return SimpleTypes.VALUE;
}
case 8:
break;
case 5: {
yybegin(WAITING_VALUE);
return SimpleTypes.SEPARATOR;
}
case 9:
break;
case 4: {
yybegin(YYINITIAL);
return SimpleTypes.COMMENT;
}
case 10:
break;
case 3: {
return TokenType.BAD_CHARACTER;
}
case 11:
break;
case 2: {
yybegin(YYINITIAL);
return TokenType.WHITE_SPACE;
}
case 12:
break;
case 7: {
yybegin(WAITING_VALUE);
return TokenType.WHITE_SPACE;
}
case 13:
break;
case 1: {
yybegin(YYINITIAL);
return SimpleTypes.KEY;
}
case 14:
break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
zzDoEOF();
return null;
}
else {
} else {
zzScanError(ZZ_NO_MATCH);
}
}

View File

@ -5,7 +5,7 @@ import com.intellij.lexer.FlexAdapter;
import java.io.Reader;
public class SimpleLexerAdapter extends FlexAdapter {
public SimpleLexerAdapter() {
super(new SimpleLexer((Reader) null));
}
public SimpleLexerAdapter() {
super(new SimpleLexer((Reader) null));
}
}

View File

@ -13,22 +13,23 @@ import java.util.Collection;
import java.util.List;
public class SimpleLineMarkerProvider extends RelatedItemLineMarkerProvider {
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element, Collection<? super RelatedItemLineMarkerInfo> result) {
if (element instanceof PsiLiteralExpression) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
String value = literalExpression.getValue() instanceof String ? (String)literalExpression.getValue() : null;
if (value != null && value.startsWith("simple"+":")) {
Project project = element.getProject();
final List<SimpleProperty> properties = SimpleUtil.findProperties(project, value.substring(7));
if (properties.size() > 0) {
NavigationGutterIconBuilder<PsiElement> builder =
NavigationGutterIconBuilder.create(SimpleIcons.FILE).
setTargets(properties).
setTooltipText("Navigate to a simple property");
result.add(builder.createLineMarkerInfo(element));
}
}
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element,
Collection<? super RelatedItemLineMarkerInfo> result) {
if (element instanceof PsiLiteralExpression) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
if (value != null && value.startsWith("simple" + ":")) {
Project project = element.getProject();
final List<SimpleProperty> properties = SimpleUtil.findProperties(project, value.substring(7));
if (properties.size() > 0) {
NavigationGutterIconBuilder<PsiElement> builder =
NavigationGutterIconBuilder.create(SimpleIcons.FILE).
setTargets(properties).
setTooltipText("Navigate to a simple property");
result.add(builder.createLineMarkerInfo(element));
}
}
}
}
}

View File

@ -17,53 +17,54 @@ import com.simpleplugin.psi.SimpleFile;
import com.simpleplugin.psi.SimpleTypes;
import org.jetbrains.annotations.NotNull;
public class SimpleParserDefinition implements ParserDefinition{
public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE);
public static final TokenSet COMMENTS = TokenSet.create(SimpleTypes.COMMENT);
public class SimpleParserDefinition implements ParserDefinition {
public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE);
public static final TokenSet COMMENTS = TokenSet.create(SimpleTypes.COMMENT);
public static final IFileElementType FILE = new IFileElementType(Language.<SimpleLanguage>findInstance(SimpleLanguage.class));
public static final IFileElementType FILE =
new IFileElementType(Language.<SimpleLanguage>findInstance(SimpleLanguage.class));
@NotNull
@Override
public Lexer createLexer(Project project) {
return new SimpleLexerAdapter();
}
@NotNull
@Override
public Lexer createLexer(Project project) {
return new SimpleLexerAdapter();
}
@NotNull
public TokenSet getWhitespaceTokens() {
return WHITE_SPACES;
}
@NotNull
public TokenSet getWhitespaceTokens() {
return WHITE_SPACES;
}
@NotNull
public TokenSet getCommentTokens() {
return COMMENTS;
}
@NotNull
public TokenSet getCommentTokens() {
return COMMENTS;
}
@NotNull
public TokenSet getStringLiteralElements() {
return TokenSet.EMPTY;
}
@NotNull
public TokenSet getStringLiteralElements() {
return TokenSet.EMPTY;
}
@NotNull
public PsiParser createParser(final Project project) {
return new SimpleParser();
}
@NotNull
public PsiParser createParser(final Project project) {
return new SimpleParser();
}
@Override
public IFileElementType getFileNodeType() {
return FILE;
}
@Override
public IFileElementType getFileNodeType() {
return FILE;
}
public PsiFile createFile(FileViewProvider viewProvider) {
return new SimpleFile(viewProvider);
}
public PsiFile createFile(FileViewProvider viewProvider) {
return new SimpleFile(viewProvider);
}
public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) {
return SpaceRequirements.MAY;
}
public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) {
return SpaceRequirements.MAY;
}
@NotNull
public PsiElement createElement(ASTNode node) {
return SimpleTypes.Factory.createElement(node);
}
@NotNull
public PsiElement createElement(ASTNode node) {
return SimpleTypes.Factory.createElement(node);
}
}

Some files were not shown because too many files have changed in this diff Show More