private void scrollToSelectedElement() {
    if (myAutoscrollFeedback) {
      myAutoscrollFeedback = false;
      return;
    }

    StructureViewFactoryImpl structureViewFactory =
        (StructureViewFactoryImpl) StructureViewFactoryEx.getInstance(myProject);

    if (!structureViewFactory.getState().AUTOSCROLL_FROM_SOURCE) {
      return;
    }

    myAutoscrollAlarm.cancelAllRequests();
    myAutoscrollAlarm.addRequest(
        new Runnable() {
          public void run() {
            if (myAbstractTreeBuilder == null) {
              return;
            }
            try {
              selectViewableElement();
            } catch (IndexNotReadyException ignore) {
            }
          }
        },
        1000);
  }
  private void hideCurrentNow(boolean animationEnabled) {
    if (myCurrentTipUi != null) {
      myCurrentTipUi.setAnimationEnabled(animationEnabled);
      myCurrentTipUi.hide();
      myCurrentTooltip.onHidden();
      myShowDelay = false;
      myAlarm.addRequest(
          new Runnable() {
            @Override
            public void run() {
              myShowDelay = true;
            }
          },
          Registry.intValue("ide.tooltip.reshowDelay"));
    }

    myShowRequest = null;
    myCurrentTooltip = null;
    myCurrentTipUi = null;
    myCurrentComponent = null;
    myQueuedComponent = null;
    myQueuedTooltip = null;
    myCurrentEvent = null;
    myCurrentTipIsCentered = false;
    myX = -1;
    myY = -1;
  }
 public void propertyChange(final PropertyChangeEvent e) {
   if (myAlarm.getActiveRequestCount() == 0) {
     myInitialFocusedWindow = (Window) e.getOldValue();
     final MenuElement[] selectedPath = MenuSelectionManager.defaultManager().getSelectedPath();
     if (selectedPath.length == 0) { // there is no visible popup
       return;
     }
     Component firstComponent = null;
     for (final MenuElement menuElement : selectedPath) {
       final Component component = menuElement.getComponent();
       if (component instanceof JMenuBar) {
         firstComponent = component;
         break;
       } else if (component instanceof JPopupMenu) {
         firstComponent = ((JPopupMenu) component).getInvoker();
         break;
       }
     }
     if (firstComponent == null) {
       return;
     }
     final Window window = SwingUtilities.getWindowAncestor(firstComponent);
     if (window != myInitialFocusedWindow) { // focused window doesn't have popup
       return;
     }
   }
   myLastFocusedWindow = (Window) e.getNewValue();
   myAlarm.cancelAllRequests();
   myAlarm.addRequest(myClearSelectedPathRunnable, 150);
 }
  public void waitFor(Runnable r) {
    Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD, getTestRootDisposable());
    final Thread thread = Thread.currentThread();

    final boolean[] isRunning = {true};
    alarm.addRequest(
        new Runnable() {
          @Override
          public void run() {
            boolean b;
            synchronized (isRunning) {
              b = isRunning[0];
            }
            if (b) {
              thread.interrupt();
              LOG.error("test was running over " + myTimeout / 1000 + " seconds. Interrupted. ");
            }
          }
        },
        myTimeout);
    r.run();
    synchronized (isRunning) {
      isRunning[0] = false;
    }
    Thread.interrupted();
  }
 private void addUpdatingRequest() {
   if (myRefreshingAlarm.isDisposed()) {
     return;
   }
   myRefreshingAlarm.cancelAllRequests();
   myRefreshingAlarm.addRequest(myUpdateRequest, REFRESH_INTERVAL_MS);
 }
 @Override
 public void initialize() {
   try {
     base.initialize();
   } catch (Exception ignore) {
   }
   myDisposable = Disposer.newDisposable();
   Application application = ApplicationManager.getApplication();
   if (application != null) {
     Disposer.register(application, myDisposable);
   }
   myMnemonicAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD, myDisposable);
   IdeEventQueue.getInstance()
       .addDispatcher(
           e -> {
             if (e instanceof KeyEvent && ((KeyEvent) e).getKeyCode() == KeyEvent.VK_ALT) {
               myAltPressed = e.getID() == KeyEvent.KEY_PRESSED;
               myMnemonicAlarm.cancelAllRequests();
               final Component focusOwner = IdeFocusManager.findInstance().getFocusOwner();
               if (focusOwner != null) {
                 myMnemonicAlarm.addRequest(() -> repaintMnemonics(focusOwner, myAltPressed), 10);
               }
             }
             return false;
           },
           myDisposable);
 }
  public void waitProcess(@NotNull final ProcessHandler processHandler) {
    Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD, getTestRootDisposable());

    final boolean[] isRunning = {true};
    alarm.addRequest(
        new Runnable() {
          @Override
          public void run() {
            boolean b;
            synchronized (isRunning) {
              b = isRunning[0];
            }
            if (b) {
              processHandler.destroyProcess();
              LOG.error("process was running over " + myTimeout / 1000 + " seconds. Interrupted. ");
            }
          }
        },
        myTimeout);
    processHandler.waitFor();
    synchronized (isRunning) {
      isRunning[0] = false;
    }
    Disposer.dispose(alarm);
  }
 private synchronized void addCommand(LogCommand command) {
   if (!myAlarm.isDisposed()) {
     myLog.add(command);
     myAlarm.cancelAllRequests();
     myAlarm.addRequest(myFlushLogRunnable, 100L);
   }
 }
  /**
   * waits COMMAND_TIMEOUT milliseconds if worker thread is still processing the same command calls
   * terminateCommand
   */
  public void terminateAndInvoke(DebuggerCommandImpl command, int terminateTimeout) {
    final DebuggerCommandImpl currentCommand = myEvents.getCurrentEvent();

    invoke(command);

    if (currentCommand != null) {
      final Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
      alarm.addRequest(
          new Runnable() {
            public void run() {
              if (currentCommand == myEvents.getCurrentEvent()) {
                // if current command is still in progress, cancel it
                getCurrentRequest().interrupt();
                try {
                  getCurrentRequest().join();
                } catch (InterruptedException ignored) {
                } catch (Exception e) {
                  throw new RuntimeException(e);
                } finally {
                  startNewWorkerThread();
                }
              }
            }
          },
          terminateTimeout);
    }
  }
Exemple #10
0
  private void _addTestOrSuite(@NotNull final SMTestProxy newTestOrSuite) {

    final SMTestProxy parentSuite = newTestOrSuite.getParent();
    assert parentSuite != null;

    // Tree
    final Update update =
        new Update(parentSuite) {
          @Override
          public void run() {
            myRequests.remove(this);
            myTreeBuilder.updateTestsSubtree(parentSuite);
          }
        };
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      update.run();
    } else if (myRequests.add(update) && !myUpdateQueue.isDisposed()) {
      myUpdateQueue.addRequest(update, 100);
    }
    myTreeBuilder.repaintWithParents(newTestOrSuite);

    myAnimator.setCurrentTestCase(newTestOrSuite);

    if (TestConsoleProperties.TRACK_RUNNING_TEST.value(myProperties)) {
      if (myLastSelected == null || myLastSelected == newTestOrSuite) {
        myLastSelected = null;
        selectAndNotify(newTestOrSuite);
      }
    }
  }
 private void awaitTermination(@NotNull Runnable request, long delayMillis) {
   if (ApplicationManager.getApplication().isUnitTestMode()) {
     ApplicationManager.getApplication().invokeLater(request, ModalityState.any());
   } else {
     myAwaitingTerminationAlarm.addRequest(request, delayMillis);
   }
 }
Exemple #12
0
  public synchronized void start() {
    if (isRunning()) return;

    super.start();
    myOriginalStarted = false;
    myStartupAlarm.addRequest(myShowRequest, SHOW_DELAY);
  }
 private void scheduleUpdate(int delay) {
   myAlarm.cancelAllRequests();
   UpdateRequest updateRequest = new UpdateRequest();
   if (isTestingMode) {
     ApplicationManager.getApplication().invokeLater(updateRequest);
   } else {
     myAlarm.addRequest(updateRequest, delay);
   }
 }
  synchronized void stopProcess(boolean toRestartAlarm) {
    if (!allowToInterrupt) throw new RuntimeException("Cannot interrupt daemon");

    cancelUpdateProgress(toRestartAlarm, "by Stop process");
    myAlarm.cancelAllRequests();
    boolean restart = toRestartAlarm && !myDisposed && myInitialized;
    if (restart) {
      myAlarm.addRequest(myUpdateRunnable, mySettings.AUTOREPARSE_DELAY);
    }
  }
    public void editorCreated(@NotNull EditorFactoryEvent event) {
      synchronized (myLock) {
        if (myIsProjectClosing) return;
      }

      final Editor editor = event.getEditor();
      if (editor.getProject() != myProject) return;
      final PsiFile psiFile =
          ApplicationManager.getApplication()
              .runReadAction(
                  new Computable<PsiFile>() {
                    @Nullable
                    @Override
                    public PsiFile compute() {
                      if (myProject.isDisposed()) return null;
                      final PsiDocumentManager documentManager =
                          PsiDocumentManager.getInstance(myProject);
                      final Document document = editor.getDocument();
                      return documentManager.getPsiFile(document);
                    }
                  });

      if (psiFile != null && myCurrentSuitesBundle != null && psiFile.isPhysical()) {
        final CoverageEngine engine = myCurrentSuitesBundle.getCoverageEngine();
        if (!engine.coverageEditorHighlightingApplicableTo(psiFile)) {
          return;
        }

        SrcFileAnnotator annotator = getAnnotator(editor);
        if (annotator == null) {
          annotator = new SrcFileAnnotator(psiFile, editor);
        }

        final SrcFileAnnotator finalAnnotator = annotator;

        synchronized (ANNOTATORS_LOCK) {
          myAnnotators.put(editor, finalAnnotator);
        }

        final Runnable request =
            new Runnable() {
              @Override
              public void run() {
                if (myProject.isDisposed()) return;
                if (myCurrentSuitesBundle != null) {
                  if (engine.acceptedByFilters(psiFile, myCurrentSuitesBundle)) {
                    finalAnnotator.showCoverageInformation(myCurrentSuitesBundle);
                  }
                }
              }
            };
        myCurrentEditors.put(editor, request);
        myAlarm.addRequest(request, 100);
      }
    }
 private void scheduleUpdate() {
   myAlarm.cancelAllRequests();
   myAlarm.addRequest(
       new Runnable() {
         @Override
         public void run() {
           fireStateChanged();
         }
       },
       ArrangementConstants.TEXT_UPDATE_DELAY_MILLIS);
 }
 private void queueChangesCheck() {
   if (myAlarm.isDisposed()) {
     return;
   }
   myAlarm.addRequest(
       () -> {
         checkChanges();
         queueChangesCheck();
       },
       CHANGES_CHECK_TIME,
       ModalityState.any());
 }
 private void addAlarmRequest() {
   Runnable request =
       () -> {
         if (!myDisposed && !myProject.isDisposed()) {
           PsiDocumentManager.getInstance(myProject)
               .performLaterWhenAllCommitted(
                   () ->
                       DumbService.getInstance(myProject)
                           .withAlternativeResolveEnabled(this::updateComponent));
         }
       };
   myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent()));
 }
  private void updateLater() {
    myUpdateAlarm.cancelAllRequests();
    myUpdateAlarm.addRequest(
        new Runnable() {
          @Override
          public void run() {
            if (myProject.isDisposed()) return;
            PsiDocumentManager.getInstance(myProject).commitAllDocuments();

            updateImmediately();
          }
        },
        300);
  }
 private void updateFileIconLater(VirtualFile file) {
   myFilesToUpdateIconsFor.add(file);
   myIconUpdaterAlarm.cancelAllRequests();
   myIconUpdaterAlarm.addRequest(
       () -> {
         if (myManager.getProject().isDisposed()) return;
         for (VirtualFile file1 : myFilesToUpdateIconsFor) {
           updateFileIconImmediately(file1);
         }
         myFilesToUpdateIconsFor.clear();
       },
       200,
       ModalityState.stateForComponent(this));
 }
  public boolean hideCurrent(
      @Nullable MouseEvent me,
      @Nullable AnAction action,
      @Nullable AnActionEvent event,
      final boolean animationEnabled) {
    myShowRequest = null;
    myQueuedComponent = null;
    myQueuedTooltip = null;

    if (myCurrentTooltip == null) return true;

    if (myCurrentTipUi != null) {
      boolean isInside = me != null && myCurrentTipUi.isInsideBalloon(me);
      boolean canAutoHide =
          myCurrentTooltip.canAutohideOn(new TooltipEvent(me, isInside, action, event));
      boolean implicitMouseMove =
          me != null
              && (me.getID() == MouseEvent.MOUSE_MOVED
                  || me.getID() == MouseEvent.MOUSE_EXITED
                  || me.getID() == MouseEvent.MOUSE_ENTERED);

      if (!canAutoHide || myCurrentTooltip.isExplicitClose() && implicitMouseMove) {
        if (myHideRunnable != null) {
          myHideRunnable = null;
        }
        return false;
      }
    }

    myHideRunnable =
        new Runnable() {
          @Override
          public void run() {
            if (myHideRunnable != null) {
              hideCurrentNow(animationEnabled);
              myHideRunnable = null;
            }
          }
        };

    if (me != null) {
      myAlarm.addRequest(myHideRunnable, Registry.intValue("ide.tooltip.autoDismissDeadZone"));
    } else {
      myHideRunnable.run();
      myHideRunnable = null;
    }

    return true;
  }
 private void runWithDelay(
     final @NotNull RemotelyConfigurableStatisticsService statisticsService) {
   myAlarm.addRequest(
       new Runnable() {
         @Override
         public void run() {
           if (DumbService.isDumb(myProject)) {
             runWithDelay(statisticsService);
           } else {
             statisticsService.send();
           }
         }
       },
       DELAY_IN_MIN * 60 * 1000);
 }
  public static void trackStatistics(InsertionContext context, final StatisticsUpdate update) {
    if (ourPendingUpdate != update) {
      return;
    }

    final Document document = context.getDocument();
    int startOffset = context.getStartOffset();
    int tailOffset = context.getEditor().getCaretModel().getOffset();
    if (startOffset < 0 || tailOffset <= startOffset) {
      return;
    }

    final RangeMarker marker = document.createRangeMarker(startOffset, tailOffset);
    final DocumentAdapter listener =
        new DocumentAdapter() {
          @Override
          public void beforeDocumentChange(DocumentEvent e) {
            if (!marker.isValid()
                || e.getOffset() > marker.getStartOffset()
                    && e.getOffset() < marker.getEndOffset()) {
              cancelLastCompletionStatisticsUpdate();
            }
          }
        };

    ourStatsAlarm.addRequest(
        new Runnable() {
          @Override
          public void run() {
            if (ourPendingUpdate == update) {
              applyLastCompletionStatisticsUpdate();
            }
          }
        },
        20 * 1000);

    document.addDocumentListener(listener);
    Disposer.register(
        update,
        new Disposable() {
          @Override
          public void dispose() {
            document.removeDocumentListener(listener);
            marker.dispose();
            ourStatsAlarm.cancelAllRequests();
          }
        });
  }
  public boolean startIfNotStarted(final int refreshInterval) {
    final boolean refreshIntervalChanged =
        (refreshInterval > 0) && refreshInterval != myRefreshInterval;
    if (refreshIntervalChanged) {
      mySimpleAlarm.cancelAllRequests();
    }
    if (refreshInterval > 0) {
      myRefreshInterval = refreshInterval;
    }

    final boolean wasSet = myActive.compareAndSet(false, true);
    if (wasSet || refreshIntervalChanged) {
      mySimpleAlarm.addRequest(myRunnable, myRefreshInterval);
    }
    return wasSet;
  }
  private void rebuild(
      final boolean updateText,
      @Nullable final Runnable runnable,
      final boolean requestFocus,
      final int delayMillis) {
    myUpdateAlarm.cancelAllRequests();
    final Runnable request =
        new Runnable() {
          public void run() {
            ApplicationManager.getApplication()
                .executeOnPooledThread(
                    new Runnable() {
                      public void run() {
                        if (updateText) {
                          final String text =
                              myCurrentScope != null ? myCurrentScope.getText() : null;
                          SwingUtilities.invokeLater(
                              new Runnable() {
                                public void run() {
                                  try {
                                    myIsInUpdate = true;
                                    myPatternField.setText(text);
                                  } finally {
                                    myIsInUpdate = false;
                                  }
                                }
                              });
                        }

                        try {
                          if (!myProject.isDisposed()) {
                            updateTreeModel(requestFocus);
                          }
                        } catch (ProcessCanceledException e) {
                          return;
                        }
                        if (runnable != null) {
                          runnable.run();
                        }
                      }
                    });
          }
        };
    myUpdateAlarm.addRequest(request, delayMillis);
  }
  private void setStructureViewSelection(@NotNull final String propertyName) {
    if (myStructureViewComponent.isDisposed()) {
      return;
    }
    JTree tree = myStructureViewComponent.getTree();
    if (tree == null) {
      return;
    }

    Object root = tree.getModel().getRoot();
    if (AbstractTreeUi.isLoadingChildrenFor(root)) {
      mySelectionChangeAlarm.cancelAllRequests();
      mySelectionChangeAlarm.addRequest(
          new Runnable() {
            @Override
            public void run() {
              mySelectionChangeAlarm.cancelAllRequests();
              setStructureViewSelection(propertyName);
            }
          },
          500);
      return;
    }

    Stack<TreeElement> toCheck = ContainerUtilRt.newStack();
    toCheck.push(myStructureViewComponent.getTreeModel().getRoot());

    while (!toCheck.isEmpty()) {
      TreeElement element = toCheck.pop();
      PsiElement value =
          element instanceof ResourceBundlePropertyStructureViewElement
              ? ((ResourceBundlePropertyStructureViewElement) element).getValue()
              : null;
      if (value instanceof IProperty
          && propertyName.equals(((IProperty) value).getUnescapedKey())) {
        myStructureViewComponent.select(value, true);
        selectionChanged();
        return;
      } else {
        for (TreeElement treeElement : element.getChildren()) {
          toCheck.push(treeElement);
        }
      }
    }
  }
 public void stateChanged() {
   livePreviewAlarm.cancelAllRequests();
   final Editor editor1 = getEditor();
   if (editor1 == null) return;
   cleanUp();
   injectActivityWatcher();
   pattern = patternController.buildPattern();
   livePreviewAlarm.addRequest(
       new Runnable() {
         @Override
         public void run() {
           if (patternController != null) {
             update(editor1);
           }
         }
       },
       USER_ACTIVITY_PAUSE);
 }
 @Override
 public void run() {
   LOG.debug("-- (event, expected=" + myAccept + ")");
   if (!myAccept) return;
   myAlarm.cancelAllRequests();
   myAlarm.addRequest(
       new Runnable() {
         @Override
         public void run() {
           myAccept = false;
           LOG.debug("** waiting finished");
           synchronized (myWaiter) {
             myWaiter.notifyAll();
           }
         }
       },
       INTER_RESPONSE_DELAY);
 }
  private void runQuery() {
    if (getRootPane() == null) return;

    Set<InlineProgressIndicator> indicators = getCurrentInlineIndicators();
    if (indicators.isEmpty()) return;

    for (InlineProgressIndicator each : indicators) {
      each.updateProgress();
    }
    myQueryAlarm.cancelAllRequests();
    myQueryAlarm.addRequest(
        new Runnable() {
          @Override
          public void run() {
            runQuery();
          }
        },
        2000);
  }
  @TestOnly
  public static void waitForAlarm(final int delay) throws InterruptedException {
    assert !ApplicationManager.getApplication().isWriteAccessAllowed()
        : "It's a bad idea to wait for an alarm under the write action. Somebody creates an alarm which requires read action and you are deadlocked.";
    assert ApplicationManager.getApplication().isDispatchThread();

    final AtomicBoolean invoked = new AtomicBoolean();
    final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
    alarm.addRequest(
        new Runnable() {
          @Override
          public void run() {
            ApplicationManager.getApplication()
                .invokeLater(
                    new Runnable() {
                      @Override
                      public void run() {
                        alarm.addRequest(
                            new Runnable() {
                              @Override
                              public void run() {
                                invoked.set(true);
                              }
                            },
                            delay);
                      }
                    });
          }
        },
        delay);

    UIUtil.dispatchAllInvocationEvents();

    boolean sleptAlready = false;
    while (!invoked.get()) {
      UIUtil.dispatchAllInvocationEvents();
      //noinspection BusyWait
      Thread.sleep(sleptAlready ? 10 : delay);
      sleptAlready = true;
    }
    UIUtil.dispatchAllInvocationEvents();
  }