コード例 #1
0
  private void detectAndDisconnectLoops(@NotNull TopDownAnalysisContext c) {
    // Loop detection and disconnection
    List<Runnable> tasks = new ArrayList<Runnable>();
    for (final MutableClassDescriptorLite klass : c.getClassesTopologicalOrder()) {
      for (final JetType supertype : klass.getSupertypes()) {
        ClassifierDescriptor supertypeDescriptor =
            supertype.getConstructor().getDeclarationDescriptor();
        if (supertypeDescriptor instanceof MutableClassDescriptorLite) {
          MutableClassDescriptorLite superclass = (MutableClassDescriptorLite) supertypeDescriptor;
          if (isReachable(superclass, klass, new HashSet<ClassDescriptor>())) {
            tasks.add(
                new Runnable() {
                  @Override
                  public void run() {
                    klass.getSupertypes().remove(supertype);
                  }
                });
            reportCyclicInheritanceHierarchyError(trace, klass, superclass);
          }
        }
      }
    }

    for (Runnable task : tasks) {
      task.run();
    }
  }
コード例 #2
0
  @Nullable
  public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) {
    final PsiClass[][] holder = new PsiClass[1][];
    final Runnable process =
        () -> {
          final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();

          final Collection<PsiClass> set = new LinkedHashSet<>();
          final PsiManager manager = PsiManager.getInstance(filter.getProject());
          final GlobalSearchScope projectScope =
              GlobalSearchScope.projectScope(manager.getProject());
          final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope());
          for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) {
            if (filter.isAccepted(psiClass)) {
              if (indicator != null) {
                indicator.setText2(
                    "Found test class " + ReadAction.compute(psiClass::getQualifiedName));
              }
              set.add(psiClass);
            }
          }
          holder[0] = set.toArray(new PsiClass[set.size()]);
        };
    if (sync) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, "Searching For Tests...", true, filter.getProject());
    } else {
      process.run();
    }
    return holder[0];
  }
コード例 #3
0
  /**
   * sets the window passed as a current ('focused') window among all splitters. All file openings
   * will be done inside this current window
   *
   * @param window a window to be set as current
   * @param requestFocus whether to request focus to the editor currently selected in this window
   */
  public void setCurrentWindow(@Nullable final EditorWindow window, final boolean requestFocus) {
    final EditorWithProviderComposite newEditor =
        window != null ? window.getSelectedEditor() : null;

    Runnable fireRunnable =
        new Runnable() {
          public void run() {
            getManager().fireSelectionChanged(newEditor);
          }
        };

    setCurrentWindow(window);

    getManager().updateFileName(window == null ? null : window.getSelectedFile());

    if (window != null) {
      final EditorWithProviderComposite selectedEditor = window.getSelectedEditor();
      if (selectedEditor != null) {
        fireRunnable.run();
      }

      if (requestFocus) {
        window.requestFocus(true);
      }
    } else {
      fireRunnable.run();
    }
  }
  @SuppressWarnings("unchecked")
  private void executeAndRestoreDefaultProjectSettings(
      @NotNull Project project, @NotNull Runnable task) {
    if (!project.isDefault()) {
      task.run();
      return;
    }

    AbstractExternalSystemSettings systemSettings =
        ExternalSystemApiUtil.getSettings(project, myExternalSystemId);
    Object systemStateToRestore = null;
    if (systemSettings instanceof PersistentStateComponent) {
      systemStateToRestore = ((PersistentStateComponent) systemSettings).getState();
    }
    systemSettings.copyFrom(myControl.getSystemSettings());
    Collection projectSettingsToRestore = systemSettings.getLinkedProjectsSettings();
    systemSettings.setLinkedProjectsSettings(
        Collections.singleton(getCurrentExternalProjectSettings()));
    try {
      task.run();
    } finally {
      if (systemStateToRestore != null) {
        ((PersistentStateComponent) systemSettings).loadState(systemStateToRestore);
      } else {
        systemSettings.setLinkedProjectsSettings(projectSettingsToRestore);
      }
    }
  }
コード例 #5
0
ファイル: RADComponentNode.java プロジェクト: PrimoS/Netbeans
 @Override
 public Node.PropertySet[] getPropertySets() {
   final Node.PropertySet[][] props = new Node.PropertySet[1][];
   Runnable runnable =
       new Runnable() {
         @Override
         public void run() {
           FormLAF.executeWithLAFLocks(
               new Runnable() {
                 @Override
                 public void run() {
                   props[0] = component.getProperties();
                 }
               });
         }
       };
   if (EventQueue.isDispatchThread()) {
     runnable.run();
   } else {
     try {
       // We have made some attempts to keep initialization
       // of properties outside AWT thread, but it always
       // deadlocked with AWT thread for various reasons.
       EventQueue.invokeAndWait(runnable);
     } catch (InterruptedException iex) {
       FormUtils.LOGGER.log(Level.INFO, iex.getMessage(), iex);
     } catch (InvocationTargetException itex) {
       FormUtils.LOGGER.log(Level.INFO, itex.getMessage(), itex);
     }
   }
   return props[0];
 }
コード例 #6
0
 void stop(Runnable callback) {
   if (player != null) {
     new Tween(player.getVolume())
         .tweenToZero(
             0.06,
             10L,
             (curVolume) -> {
               player.setVolume(curVolume);
             },
             (zeroVolume) -> {
               isPlaying = false;
               try {
                 if (currentAudioIn != null) {
                   currentAudioIn.close();
                 }
                 player.stop();
                 callback.run();
               } catch (IOException | IllegalStateException | NullPointerException ex) {
                 log.log(Level.ERROR, null, ex);
               }
             });
   } else {
     callback.run();
   }
 }
コード例 #7
0
 public void fireBreakpointChanged(Breakpoint breakpoint) {
   breakpoint.reload();
   breakpoint.updateUI();
   RequestManagerImpl.updateRequests(breakpoint);
   if (myAllowMulticasting) {
     // can be invoked from non-AWT thread
     myAlarm.cancelAllRequests();
     final Runnable runnable =
         new Runnable() {
           @Override
           public void run() {
             myAlarm.addRequest(
                 new Runnable() {
                   @Override
                   public void run() {
                     myDispatcher.getMulticaster().breakpointsChanged();
                   }
                 },
                 100);
           }
         };
     if (ApplicationManager.getApplication().isDispatchThread()) {
       runnable.run();
     } else {
       SwingUtilities.invokeLater(runnable);
     }
   }
 }
コード例 #8
0
ファイル: HavenPanel.java プロジェクト: ProPuke/hafen-client
 public void run() {
   try {
     uglyjoglhack();
     if (state == null)
       throw (new RuntimeException("State applier is still null after redraw"));
     synchronized (drawfun) {
       drawfun.notifyAll();
     }
     while (true) {
       long then = System.currentTimeMillis();
       int waited = 0;
       synchronized (drawfun) {
         while ((curdraw = bufdraw) == null) drawfun.wait();
         bufdraw = null;
         drawfun.notifyAll();
         waited += System.currentTimeMillis() - then;
       }
       CPUProfile.Frame curf = null;
       if (Config.profile) curdraw.pf = curf = rprof.new Frame();
       uglyjoglhack();
       if (curf != null) {
         curf.tick("aux");
         curf.fin();
       }
       long now = System.currentTimeMillis();
       waited += now - curdraw.doneat;
       ridle = (ridle * 0.95) + (((double) waited / ((double) (now - then))) * 0.05);
       curdraw = null;
     }
   } catch (InterruptedException e) {
     return;
   }
 }
コード例 #9
0
  @Override
  public void compileAndRun(
      @NotNull final Runnable startRunnable,
      @NotNull final ExecutionEnvironment environment,
      @Nullable final RunProfileState state,
      @Nullable final Runnable onCancelRunnable) {
    long id = environment.getExecutionId();
    if (id == 0) {
      id = environment.assignNewExecutionId();
    }

    RunProfile profile = environment.getRunProfile();
    if (!(profile instanceof RunConfiguration)) {
      startRunnable.run();
      return;
    }

    final RunConfiguration runConfiguration = (RunConfiguration) profile;
    final List<BeforeRunTask> beforeRunTasks =
        RunManagerEx.getInstanceEx(myProject).getBeforeRunTasks(runConfiguration);
    if (beforeRunTasks.isEmpty()) {
      startRunnable.run();
    } else {
      DataContext context = environment.getDataContext();
      final DataContext projectContext =
          context != null ? context : SimpleDataContext.getProjectContext(myProject);
      final long finalId = id;
      final Long executionSessionId = new Long(id);
      ApplicationManager.getApplication()
          .executeOnPooledThread(
              () -> {
                for (BeforeRunTask task : beforeRunTasks) {
                  if (myProject.isDisposed()) {
                    return;
                  }
                  @SuppressWarnings("unchecked")
                  BeforeRunTaskProvider<BeforeRunTask> provider =
                      BeforeRunTaskProvider.getProvider(myProject, task.getProviderId());
                  if (provider == null) {
                    LOG.warn(
                        "Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'");
                    continue;
                  }
                  ExecutionEnvironment taskEnvironment =
                      new ExecutionEnvironmentBuilder(environment).contentToReuse(null).build();
                  taskEnvironment.setExecutionId(finalId);
                  EXECUTION_SESSION_ID_KEY.set(taskEnvironment, executionSessionId);
                  if (!provider.executeTask(
                      projectContext, runConfiguration, taskEnvironment, task)) {
                    if (onCancelRunnable != null) {
                      SwingUtilities.invokeLater(onCancelRunnable);
                    }
                    return;
                  }
                }

                doRun(environment, startRunnable);
              });
    }
  }
コード例 #10
0
  private void runAfterCommitActions(@NotNull Document document) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    List<Runnable> list;
    synchronized (ACTION_AFTER_COMMIT) {
      list = document.getUserData(ACTION_AFTER_COMMIT);
      if (list != null) {
        list = new ArrayList<Runnable>(list);
        document.putUserData(ACTION_AFTER_COMMIT, null);
      }
    }
    if (list != null) {
      for (final Runnable runnable : list) {
        runnable.run();
      }
    }

    if (!hasUncommitedDocuments() && !actionsWhenAllDocumentsAreCommitted.isEmpty()) {
      List<Object> keys = new ArrayList<Object>(actionsWhenAllDocumentsAreCommitted.keySet());
      for (Object key : keys) {
        Runnable action = actionsWhenAllDocumentsAreCommitted.remove(key);
        myDocumentCommitProcessor.log("Running after commit runnable: ", null, false, key, action);
        action.run();
      }
    }
  }
コード例 #11
0
ファイル: XmlHelper.java プロジェクト: dkvashninbay/Magicento
  /**
   * @param xmlFile
   * @param tagName
   * @param tagValue
   * @param path hierarchy path, this will be the parent of the new tag, ex: root/node1/node2
   * @return
   */
  public static XmlTag createTagInFile(
      final XmlFile xmlFile,
      String tagName,
      String tagValue,
      String path,
      Map<String, String> attributes) {
    XmlTag root = xmlFile.getRootTag();

    String[] pathElements = path.split("/");

    if (pathElements.length > 0 && pathElements[0].equals(root.getName())) {
      XmlTag lastExistentParent = root;
      String curPath = pathElements[0];
      pathElements =
          (String[])
              ArrayUtils.remove(
                  pathElements, 0); // ArrayUtils.removeElement(pathElements, pathElements[0]);
      for (String curTagName : pathElements) {
        lastExistentParent = lastExistentParent.findFirstSubTag(curTagName);
        if (lastExistentParent == null) {
          lastExistentParent = createTagInFile(xmlFile, curTagName, "", curPath);
          if (lastExistentParent == null) {
            return null;
          }
        }
        curPath += "/" + curTagName;
      }
      final XmlTag newTag = lastExistentParent.createChildTag(tagName, "", tagValue, false);

      if (attributes != null) {
        for (Map.Entry<String, String> entry : attributes.entrySet()) {
          newTag.setAttribute(entry.getKey(), entry.getValue());
        }
      }

      final XmlTag parent = lastExistentParent;
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              new WriteCommandAction.Simple(
                  xmlFile.getProject(), "Create Xml Tag in File", xmlFile) {
                @Override
                protected void run() {

                  //                           newTag = (XmlTag)parent.add(newTag);
                  parent.addAfter(newTag, null);
                }
              }.execute();
            }
          };
      runnable.run();
      // PsiDocumentManager.getInstance(xmlFile.getProject()).commitDocument(document);
      return findSubTag(xmlFile, path + "/" + newTag.getName());

    } else {
      return null;
    }
  }
コード例 #12
0
 /** Retries sending requests. */
 private void retryRequests() {
   retryFuture = null;
   List<Runnable> retries = new ArrayList<>(this.retries);
   this.retries.clear();
   resetMembers();
   for (Runnable retry : retries) {
     retry.run();
   }
 }
コード例 #13
0
 @Override
 public boolean startTemplate(@NotNull Editor editor, char shortcutChar) {
   Runnable runnable = prepareTemplate(editor, shortcutChar, null);
   if (runnable != null) {
     PsiDocumentManager.getInstance(myProject).commitDocument(editor.getDocument());
     runnable.run();
   }
   return runnable != null;
 }
コード例 #14
0
  public void onTestingFinished(@NotNull SMTestProxy.SMRootTestProxy testsRoot) {
    myEndTime = System.currentTimeMillis();

    if (myTotalTestCount == 0) {
      myTotalTestCount = myStartedTestCount;
      myStatusLine.setFraction(1);
    }

    updateStatusLabel(true);
    updateIconProgress(true);

    myAnimator.stopMovie();
    myTreeBuilder.updateFromRoot();

    LvcsHelper.addLabel(this);

    final Runnable onDone =
        new Runnable() {
          @Override
          public void run() {
            myTestsRunning = false;
            final boolean sortByDuration =
                TestConsoleProperties.SORT_BY_DURATION.value(myProperties);
            if (sortByDuration) {
              myTreeBuilder.setStatisticsComparator(myProperties, sortByDuration);
            }
          }
        };
    if (myLastSelected == null) {
      selectAndNotify(myTestsRootNode, onDone);
    } else {
      onDone.run();
    }

    fireOnTestingFinished();

    if (testsRoot.wasTerminated() && myStatusLine.getStatusColor() == ColorProgressBar.GREEN) {
      myStatusLine.setStatusColor(JBColor.LIGHT_GRAY);
    }

    if (testsRoot.isEmptySuite()
        && testsRoot.isTestsReporterAttached()
        && myProperties instanceof SMTRunnerConsoleProperties
        && ((SMTRunnerConsoleProperties) myProperties).fixEmptySuite()) {
      return;
    }
    final TestsUIUtil.TestResultPresentation presentation =
        new TestsUIUtil.TestResultPresentation(testsRoot, myStartTime > 0, null)
            .getPresentation(
                myFailedTestCount,
                myFinishedTestCount - myFailedTestCount - myIgnoredTestCount,
                myTotalTestCount - myFinishedTestCount,
                myIgnoredTestCount);
    TestsUIUtil.notifyByBalloon(myProperties.getProject(), testsRoot, myProperties, presentation);
    addToHistory(testsRoot, myProperties, this);
  }
コード例 #15
0
ファイル: MavenUtil.java プロジェクト: Zeratyl-SK/consulo
  public static MavenTaskHandler runInBackground(
      final Project project, final String title, final boolean cancellable, final MavenTask task) {
    final MavenProgressIndicator indicator = new MavenProgressIndicator();

    Runnable runnable =
        new Runnable() {
          public void run() {
            if (project.isDisposed()) return;

            try {
              task.run(indicator);
            } catch (MavenProcessCanceledException ignore) {
              indicator.cancel();
            } catch (ProcessCanceledException ignore) {
              indicator.cancel();
            }
          }
        };

    if (isNoBackgroundMode()) {
      runnable.run();
      return new MavenTaskHandler() {
        public void waitFor() {}
      };
    } else {
      final Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(runnable);
      final MavenTaskHandler handler =
          new MavenTaskHandler() {
            public void waitFor() {
              try {
                future.get();
              } catch (InterruptedException e) {
                MavenLog.LOG.error(e);
              } catch (ExecutionException e) {
                MavenLog.LOG.error(e);
              }
            }
          };
      invokeLater(
          project,
          new Runnable() {
            public void run() {
              if (future.isDone()) return;
              new Task.Backgroundable(project, title, cancellable) {
                public void run(@NotNull ProgressIndicator i) {
                  indicator.setIndicator(i);
                  handler.waitFor();
                }
              }.queue();
            }
          });
      return handler;
    }
  }
コード例 #16
0
  /** Read and process the log file. */
  public void activateOptions() {
    getLogger().info("activateOptions");
    active = true;
    Runnable runnable =
        new Runnable() {
          public void run() {
            initialize();
            while (reader == null) {
              getLogger().info("attempting to load file: " + getFileURL());
              try {
                reader = new InputStreamReader(new URL(getFileURL()).openStream());
              } catch (FileNotFoundException fnfe) {
                getLogger().info("file not available - will try again");
                synchronized (this) {
                  try {
                    wait(MISSING_FILE_RETRY_MILLIS);
                  } catch (InterruptedException ie) {
                  }
                }
              } catch (IOException ioe) {
                getLogger().warn("unable to load file", ioe);
                return;
              }
            }
            try {
              BufferedReader bufferedReader = new BufferedReader(reader);
              createPattern();
              do {
                process(bufferedReader);
                try {
                  synchronized (this) {
                    wait(waitMillis);
                  }
                } catch (InterruptedException ie) {
                }
                if (tailing) {
                  getLogger().debug("tailing file");
                }
              } while (tailing);

            } catch (IOException ioe) {
              // io exception - probably shut down
              getLogger().info("stream closed");
            }
            getLogger().debug("processing " + path + " complete");
            shutdown();
          }
        };
    if (useCurrentThread) {
      runnable.run();
    } else {
      new Thread(runnable, "LogFilePatternReceiver-" + getName()).start();
    }
  }
コード例 #17
0
ファイル: MainThread.java プロジェクト: utgarda/jogl
  /** invokes the given Runnable */
  public void invoke(boolean wait, Runnable r) {
    if (r == null) {
      return;
    }

    if (NativeWindowFactory.isAWTAvailable()) {
      initAWTReflection();

      // handover to AWT MainThread ..
      try {
        if (((Boolean) ReflectionUtil.callMethod(null, mAWTIsDispatchThread, null))
            .booleanValue()) {
          r.run();
          return;
        }
        if (wait) {
          ReflectionUtil.callMethod(null, mAWTInvokeAndWait, new Object[] {r});
        } else {
          ReflectionUtil.callMethod(null, mAWTInvokeLater, new Object[] {r});
        }
      } catch (Exception e) {
        throw new NativeWindowException(e);
      }
      return;
    }

    // if this main thread is not being used or
    // if this is already the main thread .. just execute.
    if (!isRunning() || mainThread == Thread.currentThread()) {
      r.run();
      return;
    }

    boolean doWait = wait && isRunning() && mainThread != Thread.currentThread();
    Object lock = new Object();
    RunnableTask rTask = new RunnableTask(r, doWait ? lock : null, true);
    Throwable throwable = null;
    synchronized (lock) {
      invokeLater(rTask);
      if (doWait) {
        try {
          lock.wait();
        } catch (InterruptedException ie) {
          throwable = ie;
        }
      }
    }
    if (null == throwable) {
      throwable = rTask.getThrowable();
    }
    if (null != throwable) {
      throw new RuntimeException(throwable);
    }
  }
コード例 #18
0
  /**
   * Emulates pressing <code>Enter</code> at current caret position.
   *
   * @param editor target editor
   * @param project target project
   * @param shifts two-elements array which is expected to be filled with the following info: 1. The
   *     first element holds added lines number; 2. The second element holds added symbols number;
   */
  private static void emulateEnter(
      @NotNull final Editor editor, @NotNull Project project, int[] shifts) {
    final DataContext dataContext = prepareContext(editor.getComponent(), project);
    int caretOffset = editor.getCaretModel().getOffset();
    Document document = editor.getDocument();
    SelectionModel selectionModel = editor.getSelectionModel();
    int startSelectionOffset = 0;
    int endSelectionOffset = 0;
    boolean restoreSelection = selectionModel.hasSelection();
    if (restoreSelection) {
      startSelectionOffset = selectionModel.getSelectionStart();
      endSelectionOffset = selectionModel.getSelectionEnd();
      selectionModel.removeSelection();
    }
    int textLengthBeforeWrap = document.getTextLength();
    int lineCountBeforeWrap = document.getLineCount();

    DataManager.getInstance()
        .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, true);
    CommandProcessor commandProcessor = CommandProcessor.getInstance();
    try {
      Runnable command =
          new Runnable() {
            @Override
            public void run() {
              EditorActionManager.getInstance()
                  .getActionHandler(IdeActions.ACTION_EDITOR_ENTER)
                  .execute(editor, dataContext);
            }
          };
      if (commandProcessor.getCurrentCommand() == null) {
        commandProcessor.executeCommand(editor.getProject(), command, WRAP_LINE_COMMAND_NAME, null);
      } else {
        command.run();
      }
    } finally {
      DataManager.getInstance()
          .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, null);
    }
    int symbolsDiff = document.getTextLength() - textLengthBeforeWrap;
    if (restoreSelection) {
      int newSelectionStart = startSelectionOffset;
      int newSelectionEnd = endSelectionOffset;
      if (startSelectionOffset >= caretOffset) {
        newSelectionStart += symbolsDiff;
      }
      if (endSelectionOffset >= caretOffset) {
        newSelectionEnd += symbolsDiff;
      }
      selectionModel.setSelection(newSelectionStart, newSelectionEnd);
    }
    shifts[0] = document.getLineCount() - lineCountBeforeWrap;
    shifts[1] = symbolsDiff;
  }
コード例 #19
0
ファイル: SavePoint.java プロジェクト: borisbrodski/jmockit
  public synchronized void rollback() {
    if (rollbackActions != null) {
      for (Runnable action : rollbackActions) {
        action.run();
      }
    }

    MockFixture mockFixture = TestRun.mockFixture();
    mockFixture.restoreTransformedClasses(previousTransformedClasses);
    mockFixture.restoreRedefinedClasses(previousRedefinedClasses);
    TestRun.getMockClasses().getRegularMocks().removeInstances(previousMockInstancesCount);
  }
コード例 #20
0
ファイル: Utils.java プロジェクト: Bama4255/IRC-Extended
 public void run() {
   try {
     while (true) {
       Runnable cur;
       synchronized (q) {
         while ((cur = q.poll()) == null) q.wait();
       }
       cur.run();
       cur = null;
     }
   } catch (InterruptedException e) {
   }
 }
コード例 #21
0
 /**
  * Determines if the given DataObject has an opened editor
  *
  * @param dataObject
  * @return true if the given DataObject has an opened editor. Otherwise false.
  * @throws InterruptedException
  * @throws InvocationTargetException
  */
 private boolean hasOpenedEditorPanes(final DataObject dataObject)
     throws InterruptedException, InvocationTargetException {
   final boolean[] hasEditorPanes = new boolean[] {false};
   Runnable r =
       new Runnable() {
         @Override
         public void run() {
           final EditorCookie cookie = dataObject.getLookup().lookup(EditorCookie.class);
           if (cookie != null) {
             // hack - care only about dataObjects with opened editors.
             // otherwise we won't assume it's file were opened to be edited
             JEditorPane pane = NbDocument.findRecentEditorPane(cookie);
             if (pane == null) {
               if (cookie instanceof EditorCookie.Observable) {
                 final EditorCookie.Observable o = (EditorCookie.Observable) cookie;
                 PropertyChangeListener l =
                     new PropertyChangeListener() {
                       @Override
                       public void propertyChange(PropertyChangeEvent evt) {
                         if (EditorCookie.Observable.PROP_OPENED_PANES.equals(
                             evt.getPropertyName())) {
                           addOpenedFiles(getFiles(dataObject));
                           o.removePropertyChangeListener(this);
                         }
                       }
                     };
                 o.addPropertyChangeListener(l);
                 pane = NbDocument.findRecentEditorPane(cookie);
                 if (pane != null) {
                   hasEditorPanes[0] = true;
                   o.removePropertyChangeListener(l);
                 }
               } else {
                 JEditorPane[] panes = cookie.getOpenedPanes();
                 hasEditorPanes[0] = panes != null && panes.length > 0;
               }
             } else {
               hasEditorPanes[0] = true;
             }
           }
         }
       };
   if (SwingUtilities.isEventDispatchThread()) {
     r.run();
   } else {
     SwingUtilities.invokeAndWait(r);
   }
   return hasEditorPanes[0];
 }
コード例 #22
0
 /**
  * Cancel previously registered action and schedules (new) action to be executed when all
  * documents are committed.
  *
  * @param key the (unique) id of the action.
  * @param action The action to be executed after automatic commit. This action will overwrite any
  *     action which was registered under this key earlier. The action will be executed in EDT.
  * @return true if action has been run immediately, or false if action was scheduled for execution
  *     later.
  */
 public boolean cancelAndRunWhenAllCommitted(
     @NonNls @NotNull Object key, @NotNull final Runnable action) {
   ApplicationManager.getApplication().assertIsDispatchThread();
   if (myProject.isDisposed()) {
     action.run();
     return true;
   }
   if (myUncommittedDocuments.isEmpty()) {
     action.run();
     assert actionsWhenAllDocumentsAreCommitted.isEmpty() : actionsWhenAllDocumentsAreCommitted;
     return true;
   }
   actionsWhenAllDocumentsAreCommitted.put(key, action);
   return false;
 }
コード例 #23
0
 public void resumeInteractions() {
   myAvailabilityNotificationsActive = true;
   ExtensionPoint[] extensionPoints = getExtensionPoints();
   for (ExtensionPoint extensionPoint : extensionPoints) {
     extensionPoint.getExtensions(); // creates extensions from ComponentAdapters
   }
   for (Runnable action : mySuspendedListenerActions) {
     try {
       action.run();
     } catch (Exception e) {
       myLogger.error(e);
     }
   }
   mySuspendedListenerActions.clear();
 }
コード例 #24
0
 protected void doRun(
     @NotNull final ExecutionEnvironment environment, @NotNull final Runnable startRunnable) {
   Boolean allowSkipRun = environment.getUserData(EXECUTION_SKIP_RUN);
   if (allowSkipRun != null && allowSkipRun) {
     environment
         .getProject()
         .getMessageBus()
         .syncPublisher(EXECUTION_TOPIC)
         .processNotStarted(environment.getExecutor().getId(), environment);
   } else {
     // important! Do not use DumbService.smartInvokeLater here because it depends on modality
     // state
     // and execution of startRunnable could be skipped if modality state check fails
     //noinspection SSBasedInspection
     SwingUtilities.invokeLater(
         () -> {
           if (!myProject.isDisposed()) {
             if (!Registry.is("dumb.aware.run.configurations")) {
               DumbService.getInstance(myProject).runWhenSmart(startRunnable);
             } else {
               try {
                 DumbService.getInstance(myProject).setAlternativeResolveEnabled(true);
                 startRunnable.run();
               } catch (IndexNotReadyException ignored) {
                 ExecutionUtil.handleExecutionError(
                     environment,
                     new ExecutionException("cannot start while indexing is in progress."));
               } finally {
                 DumbService.getInstance(myProject).setAlternativeResolveEnabled(false);
               }
             }
           }
         });
   }
 }
コード例 #25
0
    @Override
    public void run() {
      if (!connectionFinalizerActiveJobQueue.isEmpty()) {
        for (Runnable r : connectionFinalizerActiveJobQueue) {
          r.run();
        }
        connectionFinalizerActiveJobQueue.clear();
      }

      // Switch the lists.
      synchronized (connectionFinalizerLock) {
        List<Runnable> tmp = connectionFinalizerActiveJobQueue;
        connectionFinalizerActiveJobQueue = connectionFinalizerPendingJobQueue;
        connectionFinalizerPendingJobQueue = tmp;
      }
    }
コード例 #26
0
 private void queueNotificationAction(final Runnable action) {
   if (myAvailabilityNotificationsActive) {
     action.run();
   } else {
     mySuspendedListenerActions.add(action);
   }
 }
コード例 #27
0
  @Override
  public void rebuildList() {
    if (myInRebuildList) return;
    try {
      myInRebuildList = true;
      if (myChangesToDisplay == null) {
        // changes set not fixed === local changes
        final ChangeListManager manager = ChangeListManager.getInstance(myProject);
        myChangeListsMap = new HashMap<Change, LocalChangeList>();
        final List<LocalChangeList> lists = manager.getChangeListsCopy();
        Collection<Change> allChanges = new ArrayList<Change>();
        for (LocalChangeList list : lists) {
          final Collection<Change> changes = list.getChanges();
          allChanges.addAll(changes);
          for (Change change : changes) {
            myChangeListsMap.put(change, list);
          }
        }
        myAllChanges = allChanges;
        // refresh selected list also
        updateListsInChooser();
      }

      super.rebuildList();
      if (myRebuildListListener != null) {
        myRebuildListListener.run();
      }
    } finally {
      myInRebuildList = false;
    }
  }
コード例 #28
0
ファイル: RefCountHolder.java プロジェクト: novokrest/JBIDEA
  public boolean analyze(
      @NotNull PsiFile file,
      TextRange dirtyScope,
      @NotNull Runnable analyze,
      @NotNull ProgressIndicator indicator) {
    ProgressIndicator old = myState.get();
    if (old != VIRGIN && old != READY) return false;
    if (!myState.compareAndSet(old, indicator)) {
      log("a: failed to change ", old, "->", indicator);
      return false;
    }
    log("a: changed ", old, "->", indicator);
    analyzedUnder = null;
    boolean completed = false;
    try {
      if (dirtyScope != null) {
        if (dirtyScope.equals(file.getTextRange())) {
          clear();
        } else {
          removeInvalidRefs();
        }
      }

      analyze.run();
      analyzedUnder = indicator;
      completed = true;
    } finally {
      ProgressIndicator resultState = completed ? READY : VIRGIN;
      boolean set = myState.compareAndSet(indicator, resultState);
      assert set : myState.get();
      log("a: changed after analyze", indicator, "->", resultState);
    }
    return true;
  }
コード例 #29
0
 /**
  * This method runs the Runnable and measures how long it takes.
  *
  * @param r is the Runnable for the task that we want to measure
  * @return the time it took to execute this task
  */
 public static long time(Runnable r) {
   long time = -System.currentTimeMillis();
   r.run();
   time += System.currentTimeMillis();
   System.out.println("Took " + time + "ms");
   return time;
 }
コード例 #30
0
  private List<VFileEvent> getEvents(String msg, @Nullable Runnable action) {
    LOG.debug("** waiting for " + msg);
    myAccept = true;

    if (action != null) {
      action.run();
    }

    int timeout = myTimeout;
    try {
      synchronized (myWaiter) {
        //noinspection WaitNotInLoop
        myWaiter.wait(timeout);
      }
    } catch (InterruptedException e) {
      LOG.warn(e);
    }

    LOG.debug("** waited for " + timeout);
    myFileSystem.refresh(false);

    ArrayList<VFileEvent> result;
    synchronized (myEvents) {
      result = new ArrayList<VFileEvent>(myEvents);
      myEvents.clear();
    }
    LOG.debug("** events: " + result.size());
    return result;
  }