@Nullable
 public CvsTabbedWindow openTabbedWindow(final CvsHandler output) {
   if (ApplicationManager.getApplication().isUnitTestMode()) return null;
   if (myProject != null && myProject.isDefault()) return null;
   if (myProject != null) {
     if (myConfiguration != null && myConfiguration.SHOW_OUTPUT && !myIsQuietOperation) {
       if (ApplicationManager.getApplication().isDispatchThread()) {
         connectToOutput(output);
       } else {
         ApplicationManager.getApplication()
             .invokeAndWait(
                 new Runnable() {
                   public void run() {
                     connectToOutput(output);
                   }
                 },
                 ModalityState.defaultModalityState());
       }
     }
     if (!myProject.isDisposed()) {
       return CvsTabbedWindow.getInstance(myProject);
     }
   }
   return null;
 }
 private static void showCircularWarningAndContinue(
     final Project project,
     final Pair<Module, Module> circularModules,
     final Module classModule,
     final Runnable doit) {
   final String message =
       QuickFixBundle.message(
           "orderEntry.fix.circular.dependency.warning",
           classModule.getName(),
           circularModules.getFirst().getName(),
           circularModules.getSecond().getName());
   if (ApplicationManager.getApplication().isUnitTestMode()) throw new RuntimeException(message);
   ApplicationManager.getApplication()
       .invokeLater(
           new Runnable() {
             @Override
             public void run() {
               if (!project.isOpen()) return;
               int ret =
                   Messages.showOkCancelDialog(
                       project,
                       message,
                       QuickFixBundle.message("orderEntry.fix.title.circular.dependency.warning"),
                       Messages.getWarningIcon());
               if (ret == Messages.OK) {
                 ApplicationManager.getApplication().runWriteAction(doit);
               }
             }
           });
 }
  private void attachLibraries(
      @NotNull Collection<VirtualFile> libraryRoots, Set<VirtualFile> exclusions) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (!libraryRoots.isEmpty()) {
      ApplicationManager.getApplication()
          .runWriteAction(
              () -> {
                ModuleRootManager model = ModuleRootManager.getInstance(myModule);
                LibraryOrderEntry goLibraryEntry =
                    OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName());

                if (goLibraryEntry != null && goLibraryEntry.isValid()) {
                  Library library = goLibraryEntry.getLibrary();
                  if (library != null && !((LibraryEx) library).isDisposed()) {
                    fillLibrary(library, libraryRoots, exclusions);
                  }
                } else {
                  LibraryTable libraryTable =
                      LibraryTablesRegistrar.getInstance().getLibraryTable(myModule.getProject());
                  Library library = libraryTable.createLibrary(getLibraryName());
                  fillLibrary(library, libraryRoots, exclusions);
                  ModuleRootModificationUtil.addDependency(myModule, library);
                }
              });
      showNotification(myModule.getProject());
    } else {
      removeLibraryIfNeeded();
    }
  }
 private boolean belongsToScope(final PsiElement psiElement, final boolean ignoreScope) {
   if (psiElement == null || !psiElement.isValid()) return false;
   if (psiElement instanceof PsiCompiledElement) return false;
   final PsiFile containingFile =
       ApplicationManager.getApplication()
           .runReadAction(
               new Computable<PsiFile>() {
                 @Override
                 public PsiFile compute() {
                   return psiElement.getContainingFile();
                 }
               });
   if (containingFile == null) {
     return false;
   }
   for (RefManagerExtension extension : myExtensions.values()) {
     if (!extension.belongsToScope(psiElement)) return false;
   }
   final Boolean inProject =
       ApplicationManager.getApplication()
           .runReadAction(
               new Computable<Boolean>() {
                 @Override
                 public Boolean compute() {
                   return psiElement.getManager().isInProject(psiElement);
                 }
               });
   return inProject.booleanValue()
       && (ignoreScope || getScope() == null || getScope().contains(psiElement));
 }
 @NotNull
 public ExceptionBreakpoint addExceptionBreakpoint(
     @NotNull final String exceptionClassName, final String packageName) {
   ApplicationManager.getApplication().assertIsDispatchThread();
   final JavaExceptionBreakpointType type =
       (JavaExceptionBreakpointType)
           XDebuggerUtil.getInstance().findBreakpointType(JavaExceptionBreakpointType.class);
   return ApplicationManager.getApplication()
       .runWriteAction(
           new Computable<ExceptionBreakpoint>() {
             @Override
             public ExceptionBreakpoint compute() {
               XBreakpoint<JavaExceptionBreakpointProperties> xBreakpoint =
                   XDebuggerManager.getInstance(myProject)
                       .getBreakpointManager()
                       .addBreakpoint(
                           type,
                           new JavaExceptionBreakpointProperties(exceptionClassName, packageName));
               ExceptionBreakpoint breakpoint =
                   new ExceptionBreakpoint(
                       myProject, exceptionClassName, packageName, xBreakpoint);
               addBreakpoint(breakpoint);
               if (LOG.isDebugEnabled()) {
                 LOG.debug("ExceptionBreakpoint Added");
               }
               return breakpoint;
             }
           });
 }
  @Override
  public void initComponent() {
    myMode = Registry.get("ide.tooltip.mode");

    myIsEnabled = Registry.get("ide.tooltip.callout");
    myIsEnabled.addListener(
        new RegistryValueListener.Adapter() {
          @Override
          public void afterValueChanged(RegistryValue value) {
            processEnabled();
          }
        },
        ApplicationManager.getApplication());

    Toolkit.getDefaultToolkit()
        .addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);

    ActionManager.getInstance()
        .addAnActionListener(
            new AnActionListener.Adapter() {
              @Override
              public void beforeActionPerformed(
                  AnAction action, DataContext dataContext, AnActionEvent event) {
                hideCurrent(null, action, event);
              }
            },
            ApplicationManager.getApplication());

    processEnabled();
  }
  public synchronized void addItem(final CompletionResult item) {
    if (!isRunning()) return;
    ProgressManager.checkCanceled();

    final boolean unitTestMode = ApplicationManager.getApplication().isUnitTestMode();
    if (!unitTestMode) {
      LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread());
    }

    LOG.assertTrue(myParameters.getPosition().isValid());

    myItemSorters.put(item.getLookupElement(), (CompletionSorterImpl) item.getSorter());
    myLookup.addItem(item.getLookupElement(), item.getPrefixMatcher());
    myCount++;

    if (myCount == 1) {
      new Alarm(Alarm.ThreadToUse.SHARED_THREAD, this)
          .addRequest(
              new Runnable() {
                @Override
                public void run() {
                  myFreezeSemaphore.up();
                }
              },
              300);
    }
    myQueue.queue(myUpdate);
  }
Ejemplo n.º 8
0
  @Override
  public void addMessage(CompilerMessage msg) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      LOG.info("addMessage: " + msg + " this=" + this);
    }

    Collection<CompilerMessage> messages = myMessages.get(msg.getCategory());
    if (messages == null) {
      messages = new LinkedHashSet<CompilerMessage>();
      myMessages.put(msg.getCategory(), messages);
    }
    if (messages.add(msg)) {
      myTask.addMessage(msg);
    }

    if (ApplicationManager.getApplication().isCompilerServerMode()) {
      VirtualFile virtualFile = msg.getVirtualFile();
      CompilerClientConnector.getInstance(myProject)
          .addMessage(
              msg.getCategory(),
              msg.getMessage(),
              virtualFile == null ? null : virtualFile.getPath(),
              msg.getLine(),
              msg.getColumn());
    } else {
      ProblemsView.getInstance(myProject).addMessage(msg);
    }
  }
 protected boolean resultIsValid(
     final Project project,
     ProgressIndicator indicator,
     final String resourceUrl,
     FetchResult result) {
   if (myForceResultIsValid) {
     return true;
   }
   if (!ApplicationManager.getApplication().isUnitTestMode()
       && result.contentType != null
       && result.contentType.contains(HTML_MIME)
       && new String(result.bytes).contains("<html")) {
     ApplicationManager.getApplication()
         .invokeLater(
             () ->
                 Messages.showMessageDialog(
                     project,
                     XmlBundle.message("invalid.url.no.xml.file.at.location", resourceUrl),
                     XmlBundle.message("invalid.url.title"),
                     Messages.getErrorIcon()),
             indicator.getModalityState());
     return false;
   }
   return true;
 }
 public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
   if (editor == null) return;
   // final PsiFile psiFile =
   // PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
   final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
   if (psiFile == null) return;
   CommandProcessor.getInstance()
       .executeCommand(
           project,
           () -> {
             final CodeInsightActionHandler handler = getHandler();
             final Runnable action =
                 () -> {
                   if (!ApplicationManager.getApplication().isUnitTestMode()
                       && !editor.getContentComponent().isShowing()) return;
                   handler.invoke(project, editor, psiFile);
                 };
             if (handler.startInWriteAction()) {
               ApplicationManager.getApplication().runWriteAction(action);
             } else {
               action.run();
             }
           },
           getCommandName(),
           DocCommandGroupId.noneGroupId(editor.getDocument()));
 }
  private void processClose() {
    if (Registry.getInstance().isRestartNeeded()) {
      final ApplicationEx app = (ApplicationEx) ApplicationManager.getApplication();
      final ApplicationInfo info = ApplicationInfo.getInstance();

      final int r =
          Messages.showOkCancelDialog(
              myContent,
              "You need to restart " + info.getVersionName() + " for the changes to take effect",
              "Restart Required",
              app.isRestartCapable() ? "Restart Now" : "Shutdown Now",
              app.isRestartCapable() ? "Restart Later" : "Shutdown Later",
              Messages.getQuestionIcon());

      if (r == Messages.OK) {
        ApplicationManager.getApplication()
            .invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    app.restart(true);
                  }
                },
                ModalityState.NON_MODAL);
      }
    }
  }
  public void testInitializingDoesntTakeReadAction() throws Exception {
    // make sure all components are initialized to prevent deadlocks
    MavenServerManager.getInstance().getOrCreateWrappee();

    ApplicationManager.getApplication()
        .runWriteAction(
            () -> {
              Future result =
                  ApplicationManager.getApplication()
                      .executeOnPooledThread(
                          () -> {
                            MavenServerManager.getInstance().shutdown(true);
                            try {
                              MavenServerManager.getInstance().getOrCreateWrappee();
                            } catch (RemoteException e) {
                              throw new RuntimeException(e);
                            }
                          });

              try {
                result.get(10, TimeUnit.SECONDS);
              } catch (InterruptedException e) {
                throw new RuntimeException(e);
              } catch (java.util.concurrent.ExecutionException e) {
                throw new RuntimeException(e);
              } catch (TimeoutException e) {
                printThreadDump();
                throw new RuntimeException(e);
              }
              result.cancel(true);
            });
  }
 public void updateIssues(final @Nullable Runnable onComplete) {
   TaskRepository first =
       ContainerUtil.find(
           getAllRepositories(),
           new Condition<TaskRepository>() {
             public boolean value(TaskRepository repository) {
               return repository.isConfigured();
             }
           });
   if (first == null) {
     myIssueCache.clear();
     if (onComplete != null) {
       onComplete.run();
     }
     return;
   }
   myUpdating = true;
   if (ApplicationManager.getApplication().isUnitTestMode()) {
     doUpdate(onComplete);
   } else {
     ApplicationManager.getApplication()
         .executeOnPooledThread(
             new Runnable() {
               public void run() {
                 doUpdate(onComplete);
               }
             });
   }
 }
Ejemplo n.º 14
0
 /** @return were javadoc params used */
 public static void collectAnnotationValues(
     final Map<String, Collection<String>> results, PsiMethod[] psiMethods, PsiClass... classes) {
   final Set<String> test = new HashSet<>(1);
   test.add(TEST_ANNOTATION_FQN);
   ContainerUtil.addAll(test, CONFIG_ANNOTATIONS_FQN);
   if (psiMethods != null) {
     for (final PsiMethod psiMethod : psiMethods) {
       ApplicationManager.getApplication()
           .runReadAction(
               () ->
                   appendAnnotationAttributeValues(
                       results, AnnotationUtil.findAnnotation(psiMethod, test), psiMethod));
     }
   } else {
     for (final PsiClass psiClass : classes) {
       ApplicationManager.getApplication()
           .runReadAction(
               () -> {
                 if (psiClass != null && hasTest(psiClass)) {
                   appendAnnotationAttributeValues(
                       results, AnnotationUtil.findAnnotation(psiClass, test), psiClass);
                   PsiMethod[] methods = psiClass.getMethods();
                   for (PsiMethod method : methods) {
                     if (method != null) {
                       appendAnnotationAttributeValues(
                           results, AnnotationUtil.findAnnotation(method, test), method);
                     }
                   }
                 }
               });
     }
   }
 }
 private void awaitTermination(@NotNull Runnable request, long delayMillis) {
   if (ApplicationManager.getApplication().isUnitTestMode()) {
     ApplicationManager.getApplication().invokeLater(request, ModalityState.any());
   } else {
     myAwaitingTerminationAlarm.addRequest(request, delayMillis);
   }
 }
  @Nullable
  private static FetchResult fetchData(
      final Project project, final String dtdUrl, final ProgressIndicator indicator)
      throws IOException {
    try {
      return HttpRequests.request(dtdUrl)
          .accept("text/xml,application/xml,text/html,*/*")
          .connect(
              new HttpRequests.RequestProcessor<FetchResult>() {
                @Override
                public FetchResult process(@NotNull HttpRequests.Request request)
                    throws IOException {
                  FetchResult result = new FetchResult();
                  result.bytes = request.readBytes(indicator);
                  result.contentType = request.getConnection().getContentType();
                  return result;
                }
              });
    } catch (MalformedURLException e) {
      if (!ApplicationManager.getApplication().isUnitTestMode()) {
        ApplicationManager.getApplication()
            .invokeLater(
                () ->
                    Messages.showMessageDialog(
                        project,
                        XmlBundle.message("invalid.url.message", dtdUrl),
                        XmlBundle.message("invalid.url.title"),
                        Messages.getErrorIcon()),
                indicator.getModalityState());
      }
    }

    return null;
  }
Ejemplo n.º 17
0
 public void markSelectionTouched() {
   if (!ApplicationManager.getApplication().isUnitTestMode()) {
     ApplicationManager.getApplication().assertIsDispatchThread();
   }
   mySelectionTouched = true;
   myList.repaint();
 }
Ejemplo n.º 18
0
  public void addMessage(final CompilerMessage message) {
    prepareMessageView();

    final CompilerMessageCategory messageCategory = message.getCategory();
    if (CompilerMessageCategory.WARNING.equals(messageCategory)) {
      myWarningCount += 1;
    } else if (CompilerMessageCategory.ERROR.equals(messageCategory)) {
      myErrorCount += 1;
      informWolf(message);
    }

    if (ApplicationManager.getApplication().isDispatchThread()) {
      openMessageView();
      doAddMessage(message);
    } else {
      final Window window = getWindow();
      final ModalityState modalityState =
          window != null ? ModalityState.stateForComponent(window) : ModalityState.NON_MODAL;
      ApplicationManager.getApplication()
          .invokeLater(
              new Runnable() {
                public void run() {
                  if (!myProject.isDisposed()) {
                    openMessageView();
                    doAddMessage(message);
                  }
                }
              },
              modalityState);
    }
  }
 private static void checkNoWriteAccess() {
   if (!ApplicationManager.getApplication().isUnitTestMode()) {
     if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
       throw new AssertionError("Completion should not be invoked inside write action");
     }
   }
 }
 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();
 }
Ejemplo n.º 21
0
 public static void invoke(Runnable runnable) {
   if (ApplicationManager.getApplication().isDispatchThread()) {
     runnable.run();
   } else {
     ApplicationManager.getApplication().invokeLater(runnable, ModalityState.NON_MODAL);
   }
 }
  private boolean tryToReloadApplication() {
    try {
      final Application app = ApplicationManager.getApplication();

      if (app.isDisposed()) return false;
      final HashSet<Pair<VirtualFile, StateStorage>> causes =
          new HashSet<Pair<VirtualFile, StateStorage>>(myChangedApplicationFiles);
      if (causes.isEmpty()) return true;

      final boolean[] reloadOk = {false};
      final LinkedHashSet<String> components = new LinkedHashSet<String>();

      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    reloadOk[0] =
                        ((ApplicationImpl) app).getStateStore().reload(causes, components);
                  } catch (StateStorageException e) {
                    Messages.showWarningDialog(
                        ProjectBundle.message("project.reload.failed", e.getMessage()),
                        ProjectBundle.message("project.reload.failed.title"));
                  } catch (IOException e) {
                    Messages.showWarningDialog(
                        ProjectBundle.message("project.reload.failed", e.getMessage()),
                        ProjectBundle.message("project.reload.failed.title"));
                  }
                }
              });

      if (!reloadOk[0] && !components.isEmpty()) {
        String message = "Application components were changed externally and cannot be reloaded:\n";
        for (String component : components) {
          message += component + "\n";
        }

        final boolean canRestart = ApplicationManager.getApplication().isRestartCapable();
        message += "Would you like to " + (canRestart ? "restart " : "shutdown ");
        message += ApplicationNamesInfo.getInstance().getProductName() + "?";

        if (Messages.showYesNoDialog(
                message, "Application Configuration Reload", Messages.getQuestionIcon())
            == Messages.YES) {
          for (Pair<VirtualFile, StateStorage> cause : causes) {
            StateStorage stateStorage = cause.getSecond();
            if (stateStorage instanceof XmlElementStorage) {
              ((XmlElementStorage) stateStorage).disableSaving();
            }
          }
          ApplicationManagerEx.getApplicationEx().restart(true);
        }
      }

      return reloadOk[0];
    } finally {
      myChangedApplicationFiles.clear();
    }
  }
  @Override
  public void waitForConnect() throws Exception {
    try {
      //noinspection SocketOpenedButNotSafelyClosed
      final Socket socket = myServerSocket.accept();

      ApplicationManager.getApplication()
          .executeOnPooledThread(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    // do we need any synchronization here with myMainDebugger.waitForConnect() ???
                    // TODO
                    sendDebuggerPort(socket, myDebugServerSocket, myDebugProcess);
                  } catch (Exception e) {
                    throw new RuntimeException(e);
                  }
                }
              });

      myMainDebugger.waitForConnect();

      disposeAcceptor();

      myDebugProcessAcceptor = new DebuggerProcessAcceptor(this, myServerSocket);
      ApplicationManager.getApplication().executeOnPooledThread(myDebugProcessAcceptor);
    } finally {

    }
  }
Ejemplo n.º 24
0
 @Override
 public void documentChanged(DocumentEvent e) {
   UndoManager undoManager = UndoManager.getInstance(myProject);
   boolean undoOrRedo = undoManager.isUndoInProgress() || undoManager.isRedoInProgress();
   if (undoOrRedo) {
     // allow undo/redo up until 'creation stamp' back in time
     // and check it after action is completed
     if (e.getDocument() == myOrigDocument) {
       //noinspection SSBasedInspection
       SwingUtilities.invokeLater(
           () -> {
             if (myOrigCreationStamp > myOrigDocument.getModificationStamp()) {
               closeEditor();
             }
           });
     }
   } else if (e.getDocument() == myNewDocument) {
     commitToOriginal(e);
     if (!isValid()) {
       ApplicationManager.getApplication()
           .invokeLater(() -> closeEditor(), myProject.getDisposed());
     }
   } else if (e.getDocument() == myOrigDocument) {
     if (myCommittingToOriginal || myAltFullRange != null && myAltFullRange.isValid()) return;
     ApplicationManager.getApplication().invokeLater(() -> closeEditor(), myProject.getDisposed());
   }
 }
  public synchronized void addItem(final CompletionResult item) {
    if (!isRunning()) return;
    ProgressManager.checkCanceled();

    final boolean unitTestMode = ApplicationManager.getApplication().isUnitTestMode();
    if (!unitTestMode) {
      LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread());
    }

    LOG.assertTrue(myParameters.getPosition().isValid());

    myItemSorters.put(item.getLookupElement(), (CompletionSorterImpl) item.getSorter());
    myLookup.addItem(item.getLookupElement(), item.getPrefixMatcher());
    myCount++;

    if (myCount == 1) {
      ApplicationManager.getApplication()
          .executeOnPooledThread(
              new Runnable() {
                public void run() {
                  try {
                    Thread.sleep(300);
                  } catch (InterruptedException ignore) {
                  } finally {
                    myFreezeSemaphore.up();
                  }
                }
              });
    }
    myQueue.queue(myUpdate);
  }
Ejemplo n.º 26
0
  @NotNull
  private static PsiElement deleteTemplateKey(
      @NotNull final PsiFile file,
      @NotNull final Document document,
      final int currentOffset,
      @NotNull final String key) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    final int startOffset = currentOffset - key.length();
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                CommandProcessor.getInstance()
                    .runUndoTransparentAction(
                        new Runnable() {
                          public void run() {
                            document.deleteString(startOffset, currentOffset);
                            PsiDocumentManager.getInstance(file.getProject())
                                .commitDocument(document);
                          }
                        });
              }
            });
    return CustomTemplateCallback.getContext(file, startOffset > 0 ? startOffset - 1 : startOffset);
  }
  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());
    }
  }
Ejemplo n.º 28
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();
  }
  private void removeLibraryIfNeeded() {
    ApplicationManager.getApplication().assertIsDispatchThread();

    ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance();
    ModifiableRootModel model = modelsProvider.getModuleModifiableModel(myModule);
    LibraryOrderEntry goLibraryEntry =
        OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName());
    if (goLibraryEntry != null) {
      ApplicationManager.getApplication()
          .runWriteAction(
              () -> {
                Library library = goLibraryEntry.getLibrary();
                if (library != null) {
                  LibraryTable table = library.getTable();
                  if (table != null) {
                    table.removeLibrary(library);
                    model.removeOrderEntry(goLibraryEntry);
                    modelsProvider.commitModuleModifiableModel(model);
                  }
                } else {
                  modelsProvider.disposeModuleModifiableModel(model);
                }
              });
    } else {
      ApplicationManager.getApplication()
          .runWriteAction(() -> modelsProvider.disposeModuleModifiableModel(model));
    }
  }
Ejemplo n.º 30
0
  @NotNull
  public static Library updatePackagesLibraryRoots(
      @NotNull final Project project, @NotNull final DartLibInfo libInfo) {
    final LibraryTable projectLibraryTable = ProjectLibraryTable.getInstance(project);
    final Library existingLibrary =
        projectLibraryTable.getLibraryByName(DartPackagesLibraryType.DART_PACKAGES_LIBRARY_NAME);
    final Library library =
        existingLibrary != null
            ? existingLibrary
            : ApplicationManager.getApplication()
                .runWriteAction(
                    new Computable<Library>() {
                      @Override
                      public Library compute() {
                        final LibraryTableBase.ModifiableModel libTableModel =
                            ProjectLibraryTable.getInstance(project).getModifiableModel();
                        final Library lib =
                            libTableModel.createLibrary(
                                DartPackagesLibraryType.DART_PACKAGES_LIBRARY_NAME,
                                DartPackagesLibraryType.LIBRARY_KIND);
                        libTableModel.commit();
                        return lib;
                      }
                    });

    final String[] existingUrls = library.getUrls(OrderRootType.CLASSES);

    final Collection<String> libRootUrls = libInfo.getLibRootUrls();

    if ((!libInfo.isProjectWithoutPubspec()
            && isBrokenPackageMap(((LibraryEx) library).getProperties()))
        || existingUrls.length != libRootUrls.size()
        || !libRootUrls.containsAll(Arrays.asList(existingUrls))) {
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  final LibraryEx.ModifiableModelEx model =
                      (LibraryEx.ModifiableModelEx) library.getModifiableModel();
                  for (String url : existingUrls) {
                    model.removeRoot(url, OrderRootType.CLASSES);
                  }

                  for (String url : libRootUrls) {
                    model.addRoot(url, OrderRootType.CLASSES);
                  }

                  final DartPackagesLibraryProperties libraryProperties =
                      new DartPackagesLibraryProperties();
                  libraryProperties.setPackageNameToDirsMap(libInfo.getPackagesMap());
                  model.setProperties(libraryProperties);

                  model.commit();
                }
              });
    }

    return library;
  }