美文网首页
浅尝辄止:Interllij Idea 插件Action开发

浅尝辄止:Interllij Idea 插件Action开发

作者: StudyForLong | 来源:发表于2019-12-25 15:36 被阅读0次

    一、Interllij Idea下载
    idea下载地址:https://www.jetbrains.com/idea
    intellij-community sdk源码地址:https://github.com/JetBrains/intellij-community
    二、环境搭建
    相信大家都会,不多说~
    三、新建插件项目

    1.png
    • 一路Next即可,建完如图
    2.png
    • 新建Action:MobRenameAction.java
    3.png
    • 选择Group为ProjectViewPopupMenu的Action类型,自定义id、类名等
    4.png
    • 建完如下
    5.png

    到这里可以正式开发自己的插件功能了。

    • ProjectViewPopupMenu:project窗口内容右键弹出的窗口;
    • AnAction:功能实现的父类;

    一键查找、一键替换我们想到的肯定是Find in Path...、Replace in Path...,但我们的场景常常是修改某个资源文件名->替换代码中引用资源文件名的硬编码,Rename我们也熟悉,但Rename只能一键修改id的引用,并不能修改硬编码的引用,如何一步到位使用Rename+Replace的功能呢?那就是定制化我们的Action。

    今天我们是轻度定制化,不可避免要利用RenameFileAction和ReplaceInPathAction已实现的功能。
    这次不讲Plugin SDK源码,只讲相关实现,看代码

    public class MobRenameAction extends AnAction {
    
        @Override
        public void actionPerformed(AnActionEvent e) {
    
            DataContext dataContext = e.getDataContext();
            //获取Project实例
            Project project = CommonDataKeys.PROJECT.getData(dataContext);
            //获取右键选中的文件元素
           PsiElement element = e.getData(CommonDataKeys.PSI_ELEMENT);
           PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
           //显示操作弹窗
           MobRenameDialog dialog = new MobRenameDialog(project, element, dataContext, file);
           dialog.show();
    
        }
    }
    
    
    • What is the PSI?

    Program Structure Interface (PSI)
    The Program Structure Interface, commonly referred to as just PSI, is the layer in the IntelliJ Platform that is responsible for parsing files and creating the syntactic and semantic code model that powers so many of the platform’s features.

    (程序结构接口(通常称为PSI)是IntelliJ平台中的一层,负责分析文件并创建支持平台许多功能的语法和语义代码模型。)

    今天实现一个简单功能,当修改layout下的某个文件名时同步修改R.layout.idxx引用以及使用ResHelper.getLayoutRes硬编码名称,最终实现效果如下:

    GIF.gif

    弹窗代码实现:

    
    package com.mob.plugintest;
    
    public class MobRenameDialog extends RefactoringDialog {
        private JLabel myNameLabel;
        private final JLabel myNewNamePrefix;
        private PsiElement myPsiElement;
        private NameSuggestionsField myNameSuggestionsField;
        private SuggestedNameInfo mySuggestedNameInfo;
        private String myOldName;
        private final Editor myEditor;
        private NameSuggestionsField.DataChanged myNameChangedListener;
        private DataContext dataContext;
        private Project project;
        private PsiFile psiFile;
    
        protected MobRenameDialog(@NotNull Project project, PsiElement psiElement, 
                        DataContext dataContext, PsiFile psiFile) {
            super(project, true);
            this.myPsiElement = psiElement;
            this.myNewNamePrefix = new JLabel("");
            this.myEditor = null;
            this.dataContext = dataContext;
            this.project = project;
            this.psiFile = psiFile;
    
            setTitle("layout文件重命名");
            this.createNewNameComponent();
            init();
            this.myNameLabel.setText(XmlStringUtil.wrapInHtml(
                  XmlTagUtilBase.escapeString(this.getLabelText(), false)));
        }
    
        @Override
        protected void doAction() {
            close(0);
            ReplaceInProjectManager replaceManager = ReplaceInProjectManager.getInstance(project);
    
            String originalFileName = psiFile.getName().substring(0, psiFile.getName().indexOf("."));
    
            String name = getNewName();
            String newName = name.substring(0, name.indexOf("."));
            //从RenameFileAction复制的重命名工具类
            RenamePsiElementProcessor elementProcessor = RenamePsiElementProcessor.forElement(this.myPsiElement);
            elementProcessor.setToSearchInComments(this.myPsiElement, false);
            RenameProcessor processor = new RenameProcessor(project, this.myPsiElement, 
    name, GlobalSearchScope.projectScope(project), false, false);;
            processor.run();
    
            if (replaceManager.isEnabled()) {
                FindManager findManager = FindManager.getInstance(project);
                FindModel findModel = findManager.getFindInProjectModel().clone();
                //定义查找字符串,使用正则表达式查找
                findModel.setStringToFind("ResHelper.getLayoutRes\\(([a-zA-Z0-9\\.\\(\\)\\s]+,\\s*)\"" 
                      + originalFileName + "\"\\);");
                System.out.println(">>>>setStringToFind>> " + findModel.getStringToFind());
                findModel.setReplaceState(true);
                //定义替换字符串,使用正则表达式替换$1=([a-zA-Z0-9\\.\\(\\)\\s]+,\\s*)
                findModel.setStringToReplace("ResHelper.getLayoutRes\\($1\"" + newName + "\"\\);");
                FindInProjectUtil.setDirectoryName(findModel, dataContext);
                FindInProjectUtil.initStringToFindFromDataContext(findModel, dataContext);
                replaceManager.replaceInPath(findModel);
            }
        }
        public String[] getSuggestedNames() {
            LinkedHashSet<String> result = new LinkedHashSet();
            String initialName = VariableInplaceRenameHandler.getInitialName();
            if (initialName != null) {
                result.add(initialName);
            }
    
            result.add(UsageViewUtil.getShortName(this.myPsiElement));
            Iterator var3 = NameSuggestionProvider.EP_NAME.getExtensionList().iterator();
    
            while(var3.hasNext()) {
                NameSuggestionProvider provider = (NameSuggestionProvider)var3.next();
                SuggestedNameInfo info = provider.getSuggestedNames(this.myPsiElement,
     this.myPsiElement, result);
                if (info != null) {
                    this.mySuggestedNameInfo = info;
                    if (provider instanceof PreferrableNameSuggestionProvider 
              && !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) {
                        break;
                    }
                }
            }
    
            return ArrayUtilRt.toStringArray(result);
        }
    
        protected void createNewNameComponent() {
            String[] suggestedNames = this.getSuggestedNames();
            this.myOldName = UsageViewUtil.getShortName(this.myPsiElement);
            this.myNameSuggestionsField = new NameSuggestionsField(suggestedNames, 
            this.myProject, FileTypes.PLAIN_TEXT, this.myEditor) {
                protected boolean shouldSelectAll() {
                    return MobRenameDialog.this.myEditor == null
     || MobRenameDialog.this.myEditor.getSettings().isPreselectRename();
                }
            };
            if (this.myPsiElement instanceof PsiFile && this.myEditor == null) {
                this.myNameSuggestionsField.selectNameWithoutExtension();
            }
    
            this.myNameChangedListener = () -> {
    //            this.processNewNameChanged();
            };
            this.myNameSuggestionsField.addDataChangedListener(this.myNameChangedListener);
        }
    
        @NotNull
        public String getNewName() {
            String newName = this.myNameSuggestionsField.getEnteredName().trim();
    
            return newName;
        }
    
        @NotNull
        protected String getLabelText() {
            String fileName = RefactoringBundle.message("rename.0.and.its.usages.to",
     new Object[]{this.getFullName()});
            return fileName;
        }
    
        protected String getFullName() {
            String name = DescriptiveNameUtil.getDescriptiveName(this.myPsiElement);
            String type = UsageViewUtil.getType(this.myPsiElement);
            return StringUtil.isEmpty(name) ? type : type + " '" + name + "'";
        }
    
        @Nullable
        @Override
        protected JComponent createNorthPanel() {
            //自定义弹窗显示控件
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbConstraints = new GridBagConstraints();
            gbConstraints.insets = JBUI.insetsBottom(4);
            gbConstraints.weighty = 0.0D;
            gbConstraints.weightx = 1.0D;
            gbConstraints.gridwidth = 1;
            gbConstraints.gridheight = 1;
            gbConstraints.fill = 1;
            this.myNameLabel = new JLabel();
            panel.add(this.myNameLabel, gbConstraints);
            gbConstraints.insets = JBUI.insets(0, 0, 4, StringUtil.isEmpty(this.myNewNamePrefix.getText()) ? 0 : 1);
            gbConstraints.gridwidth = 1;
            gbConstraints.gridheight = 1;
            gbConstraints.fill = 0;
            gbConstraints.weightx = 0.0D;
            gbConstraints.gridx = 0;
            gbConstraints.anchor = 17;
            panel.add(this.myNewNamePrefix, gbConstraints);
            gbConstraints.insets = JBUI.insetsBottom(8);
            gbConstraints.gridwidth = 2;
            gbConstraints.fill = 1;
            gbConstraints.weightx = 1.0D;
            gbConstraints.gridx = 0;
            gbConstraints.weighty = 1.0D;
            panel.add(this.myNameSuggestionsField.getComponent(), gbConstraints);
            return panel;
        }
    
        @Nullable
        @Override
        protected JComponent createCenterPanel() {
            return null;
        }
    }
    

    以上代码实际只有正则表达式为自定义,其它都来自RenameFileAction、ReplaceInPathAction,至此轻度定制重命名插件就完成了。
    一般情况下不会需要定制化插件,RenameFileAction、ReplaceInPathAction已经足够强大,这离不开正则表达式,可能会对设置的查找和替换表达式感到疑惑,说明如下:

    6.png

    以上需要关注的正则共有两个可提取的匹配([a-zA-Z0-9.()\s]+,\s),(test2),在使用表达式时我们可以使用括号分别匹配不同的字符,在替换时按顺序使用$1到$99可得到括号中匹配的实际值, 如上图在本例中只需要替换(test2),保留([a-zA-Z0-9.()\s]+,\s)匹配的任意字符,在replace则可以使用$1代替([a-zA-Z0-9.()\s]+,\s*)。

    参考资料与延伸:

    相关文章

      网友评论

          本文标题:浅尝辄止:Interllij Idea 插件Action开发

          本文链接:https://www.haomeiwen.com/subject/wppcoctx.html