@Nullable
  private FilePath unshelveBinaryFile(
      final ShelvedBinaryFile file, @NotNull final VirtualFile patchTarget) throws IOException {
    final Ref<FilePath> result = new Ref<FilePath>();
    final Ref<IOException> ex = new Ref<IOException>();
    final Ref<VirtualFile> patchedFileRef = new Ref<VirtualFile>();
    final File shelvedFile = file.SHELVED_PATH == null ? null : new File(file.SHELVED_PATH);

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                try {
                  result.set(new FilePathImpl(patchTarget));
                  if (shelvedFile == null) {
                    patchTarget.delete(this);
                  } else {
                    patchTarget.setBinaryContent(FileUtil.loadFileBytes(shelvedFile));
                    patchedFileRef.set(patchTarget);
                  }
                } catch (IOException e) {
                  ex.set(e);
                }
              }
            });
    if (!ex.isNull()) {
      throw ex.get();
    }
    return result.get();
  }
 @Nullable
 private PyType getReturnType(@NotNull TypeEvalContext context) {
   for (PyTypeProvider typeProvider : Extensions.getExtensions(PyTypeProvider.EP_NAME)) {
     final Ref<PyType> returnTypeRef = typeProvider.getReturnType(this, context);
     if (returnTypeRef != null) {
       final PyType returnType = returnTypeRef.get();
       if (returnType != null) {
         returnType.assertValid(typeProvider.toString());
       }
       return returnType;
     }
   }
   final PyType docStringType = getReturnTypeFromDocString();
   if (docStringType != null) {
     docStringType.assertValid("from docstring");
     return docStringType;
   }
   if (context.allowReturnTypes(this)) {
     final Ref<? extends PyType> yieldTypeRef = getYieldStatementType(context);
     if (yieldTypeRef != null) {
       return yieldTypeRef.get();
     }
     return getReturnStatementType(context);
   }
   return null;
 }
 private JComponent createActionLink(
     final String text, final String groupId, Icon icon, boolean focusListOnLeft) {
   final Ref<ActionLink> ref = new Ref<ActionLink>(null);
   AnAction action =
       new AnAction() {
         @Override
         public void actionPerformed(@NotNull AnActionEvent e) {
           ActionGroup configureGroup =
               (ActionGroup) ActionManager.getInstance().getAction(groupId);
           final PopupFactoryImpl.ActionGroupPopup popup =
               (PopupFactoryImpl.ActionGroupPopup)
                   JBPopupFactory.getInstance()
                       .createActionGroupPopup(
                           null,
                           new IconsFreeActionGroup(configureGroup),
                           e.getDataContext(),
                           JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
                           false,
                           ActionPlaces.WELCOME_SCREEN);
           popup.showUnderneathOfLabel(ref.get());
           UsageTrigger.trigger("welcome.screen." + groupId);
         }
       };
   ref.set(new ActionLink(text, icon, action));
   ref.get().setPaintUnderline(false);
   ref.get().setNormalColor(getLinkNormalColor());
   NonOpaquePanel panel = new NonOpaquePanel(new BorderLayout());
   panel.setBorder(JBUI.Borders.empty(4, 6, 4, 6));
   panel.add(ref.get());
   panel.add(createArrow(ref.get()), BorderLayout.EAST);
   installFocusable(panel, action, KeyEvent.VK_UP, KeyEvent.VK_DOWN, focusListOnLeft);
   return panel;
 }
 public void run() {
   Throwable error = null;
   final Ref<Boolean> hasErrors = new Ref<Boolean>(false);
   final Ref<Boolean> markedFilesUptodate = new Ref<Boolean>(false);
   try {
     runBuild(
         new MessageHandler() {
           public void processMessage(BuildMessage buildMessage) {
             final CmdlineRemoteProto.Message.BuilderMessage response;
             if (buildMessage instanceof FileGeneratedEvent) {
               final Collection<Pair<String, String>> paths =
                   ((FileGeneratedEvent) buildMessage).getPaths();
               response =
                   !paths.isEmpty() ? CmdlineProtoUtil.createFileGeneratedEvent(paths) : null;
             } else if (buildMessage instanceof UptoDateFilesSavedEvent) {
               markedFilesUptodate.set(true);
               response = null;
             } else if (buildMessage instanceof CompilerMessage) {
               markedFilesUptodate.set(true);
               final CompilerMessage compilerMessage = (CompilerMessage) buildMessage;
               final String text =
                   compilerMessage.getCompilerName() + ": " + compilerMessage.getMessageText();
               final BuildMessage.Kind kind = compilerMessage.getKind();
               if (kind == BuildMessage.Kind.ERROR) {
                 hasErrors.set(true);
               }
               response =
                   CmdlineProtoUtil.createCompileMessage(
                       kind,
                       text,
                       compilerMessage.getSourcePath(),
                       compilerMessage.getProblemBeginOffset(),
                       compilerMessage.getProblemEndOffset(),
                       compilerMessage.getProblemLocationOffset(),
                       compilerMessage.getLine(),
                       compilerMessage.getColumn(),
                       -1.0f);
             } else {
               float done = -1.0f;
               if (buildMessage instanceof ProgressMessage) {
                 done = ((ProgressMessage) buildMessage).getDone();
               }
               response =
                   CmdlineProtoUtil.createCompileProgressMessageResponse(
                       buildMessage.getMessageText(), done);
             }
             if (response != null) {
               Channels.write(myChannel, CmdlineProtoUtil.toMessage(mySessionId, response));
             }
           }
         },
         this);
   } catch (Throwable e) {
     LOG.info(e);
     error = e;
   } finally {
     finishBuild(error, hasErrors.get(), markedFilesUptodate.get());
   }
 }
 @Override
 protected byte[] key(@Nullable final Project project) throws PasswordSafeException {
   ApplicationEx application = (ApplicationEx) ApplicationManager.getApplication();
   if (!isTestMode() && application.isHeadlessEnvironment()) {
     throw new MasterPasswordUnavailableException(
         "The provider is not available in headless environment");
   }
   if (key.get() == null) {
     if (isPasswordEncrypted()) {
       try {
         String s = decryptPassword(database.getPasswordInfo());
         setMasterPassword(s);
       } catch (PasswordSafeException e) {
         // ignore exception and ask password
       }
     }
     if (key.get() == null) {
       final Ref<PasswordSafeException> ex = new Ref<PasswordSafeException>();
       if (application.holdsReadLock()) {
         throw new IllegalStateException(
             "Access from read action is not allowed, because it might lead to a deadlock.");
       }
       application.invokeAndWait(
           new Runnable() {
             public void run() {
               if (key.get() == null) {
                 try {
                   if (isTestMode()) {
                     throw new MasterPasswordUnavailableException(
                         "Master password must be specified in test mode.");
                   }
                   if (database.isEmpty()) {
                     if (!ResetPasswordDialog.newPassword(project, MasterKeyPasswordSafe.this)) {
                       throw new MasterPasswordUnavailableException(
                           "Master password is required to store passwords in the database.");
                     }
                   } else {
                     MasterPasswordDialog.askPassword(project, MasterKeyPasswordSafe.this);
                   }
                 } catch (PasswordSafeException e) {
                   ex.set(e);
                 } catch (Exception e) {
                   //noinspection ThrowableInstanceNeverThrown
                   ex.set(
                       new MasterPasswordUnavailableException(
                           "The problem with retrieving the password", e));
                 }
               }
             }
           },
           ModalityState.defaultModalityState());
       //noinspection ThrowableResultOfMethodCallIgnored
       if (ex.get() != null) {
         throw ex.get();
       }
     }
   }
   return this.key.get();
 }
Esempio n. 6
0
  public void update(final AnActionEvent e) {
    final FileGroupInfo fileGroupInfo = new FileGroupInfo();

    myHelperAction.setFileIterationListener(fileGroupInfo);
    myHelperAction.update(e);

    myGetterStub.setDelegate(fileGroupInfo);

    if ((e.getPresentation().isEnabled())) {
      removeAll();
      if (myHelperAction.allAreIgnored()) {
        final DataContext dataContext = e.getDataContext();
        final Project project = CommonDataKeys.PROJECT.getData(dataContext);
        SvnVcs vcs = SvnVcs.getInstance(project);

        final Ref<Boolean> filesOk = new Ref<Boolean>(Boolean.FALSE);
        final Ref<Boolean> extensionOk = new Ref<Boolean>(Boolean.FALSE);

        // virtual files parameter is not used -> can pass null
        SvnPropertyService.doCheckIgnoreProperty(
            vcs,
            project,
            null,
            fileGroupInfo,
            fileGroupInfo.getExtensionMask(),
            filesOk,
            extensionOk);

        if (Boolean.TRUE.equals(filesOk.get())) {
          myRemoveExactAction.setActionText(
              fileGroupInfo.oneFileSelected()
                  ? fileGroupInfo.getFileName()
                  : SvnBundle.message("action.Subversion.UndoIgnore.text"));
          add(myRemoveExactAction);
        }

        if (Boolean.TRUE.equals(extensionOk.get())) {
          myRemoveExtensionAction.setActionText(fileGroupInfo.getExtensionMask());
          add(myRemoveExtensionAction);
        }

        e.getPresentation().setText(SvnBundle.message("group.RevertIgnoreChoicesGroup.text"));
      } else if (myHelperAction.allCanBeIgnored()) {
        final String ignoreExactlyName =
            (fileGroupInfo.oneFileSelected())
                ? fileGroupInfo.getFileName()
                : SvnBundle.message("action.Subversion.Ignore.ExactMatch.text");
        myAddExactAction.setActionText(ignoreExactlyName);
        add(myAddExactAction);
        if (fileGroupInfo.sameExtension()) {
          myAddExtensionAction.setActionText(fileGroupInfo.getExtensionMask());
          add(myAddExtensionAction);
        }
        e.getPresentation().setText(SvnBundle.message("group.IgnoreChoicesGroup.text"));
      }
    }
  }
  /*test source mapping generation when source info is absent*/
  public void testInlineFunWithoutDebugInfo() throws Exception {
    compileKotlin("sourceInline.kt", tmpdir);

    File inlineFunClass = new File(tmpdir.getAbsolutePath(), "test/A.class");
    ClassWriter cw = new ClassWriter(Opcodes.ASM5);
    new ClassReader(FilesKt.readBytes(inlineFunClass))
        .accept(
            new ClassVisitor(Opcodes.ASM5, cw) {
              @Override
              public void visitSource(String source, String debug) {
                // skip debug info
              }
            },
            0);

    assert inlineFunClass.delete();
    assert !inlineFunClass.exists();

    FilesKt.writeBytes(inlineFunClass, cw.toByteArray());

    compileKotlin("source.kt", tmpdir, tmpdir);

    final Ref<String> debugInfo = new Ref<String>();
    File resultFile = new File(tmpdir.getAbsolutePath(), "test/B.class");
    new ClassReader(FilesKt.readBytes(resultFile))
        .accept(
            new ClassVisitor(Opcodes.ASM5) {
              @Override
              public void visitSource(String source, String debug) {
                // skip debug info
                debugInfo.set(debug);
              }
            },
            0);

    String expected =
        "SMAP\n"
            + "source.kt\n"
            + "Kotlin\n"
            + "*S Kotlin\n"
            + "*F\n"
            + "+ 1 source.kt\n"
            + "test/B\n"
            + "*L\n"
            + "1#1,13:1\n"
            + "*E\n";

    if (InlineCodegenUtil.GENERATE_SMAP) {
      assertEquals(expected, debugInfo.get());
    } else {
      assertEquals(null, debugInfo.get());
    }
  }
 @Override
 protected JPanel processSplitter(
     @NotNull Element splitterElement,
     Element firstChild,
     Element secondChild,
     final JPanel context) {
   if (context == null) {
     final boolean orientation =
         "vertical".equals(splitterElement.getAttributeValue("split-orientation"));
     final float proportion =
         Float.valueOf(splitterElement.getAttributeValue("split-proportion")).floatValue();
     final JPanel firstComponent = process(firstChild, null);
     final JPanel secondComponent = process(secondChild, null);
     final Ref<JPanel> panelRef = new Ref<JPanel>();
     UIUtil.invokeAndWaitIfNeeded(
         new Runnable() {
           @Override
           public void run() {
             JPanel panel = new JPanel(new BorderLayout());
             panel.setOpaque(false);
             Splitter splitter = new OnePixelSplitter(orientation, proportion, 0.1f, 0.9f);
             panel.add(splitter, BorderLayout.CENTER);
             splitter.setFirstComponent(firstComponent);
             splitter.setSecondComponent(secondComponent);
             panelRef.set(panel);
           }
         });
     return panelRef.get();
   }
   final Ref<JPanel> firstComponent = new Ref<JPanel>();
   final Ref<JPanel> secondComponent = new Ref<JPanel>();
   UIUtil.invokeAndWaitIfNeeded(
       new Runnable() {
         @Override
         public void run() {
           if (context.getComponent(0) instanceof Splitter) {
             Splitter splitter = (Splitter) context.getComponent(0);
             firstComponent.set((JPanel) splitter.getFirstComponent());
             secondComponent.set((JPanel) splitter.getSecondComponent());
           } else {
             firstComponent.set(context);
             secondComponent.set(context);
           }
         }
       });
   process(firstChild, firstComponent.get());
   process(secondChild, secondComponent.get());
   return context;
 }
  /**
   * Finds an existing run configuration matching the context.
   *
   * @return an existing configuration, or null if none was found.
   */
  @Nullable
  public RunnerAndConfigurationSettings findExisting() {
    if (myExistingConfiguration != null) return myExistingConfiguration.get();
    myExistingConfiguration = new Ref<>();
    if (myLocation == null) {
      return null;
    }

    final PsiElement psiElement = myLocation.getPsiElement();
    if (!psiElement.isValid()) {
      return null;
    }

    final List<RuntimeConfigurationProducer> producers = findPreferredProducers();
    if (myRuntimeConfiguration != null) {
      if (producers != null) {
        for (RuntimeConfigurationProducer producer : producers) {
          final RunnerAndConfigurationSettings configuration =
              producer.findExistingConfiguration(myLocation, this);
          if (configuration != null && configuration.getConfiguration() == myRuntimeConfiguration) {
            myExistingConfiguration.set(configuration);
          }
        }
      }
      for (RunConfigurationProducer producer :
          RunConfigurationProducer.getProducers(getProject())) {
        RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(this);
        if (configuration != null && configuration.getConfiguration() == myRuntimeConfiguration) {
          myExistingConfiguration.set(configuration);
        }
      }
    }
    if (producers != null) {
      for (RuntimeConfigurationProducer producer : producers) {
        final RunnerAndConfigurationSettings configuration =
            producer.findExistingConfiguration(myLocation, this);
        if (configuration != null) {
          myExistingConfiguration.set(configuration);
        }
      }
    }
    for (RunConfigurationProducer producer : RunConfigurationProducer.getProducers(getProject())) {
      RunnerAndConfigurationSettings configuration = producer.findExistingConfiguration(this);
      if (configuration != null) {
        myExistingConfiguration.set(configuration);
      }
    }
    return myExistingConfiguration.get();
  }
 protected String addToHistoryInner(
     final TextRange textRange,
     final EditorEx editor,
     final boolean erase,
     final boolean preserveMarkup) {
   final Ref<String> ref = Ref.create("");
   final Runnable action =
       new Runnable() {
         public void run() {
           ref.set(addTextRangeToHistory(textRange, editor, preserveMarkup));
           if (erase) {
             editor
                 .getDocument()
                 .deleteString(textRange.getStartOffset(), textRange.getEndOffset());
           }
         }
       };
   if (erase) {
     ApplicationManager.getApplication().runWriteAction(action);
   } else {
     ApplicationManager.getApplication().runReadAction(action);
   }
   // always scroll to end on user input
   scrollHistoryToEnd();
   queueUiUpdate(true);
   return ref.get();
 }
Esempio n. 11
0
  private boolean disposeSelf() {
    myDisposeInProgress = true;
    final CommandProcessor commandProcessor = CommandProcessor.getInstance();
    final Ref<Boolean> canClose = new Ref<Boolean>(Boolean.TRUE);
    for (final Project project : ProjectManagerEx.getInstanceEx().getOpenProjects()) {
      try {
        commandProcessor.executeCommand(
            project,
            new Runnable() {
              public void run() {
                canClose.set(ProjectUtil.closeAndDispose(project));
              }
            },
            ApplicationBundle.message("command.exit"),
            null);
      } catch (Throwable e) {
        LOG.error(e);
      }
      if (!canClose.get()) {
        myDisposeInProgress = false;
        return false;
      }
    }
    Disposer.dispose(this);

    Disposer.assertIsEmpty();
    return true;
  }
Esempio n. 12
0
 public void testNoUnnecessaryHorizontalScrollBar() throws IOException {
   // Inspired by IDEA-87184
   final String text = "12345678 abcdefgh";
   init(15, 7, text);
   myEditor.getCaretModel().moveToOffset(text.length());
   final Ref<Boolean> fail = new Ref<Boolean>(true);
   SoftWrapApplianceManager applianceManager =
       ((SoftWrapModelImpl) myEditor.getSoftWrapModel()).getApplianceManager();
   SoftWrapAwareDocumentParsingListener listener =
       new SoftWrapAwareDocumentParsingListenerAdapter() {
         @Override
         public void beforeSoftWrapLineFeed(@NotNull EditorPosition position) {
           if (position.x == text.indexOf("a") * 7) {
             fail.set(false);
           }
         }
       };
   applianceManager.addListener(listener);
   try {
     backspace();
   } finally {
     applianceManager.removeListener(listener);
   }
   assertFalse(fail.get());
 }
  public EntryPoint acquire(@NotNull Target target, @NotNull Parameters configuration)
      throws Exception {
    ApplicationManagerEx.getApplicationEx().assertTimeConsuming();

    Ref<RunningInfo> ref = Ref.create(null);
    Pair<Target, Parameters> key = Pair.create(target, configuration);
    if (!getExistingInfo(ref, key)) {
      startProcess(target, configuration, key);
      if (ref.isNull()) {
        try {
          //noinspection SynchronizationOnLocalVariableOrMethodParameter
          synchronized (ref) {
            while (ref.isNull()) {
              ref.wait(1000);
              ProgressManager.checkCanceled();
            }
          }
        } catch (InterruptedException e) {
          ProgressManager.checkCanceled();
        }
      }
    }
    if (ref.isNull())
      throw new RuntimeException("Unable to acquire remote proxy for: " + getName(target));
    RunningInfo info = ref.get();
    if (info.handler == null) {
      String message = info.name;
      if (message != null && message.startsWith("ERROR: transport error 202:")) {
        message =
            "Unable to start java process in debug mode: -Xdebug parameters are already in use.";
      }
      throw new ExecutionException(message);
    }
    return acquire(info);
  }
  public boolean navigateSelectedElement() {
    final Ref<Boolean> succeeded = new Ref<Boolean>();
    final CommandProcessor commandProcessor = CommandProcessor.getInstance();
    commandProcessor.executeCommand(
        myProject,
        new Runnable() {
          public void run() {
            final AbstractTreeNode selectedNode = getSelectedNode();
            if (selectedNode != null) {
              if (selectedNode.canNavigateToSource()) {
                myPopup.cancel();
                selectedNode.navigate(true);
                succeeded.set(true);
              } else {
                succeeded.set(false);
              }
            } else {
              succeeded.set(false);
            }

            IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation();
          }
        },
        "Navigate",
        null);
    return succeeded.get();
  }
Esempio n. 15
0
  @NotNull
  private static PsiElement addSemicolonIfNeeded(
      @NotNull final Editor editor,
      @NotNull final Document document,
      @NotNull final PsiElement context,
      final int offset) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    final Ref<PsiElement> newContext = Ref.create(context);
    final PsiFile file = context.getContainingFile();
    if (isSemicolonNeeded(file, editor)) {
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  CommandProcessor.getInstance()
                      .runUndoTransparentAction(
                          new Runnable() {
                            public void run() {
                              document.insertString(offset, ";");
                              PsiDocumentManager.getInstance(context.getProject())
                                  .commitDocument(document);
                              newContext.set(CustomTemplateCallback.getContext(file, offset - 1));
                            }
                          });
                }
              });
    }
    return newContext.get();
  }
  public boolean confirmUndeploy() {
    final Ref<Boolean> confirmed = new Ref<Boolean>(false);
    ApplicationManager.getApplication()
        .invokeAndWait(
            new Runnable() {

              @Override
              public void run() {
                String title = CloudBundle.getText("cloud.undeploy.confirm.title");
                while (true) {
                  String password =
                      Messages.showPasswordDialog(
                          CloudBundle.getText("cloud.undeploy.confirm.message", myPresentableName),
                          title);
                  if (password == null) {
                    return;
                  }
                  if (password.equals(myConfiguration.getPassword())) {
                    confirmed.set(true);
                    return;
                  }
                  Messages.showErrorDialog(
                      CloudBundle.getText("cloud.undeploy.confirm.password.incorrect"), title);
                }
              }
            },
            ModalityState.defaultModalityState());
    return confirmed.get();
  }
    public MultiMap<PsiElement, String> findConflicts(Ref<UsageInfo[]> refUsages) {
      MultiMap<PsiElement, String> conflictDescriptions = new MultiMap<PsiElement, String>();
      addMethodConflicts(conflictDescriptions);
      Set<UsageInfo> usagesSet = new HashSet<UsageInfo>(Arrays.asList(refUsages.get()));
      RenameUtil.removeConflictUsages(usagesSet);
      if (myChangeInfo.isVisibilityChanged()) {
        try {
          addInaccessibilityDescriptions(usagesSet, conflictDescriptions);
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }

      for (UsageInfo usageInfo : usagesSet) {
        if (usageInfo instanceof OverriderUsageInfo) {
          final PsiMethod method = (PsiMethod) usageInfo.getElement();
          final PsiMethod baseMethod = ((OverriderUsageInfo) usageInfo).getBaseMethod();
          final int delta =
              baseMethod.getParameterList().getParametersCount()
                  - method.getParameterList().getParametersCount();
          if (delta > 0) {
            final boolean[] toRemove = myChangeInfo.toRemoveParm();
            if (toRemove[
                toRemove.length - 1]) { // todo check if implicit parameter is not the last one
              conflictDescriptions.putValue(
                  baseMethod, "Implicit last parameter should not be deleted");
            }
          }
        }
      }

      return conflictDescriptions;
    }
Esempio n. 18
0
  public static boolean isEnabled(@NotNull ModuleType moduleType) {
    for (FacetType<?, ?> facetType : FacetTypeRegistry.getInstance().getFacetTypes()) {
      if (facetType.isSuitableModuleType(moduleType)) {
        final Ref<Boolean> hasDetector = Ref.create(false);
        //noinspection unchecked
        facetType.registerDetectors(
            new FacetDetectorRegistryEx(
                new FacetDetectorForWizardRegistry() {
                  public void register(
                      @NotNull FileType fileType,
                      @NotNull VirtualFileFilter virtualFileFilter,
                      @NotNull FacetDetector facetDetector) {
                    hasDetector.set(true);
                  }

                  public void register(
                      FileType fileType,
                      @NotNull VirtualFileFilter virtualFileFilter,
                      FacetDetector facetDetector,
                      UnderlyingFacetSelector underlyingFacetSelector) {
                    hasDetector.set(true);
                  }
                },
                null));
        if (hasDetector.get()) {
          return true;
        }
      }
    }
    return false;
  }
  @Nullable
  public Script getScriptSync(@NotNull final String isolateId, @NotNull final String scriptId) {
    assertSyncRequestAllowed();

    final Semaphore semaphore = new Semaphore();
    semaphore.down();

    final Ref<Script> resultRef = Ref.create();

    addRequest(
        () ->
            myVmService.getObject(
                isolateId,
                scriptId,
                new GetObjectConsumer() {
                  @Override
                  public void received(Obj script) {
                    resultRef.set((Script) script);
                    semaphore.up();
                  }

                  @Override
                  public void received(Sentinel response) {
                    semaphore.up();
                  }

                  @Override
                  public void onError(RPCError error) {
                    semaphore.up();
                  }
                }));

    semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
    return resultRef.get();
  }
 private static PsiElement findInside(
     @NotNull PsiElement element,
     @NotNull PsiFile hostFile,
     final int hostOffset,
     @NotNull final PsiDocumentManager documentManager) {
   final Ref<PsiElement> out = new Ref<PsiElement>();
   enumerate(
       element,
       hostFile,
       true,
       new PsiLanguageInjectionHost.InjectedPsiVisitor() {
         @Override
         public void visit(
             @NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) {
           for (PsiLanguageInjectionHost.Shred place : places) {
             TextRange hostRange = place.getHost().getTextRange();
             if (hostRange.cutOut(place.getRangeInsideHost()).grown(1).contains(hostOffset)) {
               DocumentWindowImpl document =
                   (DocumentWindowImpl) documentManager.getCachedDocument(injectedPsi);
               if (document == null) return;
               int injectedOffset = document.hostToInjected(hostOffset);
               PsiElement injElement = injectedPsi.findElementAt(injectedOffset);
               out.set(injElement == null ? injectedPsi : injElement);
             }
           }
         }
       });
   return out.get();
 }
  @Nullable
  private static AntDomElement findElementById(
      AntDomElement from, final String id, final boolean skipCustomTags) {
    if (id.equals(from.getId().getRawText())) {
      return from;
    }
    final Ref<AntDomElement> result = new Ref<AntDomElement>(null);
    from.accept(
        new AntDomRecursiveVisitor() {
          public void visitAntDomCustomElement(AntDomCustomElement custom) {
            if (!skipCustomTags) {
              super.visitAntDomCustomElement(custom);
            }
          }

          public void visitAntDomElement(AntDomElement element) {
            if (result.get() != null) {
              return;
            }
            if (id.equals(element.getId().getRawText())) {
              result.set(element);
              return;
            }
            super.visitAntDomElement(element);
          }
        });

    return result.get();
  }
  @Nullable
  private static GrVariableDeclaration findDeclaration(GroovyFile file) {
    final Ref<GrVariableDeclaration> ref = Ref.create();
    file.accept(
        new GroovyRecursiveElementVisitor() {
          @Override
          public void visitVariableDeclaration(@NotNull GrVariableDeclaration variableDeclaration) {
            super.visitVariableDeclaration(variableDeclaration);
            if (variableDeclaration
                    .getModifierList()
                    .findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_BASE_SCRIPT)
                != null) {
              ref.set(variableDeclaration);
            }
          }

          @Override
          public void visitElement(@NotNull GroovyPsiElement element) {
            if (ref.isNull()) {
              super.visitElement(element);
            }
          }
        });

    return ref.get();
  }
 @Nullable
 public GradleLibraryDependency findLibraryDependency(
     @NotNull final GradleLibraryDependencyId id) {
   final GradleModule module = findGradleModuleByName(id.getModuleName());
   if (module == null) {
     return null;
   }
   final Ref<GradleLibraryDependency> ref = new Ref<GradleLibraryDependency>();
   GradleEntityVisitor visitor =
       new GradleEntityVisitorAdapter() {
         @Override
         public void visit(@NotNull GradleLibraryDependency dependency) {
           if (id.getLibraryName().equals(dependency.getName())) {
             ref.set(dependency);
           }
         }
       };
   for (GradleDependency dependency : module.getDependencies()) {
     dependency.invite(visitor);
     final GradleLibraryDependency result = ref.get();
     if (result != null) {
       return result;
     }
   }
   return null;
 }
  protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
    final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();

    checkExistingMethods(conflicts, true);
    checkExistingMethods(conflicts, false);
    final Collection<PsiClass> classes = ClassInheritorsSearch.search(myClass).findAll();
    for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
      final Set<PsiMethod> setters = new HashSet<PsiMethod>();
      final Set<PsiMethod> getters = new HashSet<PsiMethod>();

      for (PsiClass aClass : classes) {
        final PsiMethod getterOverrider =
            myDescriptor.isToEncapsulateGet()
                ? aClass.findMethodBySignature(fieldDescriptor.getGetterPrototype(), false)
                : null;
        if (getterOverrider != null) {
          getters.add(getterOverrider);
        }
        final PsiMethod setterOverrider =
            myDescriptor.isToEncapsulateSet()
                ? aClass.findMethodBySignature(fieldDescriptor.getSetterPrototype(), false)
                : null;
        if (setterOverrider != null) {
          setters.add(setterOverrider);
        }
      }
      if (!getters.isEmpty() || !setters.isEmpty()) {
        final PsiField field = fieldDescriptor.getField();
        for (PsiReference reference : ReferencesSearch.search(field)) {
          final PsiElement place = reference.getElement();
          if (place instanceof PsiReferenceExpression) {
            final PsiExpression qualifierExpression =
                ((PsiReferenceExpression) place).getQualifierExpression();
            final PsiClass ancestor;
            if (qualifierExpression == null) {
              ancestor = PsiTreeUtil.getParentOfType(place, PsiClass.class, false);
            } else {
              ancestor = PsiUtil.resolveClassInType(qualifierExpression.getType());
            }

            final boolean isGetter = !PsiUtil.isAccessedForWriting((PsiExpression) place);
            for (PsiMethod overridden : isGetter ? getters : setters) {
              if (InheritanceUtil.isInheritorOrSelf(myClass, ancestor, true)) {
                conflicts.putValue(
                    overridden,
                    "There is already a "
                        + RefactoringUIUtil.getDescription(overridden, true)
                        + " which would hide generated "
                        + (isGetter ? "getter" : "setter")
                        + " for "
                        + place.getText());
                break;
              }
            }
          }
        }
      }
    }
    return showConflicts(conflicts, refUsages.get());
  }
  public static void deleteFile(Project project, final VirtualFile file) throws ExecutionException {
    final Ref<IOException> error = new Ref<IOException>();

    final Runnable runnable =
        new Runnable() {
          public void run() {
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Runnable() {
                      public void run() {
                        try {
                          if (file.isValid()) {
                            file.delete(this);
                          }
                        } catch (IOException e) {
                          error.set(e);
                        }
                      }
                    });
          }
        };

    if (ApplicationManager.getApplication().isDispatchThread()) {
      runnable.run();
    } else {
      ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
      ApplicationManager.getApplication()
          .invokeAndWait(runnable, pi != null ? pi.getModalityState() : ModalityState.NON_MODAL);
    }
    if (!error.isNull()) {
      //noinspection ThrowableResultOfMethodCallIgnored
      throw new ExecutionException(error.get().getMessage());
    }
  }
Esempio n. 26
0
  static String calcClassDisplayName(final PsiClass aClass) {
    final String qName = aClass.getQualifiedName();
    if (qName != null) {
      return qName;
    }
    final PsiClass parent = PsiTreeUtil.getParentOfType(aClass, PsiClass.class, true);
    if (parent == null) {
      return null;
    }

    final String name = aClass.getName();
    if (name != null) {
      return calcClassDisplayName(parent) + "$" + name;
    }

    final Ref<Integer> classIndex = new Ref<Integer>(0);
    try {
      parent.accept(
          new JavaRecursiveElementVisitor() {
            public void visitAnonymousClass(PsiAnonymousClass cls) {
              classIndex.set(classIndex.get() + 1);
              if (aClass.equals(cls)) {
                throw new ProcessCanceledException();
              }
            }
          });
    } catch (ProcessCanceledException ignored) {
    }
    return calcClassDisplayName(parent) + "$" + classIndex.get();
  }
 @Nullable
 @Override
 public PyType getReturnType(@NotNull TypeEvalContext context, @NotNull TypeEvalContext.Key key) {
   for (PyTypeProvider typeProvider : Extensions.getExtensions(PyTypeProvider.EP_NAME)) {
     final PyType returnType = typeProvider.getReturnType(this, context);
     if (returnType != null) {
       returnType.assertValid(typeProvider.toString());
       return returnType;
     }
   }
   if (context.maySwitchToAST(this)
       && LanguageLevel.forElement(this).isAtLeast(LanguageLevel.PYTHON30)) {
     PyAnnotation anno = getAnnotation();
     if (anno != null) {
       PyClass pyClass = anno.resolveToClass();
       if (pyClass != null) {
         return new PyClassTypeImpl(pyClass, false);
       }
     }
   }
   final PyType docStringType = getReturnTypeFromDocString();
   if (docStringType != null) {
     docStringType.assertValid("from docstring");
     return docStringType;
   }
   if (context.allowReturnTypes(this)) {
     final Ref<? extends PyType> yieldTypeRef = getYieldStatementType(context);
     if (yieldTypeRef != null) {
       return yieldTypeRef.get();
     }
     return getReturnStatementType(context);
   }
   return null;
 }
  /**
   * remove highlights (bounded with <marker>...</marker>) from test case file
   *
   * @param document document to process
   */
  private void extractExpectedHighlightsSet(final Document document) {
    final String text = document.getText();

    final Set<String> markers = myHighlightingTypes.keySet();
    final String typesRx = "(?:" + StringUtil.join(markers, ")|(?:") + ")";
    final String openingTagRx =
        "<("
            + typesRx
            + ")"
            + "(?:\\s+descr=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\\\])*)\")?"
            + "(?:\\s+type=\"([0-9A-Z_]+)\")?"
            + "(?:\\s+foreground=\"([0-9xa-f]+)\")?"
            + "(?:\\s+background=\"([0-9xa-f]+)\")?"
            + "(?:\\s+effectcolor=\"([0-9xa-f]+)\")?"
            + "(?:\\s+effecttype=\"([A-Z]+)\")?"
            + "(?:\\s+fonttype=\"([0-9]+)\")?"
            + "(?:\\s+textAttributesKey=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\\\])*)\")?"
            + "(?:\\s+bundleMsg=\"((?:[^\"]|\\\\\"|\\\\\\\\\")*)\")?"
            + "(/)?>";

    final Matcher matcher = Pattern.compile(openingTagRx).matcher(text);
    int pos = 0;
    final Ref<Integer> textOffset = Ref.create(0);
    while (matcher.find(pos)) {
      textOffset.set(textOffset.get() + matcher.start() - pos);
      pos = extractExpectedHighlight(matcher, text, document, textOffset);
    }
  }
  @CalledInAwt
  @Nullable
  public static <T> T tryComputeFast(
      @NotNull final Function<ProgressIndicator, T> backgroundTask, final int waitMillis) {
    final Ref<T> resultRef = new Ref<T>();
    ProgressIndicator indicator =
        executeAndTryWait(
            new Function<ProgressIndicator, Runnable>() {
              @Override
              public Runnable fun(final ProgressIndicator indicator) {
                final T result = backgroundTask.fun(indicator);
                return new Runnable() {
                  @Override
                  public void run() {
                    resultRef.set(result);
                  }
                };
              }
            },
            null,
            waitMillis,
            false);
    indicator.cancel();

    return resultRef.get();
  }
  @Nullable
  public static MavenDomDependency searchManagingDependency(
      @NotNull final MavenDomDependency dependency, @NotNull final Project project) {
    final DependencyConflictId depId = DependencyConflictId.create(dependency);
    if (depId == null) return null;

    final MavenDomProjectModel model =
        dependency.getParentOfType(MavenDomProjectModel.class, false);
    if (model == null) return null;

    final Ref<MavenDomDependency> res = new Ref<MavenDomDependency>();

    Processor<MavenDomDependency> processor =
        dependency1 -> {
          if (depId.equals(DependencyConflictId.create(dependency1))) {
            res.set(dependency1);
            return true;
          }

          return false;
        };

    processDependenciesInDependencyManagement(model, processor, project);

    return res.get();
  }