@Override
  public boolean canPutAt(
      @NotNull final VirtualFile file, final int line, @NotNull final Project project) {
    final Ref<Boolean> stoppable = Ref.create(false);
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document != null) {
      if (file.getFileType() == PythonFileType.INSTANCE) {
        XDebuggerUtil.getInstance()
            .iterateLine(
                project,
                document,
                line,
                new Processor<PsiElement>() {
                  @Override
                  public boolean process(PsiElement psiElement) {
                    if (psiElement instanceof PsiWhiteSpace || psiElement instanceof PsiComment)
                      return true;
                    if (psiElement.getNode() != null
                        && notStoppableElementType(psiElement.getNode().getElementType()))
                      return true;

                    // Python debugger seems to be able to stop on pretty much everything
                    stoppable.set(true);
                    return false;
                  }
                });

        if (PyDebugSupportUtils.isContinuationLine(document, line - 1)) {
          stoppable.set(false);
        }
      }
    }

    return stoppable.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;
 }
 @Nullable
 @Override
 public Ref<PyType> getReturnType(@NotNull PyCallable callable, @NotNull TypeEvalContext context) {
   if (callable instanceof PyFunction) {
     final PyFunction function = (PyFunction) callable;
     final PyAnnotation annotation = function.getAnnotation();
     if (annotation != null) {
       // XXX: Requires switching from stub to AST
       final PyExpression value = annotation.getValue();
       if (value != null) {
         final PyType type = getType(value, new Context(context));
         return type != null ? Ref.create(type) : null;
       }
     }
     final PyType constructorType = getGenericConstructorType(function, new Context(context));
     if (constructorType != null) {
       return Ref.create(constructorType);
     }
     final String comment = function.getTypeCommentAnnotation();
     if (comment != null) {
       final PyTypeParser.ParseResult result =
           PyTypeParser.parsePep484FunctionTypeComment(callable, comment);
       final PyCallableType funcType = as(result.getType(), PyCallableType.class);
       if (funcType != null) {
         return Ref.create(funcType.getReturnType(context));
       }
     }
   }
   return null;
 }
 @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;
 }
 @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;
 }
Example #6
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();
  }
Example #7
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());
 }
 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();
 }
  @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
 @Override
 public TextRange getExpressionRangeAtOffset(
     final Project project,
     final Document document,
     final int offset,
     final boolean sideEffectsAllowed) {
   final Ref<TextRange> currentRange = Ref.create(null);
   PsiDocumentManager.getInstance(project)
       .commitAndRunReadAction(
           new Runnable() {
             @Override
             public void run() {
               try {
                 PsiElement elementAtCursor =
                     DebuggerUtilsEx.findElementAt(
                         PsiDocumentManager.getInstance(project).getPsiFile(document), offset);
                 if (elementAtCursor == null || !elementAtCursor.isValid()) {
                   return;
                 }
                 Pair<PsiElement, TextRange> pair =
                     findExpression(elementAtCursor, sideEffectsAllowed);
                 if (pair != null) {
                   currentRange.set(pair.getSecond());
                 }
               } catch (IndexNotReadyException ignored) {
               }
             }
           });
   return currentRange.get();
 }
 @Nullable
 private Ref<PyType> getTypeOfProperty(
     @Nullable PyType qualifierType, @NotNull String name, @NotNull TypeEvalContext context) {
   if (qualifierType instanceof PyClassType) {
     final PyClassType classType = (PyClassType) qualifierType;
     PyClass pyClass = classType.getPyClass();
     Property property = pyClass.findProperty(name, true);
     if (property != null) {
       if (classType.isDefinition()) {
         return Ref.<PyType>create(
             PyBuiltinCache.getInstance(pyClass).getObjectType(PyNames.PROPERTY));
       }
       if (AccessDirection.of(this) == AccessDirection.READ) {
         final PyType type = property.getType(context);
         if (type != null) {
           return Ref.create(type);
         }
       }
       return Ref.create();
     }
   } else if (qualifierType instanceof PyUnionType) {
     final PyUnionType unionType = (PyUnionType) qualifierType;
     for (PyType type : unionType.getMembers()) {
       final Ref<PyType> result = getTypeOfProperty(type, name, context);
       if (result != null) {
         return result;
       }
     }
   }
   return null;
 }
  @NotNull
  @Override
  protected JBPopup createPopup(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    if (project == null) project = ProjectManager.getInstance().getDefaultProject();

    Ref<JBPopup> popup = new Ref<JBPopup>();
    ChangesBrowser cb = new MyChangesBrowser(project, getChanges(), getCurrentSelection(), popup);

    popup.set(
        JBPopupFactory.getInstance()
            .createComponentPopupBuilder(cb, cb.getPreferredFocusedComponent())
            .setResizable(true)
            .setModalContext(false)
            .setFocusable(true)
            .setRequestFocus(true)
            .setCancelOnWindowDeactivation(true)
            .setCancelOnOtherWindowOpen(true)
            .setMovable(true)
            .setCancelKeyEnabled(true)
            .setCancelOnClickOutside(true)
            .setDimensionServiceKey(project, "Diff.GoToChangePopup", false)
            .createPopup());

    return popup.get();
  }
  @Override
  public boolean isInContext(@NotNull final PsiFile file, final int offset) {
    PsiElement at = file.findElementAt(offset);
    if (at == null && offset == file.getTextLength()) {
      at = file.findElementAt(offset - 1);
    }
    Language language = at != null ? at.getParent().getLanguage() : null;

    if (language instanceof XMLLanguage) {
      final PsiLanguageInjectionHost host =
          PsiTreeUtil.getParentOfType(at, PsiLanguageInjectionHost.class, false);

      if (host != null) {
        final Ref<Boolean> hasJsInjection = new Ref<Boolean>(Boolean.FALSE);

        InjectedLanguageUtil.enumerate(
            host,
            new JSResolveUtil.JSInjectedFilesVisitor() {
              @Override
              protected void process(final JSFile file) {
                hasJsInjection.set(Boolean.TRUE);
              }
            });

        if (hasJsInjection.get()) {
          language = JavaScriptSupportLoader.JAVASCRIPT.getLanguage();
        }
      }
    }
    return language != null && language.isKindOf(JavaScriptSupportLoader.JAVASCRIPT.getLanguage());
  }
  static void invokeAndWait(
      @NotNull final Runnable runnable, @NotNull ModalityState modalityState) {
    LOG.assertTrue(!isDispatchThread());

    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    final Ref<Throwable> exception = Ref.create();
    Runnable runnable1 =
        new Runnable() {
          @Override
          public void run() {
            try {
              runnable.run();
            } catch (Throwable e) {
              exception.set(e);
            } finally {
              semaphore.up();
            }
          }

          @Override
          @NonNls
          public String toString() {
            return "InvokeAndWait[" + runnable + "]";
          }
        };
    invokeLater(runnable1, modalityState);
    semaphore.waitFor();
    if (!exception.isNull()) {
      throw new RuntimeException(exception.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();
  }
Example #16
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();
  }
  @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();
  }
Example #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;
  }
  /**
   * 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);
    }
  }
  @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();
  }
  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;
  }
 private boolean getExistingInfo(Ref<RunningInfo> ref, Pair<Target, Parameters> key) {
   Info info;
   synchronized (myProcMap) {
     info = myProcMap.get(key);
     try {
       while (info != null
           && (!(info instanceof RunningInfo)
               || info.handler.isProcessTerminating()
               || info.handler.isProcessTerminated())) {
         myProcMap.wait(1000);
         ProgressManager.checkCanceled();
         info = myProcMap.get(key);
       }
     } catch (InterruptedException e) {
       ProgressManager.checkCanceled();
     }
     if (info == null) {
       myProcMap.put(key, new PendingInfo(ref, null));
     }
   }
   if (info instanceof RunningInfo) {
     //noinspection SynchronizationOnLocalVariableOrMethodParameter
     synchronized (ref) {
       ref.set((RunningInfo) info);
       ref.notifyAll();
     }
   }
   return info != null;
 }
  @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();
  }
 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();
 }
  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());
    }
  }
  @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();
  }
  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();
  }
  private CompletionInitializationContext runContributorsBeforeCompletion(
      Editor editor, PsiFile psiFile, int invocationCount, Caret caret) {
    final Ref<CompletionContributor> current = Ref.create(null);
    CompletionInitializationContext context =
        new CompletionInitializationContext(
            editor, caret, psiFile, myCompletionType, invocationCount) {
          CompletionContributor dummyIdentifierChanger;

          @Override
          public void setDummyIdentifier(@NotNull String dummyIdentifier) {
            super.setDummyIdentifier(dummyIdentifier);

            if (dummyIdentifierChanger != null) {
              LOG.error(
                  "Changing the dummy identifier twice, already changed by "
                      + dummyIdentifierChanger);
            }
            dummyIdentifierChanger = current.get();
          }
        };
    List<CompletionContributor> contributors =
        CompletionContributor.forLanguage(context.getPositionLanguage());
    Project project = psiFile.getProject();
    List<CompletionContributor> filteredContributors =
        DumbService.getInstance(project).filterByDumbAwareness(contributors);
    for (final CompletionContributor contributor : filteredContributors) {
      current.set(contributor);
      contributor.beforeCompletion(context);
      CompletionAssertions.checkEditorValid(editor);
      assert !PsiDocumentManager.getInstance(project).isUncommited(editor.getDocument())
          : "Contributor " + contributor + " left the document uncommitted";
    }
    return context;
  }
 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;
 }
  @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();
  }