protected void preCache(List<Position> grid, Position centerPosition)
        throws InterruptedException {
      // Pre-cache the tiles that will be needed for the intersection calculations.
      double n = 0;
      final long start = System.currentTimeMillis();
      for (Position gridPos : grid) // for each grid point.
      {
        final double progress = 100 * (n++ / grid.size());
        terrain.cacheIntersectingTiles(centerPosition, gridPos);

        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                progressBar.setValue((int) progress);
                progressBar.setString(null);
              }
            });
      }

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              progressBar.setValue(100);
            }
          });

      long end = System.currentTimeMillis();
      System.out.printf(
          "Pre-caching time %d milliseconds, cache usage %f, tiles %d\n",
          end - start, terrain.getCacheUsage(), terrain.getNumCacheEntries());
    }
    protected void computeAndShowIntersections(final Position curPos) {
      this.previousCurrentPosition = curPos;

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              setCursor(WaitCursor);
            }
          });

      // Dispatch the calculation threads in a separate thread to avoid locking up the user
      // interface.
      this.calculationDispatchThread =
          new Thread(
              new Runnable() {
                public void run() {
                  try {
                    performIntersectionTests(curPos);
                  } catch (InterruptedException e) {
                    System.out.println("Operation was interrupted");
                  }
                }
              });

      this.calculationDispatchThread.start();
    }
Beispiel #3
0
 private void setScore() {
   SwingUtilities.invokeLater(
       new Runnable() {
         public void run() {
           setText(Integer.toString(score));
         }
       });
 }
Beispiel #4
0
 private void setScore() {
   // This method will be explained later in chapter 7
   SwingUtilities.invokeLater(
       new Runnable() {
         public void run() {
           setText(Integer.toString(score.get()));
         }
       });
 }
    protected void performIntersectionTests(final Position curPos) throws InterruptedException {
      // Clear the results lists when the user selects a new location.
      this.firstIntersectionPositions.clear();
      this.sightLines.clear();

      // Raise the selected location and the grid points a little above ground just to show we can.
      final double height = 5; // meters

      // Form the grid.
      double gridRadius = GRID_RADIUS.degrees;
      Sector sector =
          Sector.fromDegrees(
              curPos.getLatitude().degrees - gridRadius, curPos.getLatitude().degrees + gridRadius,
              curPos.getLongitude().degrees - gridRadius,
                  curPos.getLongitude().degrees + gridRadius);

      this.grid = buildGrid(sector, height, GRID_DIMENSION, GRID_DIMENSION);
      this.numGridPoints = grid.size();

      // Compute the position of the selected location (incorporate its height).
      this.referencePosition = new Position(curPos.getLatitude(), curPos.getLongitude(), height);
      this.referencePoint =
          terrain.getSurfacePoint(curPos.getLatitude(), curPos.getLongitude(), height);

      //            // Pre-caching is unnecessary and is useful only when it occurs before the
      // intersection
      //            // calculations. It will incur extra overhead otherwise. The normal intersection
      // calculations
      //            // cause the same caching, making subsequent calculations on the same area
      // faster.
      //            this.preCache(grid, this.referencePosition);

      // On the EDT, show the grid.
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              progressBar.setValue(0);
              progressBar.setString(null);
              clearLayers();
              showGrid(grid, referencePosition);
              getWwd().redraw();
            }
          });

      // Perform the intersection calculations.
      this.startTime = System.currentTimeMillis();
      for (Position gridPos : this.grid) // for each grid point.
      {
        //noinspection ConstantConditions
        if (NUM_THREADS > 0) this.threadPool.execute(new Intersector(gridPos));
        else performIntersection(gridPos);
      }
    }
    @Override
    public void run() {
      try {
        if (myDisposed) {
          return;
        }
        synchronized (LOCK) {
          if (myTask == null) return;
        }

        final Runnable scheduledTask =
            new Runnable() {
              @Override
              public void run() {
                final Runnable task;
                synchronized (LOCK) {
                  task = myTask;
                  if (task == null) return;
                  myTask = null;

                  myRequests.remove(Request.this);
                }

                if (myThreadToUse == ThreadToUse.SWING_THREAD && !isEdt()) {
                  try {
                    SwingUtilities.invokeAndWait(task);
                  } catch (Exception e) {
                    LOG.error(e);
                  }
                } else {
                  try {
                    task.run();
                  } catch (Exception e) {
                    LOG.error(e);
                  }
                }
              }
            };

        if (myModalityState == null) {
          myFuture = myExecutorService.submit(scheduledTask);
        } else {
          final Application app = ApplicationManager.getApplication();
          if (app != null) {
            app.invokeLater(scheduledTask, myModalityState);
          } else {
            SwingUtilities.invokeLater(scheduledTask);
          }
        }
      } catch (Throwable e) {
        LOG.error(e);
      }
    }
Beispiel #7
0
  /** simply dump status info to the textarea */
  private void sout(final String s) {
    Runnable soutRunner =
        new Runnable() {
          public void run() {
            if (ttaStatus.getText().equals("")) {
              ttaStatus.setText(s);
            } else {
              ttaStatus.setText(ttaStatus.getText() + "\n" + s);
            }
          }
        };

    if (ThreadUtils.isInEDT()) {
      soutRunner.run();
    } else {
      SwingUtilities.invokeLater(soutRunner);
    }
  }
    /** Keeps the progress meter current. When calculations are complete, displays the results. */
    protected synchronized void updateProgress() {
      // Update the progress bar only once every 250 milliseconds to avoid stealing time from
      // calculations.
      if (this.sightLines.size() >= this.numGridPoints) endTime = System.currentTimeMillis();
      else if (System.currentTimeMillis() < this.lastTime + 250) return;
      this.lastTime = System.currentTimeMillis();

      // On the EDT, update the progress bar and if calculations are complete, update the World
      // Window.
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              int progress = (int) (100d * getSightlinesSize() / (double) numGridPoints);
              progressBar.setValue(progress);

              if (progress >= 100) {
                setCursor(Cursor.getDefaultCursor());
                progressBar.setString((endTime - startTime) + " ms");
                showResults();
                System.out.printf("Calculation time %d milliseconds\n", endTime - startTime);
              }
            }
          });
    }
  public boolean runProcessWithProgressSynchronously(
      @NotNull final Runnable process,
      @NotNull final String progressTitle,
      final boolean canBeCanceled,
      @Nullable final Project project,
      final JComponent parentComponent,
      final String cancelText) {
    assertIsDispatchThread();

    if (myExceptionalThreadWithReadAccessRunnable != null
        || ApplicationManager.getApplication().isUnitTestMode()
        || ApplicationManager.getApplication().isHeadlessEnvironment()) {
      try {
        ProgressManager.getInstance().runProcess(process, new EmptyProgressIndicator());
      } catch (ProcessCanceledException e) {
        // ok to ignore.
        return false;
      }
      return true;
    }

    final ProgressWindow progress =
        new ProgressWindow(canBeCanceled, false, project, parentComponent, cancelText);
    progress.setTitle(progressTitle);

    try {
      myExceptionalThreadWithReadAccessRunnable = process;
      final boolean[] threadStarted = {false};
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              if (myExceptionalThreadWithReadAccessRunnable != process) {
                LOG.error(
                    "myExceptionalThreadWithReadAccessRunnable != process, process = "
                        + myExceptionalThreadWithReadAccessRunnable);
              }

              executeOnPooledThread(
                  new Runnable() {
                    public void run() {
                      if (myExceptionalThreadWithReadAccessRunnable != process) {
                        LOG.error(
                            "myExceptionalThreadWithReadAccessRunnable != process, process = "
                                + myExceptionalThreadWithReadAccessRunnable);
                      }

                      final boolean old = setExceptionalThreadWithReadAccessFlag(true);
                      LOG.assertTrue(isReadAccessAllowed());
                      try {
                        ProgressManager.getInstance().runProcess(process, progress);
                      } catch (ProcessCanceledException e) {
                        progress.cancel();
                        // ok to ignore.
                      } catch (RuntimeException e) {
                        progress.cancel();
                        throw e;
                      } finally {
                        setExceptionalThreadWithReadAccessFlag(old);
                        makeChangesVisibleToEDT();
                      }
                    }
                  });
              threadStarted[0] = true;
            }
          });

      progress.startBlocking();

      LOG.assertTrue(threadStarted[0]);
      LOG.assertTrue(!progress.isRunning());
    } finally {
      myExceptionalThreadWithReadAccessRunnable = null;
      makeChangesVisibleToEDT();
    }

    return !progress.isCanceled();
  }