// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.sh.rename;

import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.rename.RenameHandler;
import com.intellij.sh.ShSupport;
import com.intellij.sh.highlighting.ShTextOccurrencesUtil;
import com.intellij.sh.lexer.ShTokenTypes;
import com.intellij.sh.psi.ShFile;
import org.jetbrains.annotations.NotNull;

public class ShRenameHandler implements RenameHandler {
  @Override
  public boolean isAvailableOnDataContext(@NotNull DataContext dataContext) {
    Editor editor = dataContext.getData(CommonDataKeys.EDITOR);
    return editor != null
           && ShSupport.getInstance().isRenameEnabled()
           && ShRenameAllOccurrencesHandler.INSTANCE.isEnabled(editor, editor.getCaretModel().getPrimaryCaret(), dataContext)
           && isRenameAvailable(editor, dataContext)
      ;
  }

  private static boolean isRenameAvailable(@NotNull Editor editor, @NotNull DataContext dataContext) {
    ShFile file = (ShFile)dataContext.getData(CommonDataKeys.PSI_FILE);
    if (file == null) {
      return false;
    }
    if (editor.getCaretModel().getPrimaryCaret().hasSelection()) return true;
    TextRange textRange = ShTextOccurrencesUtil.findTextRangeOfIdentifierAtCaret(editor);
    if (textRange != null) {
      PsiElement element = file.findElementAt(textRange.getStartOffset());
      if (element != null && ShTokenTypes.keywords.contains(PsiUtilCore.getElementType(element))) {
        return false;
      }
    }
    return true;
  }

  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
    ShRenameAllOccurrencesHandler.INSTANCE.execute(editor, editor.getCaretModel().getPrimaryCaret(), null);
  }

  @Override
  public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
  }
}

@@ -742,24 +742,62 @@
 psi.ShFile;%0A
+import com.intellij.util.ObjectUtils;%0A
 import org.j
@@ -1436,16 +1436,28 @@
 e = 
-(ShFile)
+ObjectUtils.tryCast(
 data
@@ -1496,16 +1496,31 @@
 SI_FILE)
+, ShFile.class)
 ;%0A    if

fix ClassCastException