// Coordinates are that of the shell
 void setContentBounds(WindowDimensions dims) {
   XToolkit.awtLock();
   try {
     // Bounds of content window are of the same size as bounds of Java window and with
     // location as -(insets)
     Rectangle newBounds = dims.getBounds();
     Insets in = dims.getInsets();
     if (in != null) {
       newBounds.setLocation(-in.left, -in.top);
     }
     if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
       insLog.fine("Setting content bounds {0}, old bounds {1}", newBounds, getBounds());
     }
     // Fix for 5023533:
     // Change in the size of the content window means, well, change of the size
     // Change in the location of the content window means change in insets
     boolean needHandleResize = !(newBounds.equals(getBounds()));
     reshape(newBounds);
     if (needHandleResize) {
       insLog.fine("Sending RESIZED");
       handleResize(newBounds);
     }
   } finally {
     XToolkit.awtUnlock();
   }
   validateSurface();
 }
 private boolean checkLayering(Area b) {
   ArrayList<Number> id = getVisible();
   Vector<Rectangle> rects = new Vector<Rectangle>(id.size());
   for (Number n : id) {
     rects.add(getIE().get(n).toRectangle());
   }
   Rectangle r = b.toRectangle();
   int index = 0;
   for (Rectangle rect : rects) {
     if (r.equals(rect)) {
       index = rects.indexOf(rect) + 1;
     }
   }
   for (int i = index; i < rects.size(); i++) {
     Rectangle rect = rects.get(i);
     if (r.intersects(rect)) {
       Rectangle isect = r.intersection(rect);
       isect.setRect(isect.x, isect.y, isect.getWidth() + 1, isect.getHeight() + 2);
       if (isect.contains(mascot.getAnchor())) {
         return false;
       }
     }
   }
   return true;
 }
示例#3
0
  /**
   * Creates an image containing pixels read from the screen.
   *
   * @param bounds the rect to capture in screen coordinates
   * @return the array of pixels
   */
  @Override
  public int[] getRGBPixels(final Rectangle bounds) {
    Rectangle screenBounds = fDevice.getDefaultConfiguration().getBounds();
    // screenBounds is in the coordinates of the primary device
    // but bounds is in the coordinates of fDevice
    // so we fix screenbounds at 0,0 origin
    screenBounds.x = screenBounds.y = 0;
    Rectangle intersection = screenBounds.intersection(bounds);

    int c[] = new int[intersection.width * intersection.height];
    getScreenPixels(intersection, c);

    if (!intersection.equals(bounds)) {
      // Since we are returning a smaller array than the code expects,
      // we have to copy our existing array into an array of the
      // "correct" size
      int c2[] = new int[bounds.width * bounds.height];
      for (int h = 0; h < bounds.height; h++) {
        int boundsRow = h + bounds.y;
        if (boundsRow >= intersection.y && boundsRow < intersection.height) {
          int srcPos = (boundsRow - intersection.y) * intersection.width;
          int destPos = (h * bounds.width) + (intersection.x - bounds.x);
          System.arraycopy(c, srcPos, c2, destPos, intersection.width);
        }
      }
      c = c2;
    }

    return c;
  }
  /**
   * Makes sure the current editor height matches its content if the annotation was never resized.
   * If the annotation has been manually resized before, does nothing.
   *
   * @param anno the annotation currently in the editor
   */
  private void updateEditorHeight(final WorkflowAnnotation anno) {
    if (anno.wasResized()) {
      return;
    }

    Rectangle bounds = editPane.getBounds();
    // height is either the pref height or the current height, depending on what is bigger
    int prefHeight;
    if (anno instanceof ProcessAnnotation) {
      prefHeight =
          (int) Math.max(getContentHeightOfEditor((int) bounds.getWidth()), bounds.getHeight());
    } else {
      prefHeight =
          Math.max(
              getContentHeightOfEditor((int) bounds.getWidth()), OperatorAnnotation.MIN_HEIGHT);
    }
    Rectangle newBounds =
        new Rectangle(
            (int) bounds.getX(), (int) bounds.getY(), (int) bounds.getWidth(), prefHeight);
    if (!bounds.equals(newBounds)) {
      editPane.setBounds(newBounds);
      updateEditPanelPosition(newBounds, true);
      view.getModel().fireAnnotationMiscChanged(anno);
    }
  }
示例#5
0
 @Override
 public boolean equals(Object obj) {
   if (!(obj instanceof BoxProvider)) return false;
   final BoxProvider other = (BoxProvider) obj;
   BoxProviderResult resultOther = other.get();
   if (resultOther.isTemporary()) return false;
   return box.equals(resultOther.getBox());
 }
示例#6
0
 @Override
 public void setBounds(Point origin, Point corner) {
   Rectangle original = new Rectangle(getShape());
   getShape().setFrameFromDiagonal(origin, corner);
   if (!original.equals(getShape())) {
     updateFigure();
   }
 }
示例#7
0
  public static void main(String[] args) throws NumberFormatException {
    Scanner sc = new Scanner(System.in);
    // int x=sc.nextInt();
    // x+=55;
    // System.out.println(x);
    // String x="vipul";
    // String y=new String(x);
    // byte z =x.getByte(x);
    // System.out.println(z);
    Rectangle rect1 = new Rectangle(10, 20);
    Rectangle rect2 = new Rectangle(10, 20);
    boolean x = rect1.equals(rect2);
    if (rect1.equals(rect2)) {
      System.out.println("fskjfsfj");

    } else System.out.println("ddsff");
  }
  @Override
  public void setBounds(Point origin, Point corner) {
    java.awt.Rectangle original = new java.awt.Rectangle(rectangle);
    rectangle.setFrameFromDiagonal(origin, corner);

    if (!original.equals(rectangle)) {
      propagateFigureEvent(new FigureEvent(this));
    }
  }
  private boolean sizeChanged() {
    if ((oldComponentInnards == null) || (componentInnards == null)) {
      return true;
    }

    oldComponentInnards.setRect(componentInnards);
    componentInnards = SwingUtilities.calculateInnerArea(progressBar, componentInnards);
    return !oldComponentInnards.equals(componentInnards);
  }
示例#10
0
  /**
   * Handle a refresh of the style panel after the fig has moved.
   *
   * <p><em>Warning</em>. There is a circular trap here. Editing the boundary box will also trigger
   * a refresh, and so we reset the boundary box, which causes funny behaviour (the cursor keeps
   * jumping to the end of the text).
   *
   * <p>The solution is to not reset the boundary box field if the boundaries have not changed.
   *
   * <p>
   */
  public void refresh() {
    Fig target = getPanelTarget();
    if (target instanceof FigEdgeModelElement) {
      hasEditableBoundingBox(false);
    } else {
      hasEditableBoundingBox(true);
    }
    if (target == null) return;

    // The boundary box as held in the target fig, and as listed in
    // the
    // boundary box style field (null if we don't have anything
    // valid)

    Rectangle figBounds = target.getBounds();
    Rectangle styleBounds = parseBBox();

    // Only reset the text if the two are not the same (i.e the fig
    // has
    // moved, rather than we've just edited the text, when
    // setTargetBBox()
    // will have made them the same). Note that styleBounds could
    // be null,
    // so we do the test this way round.

    if (!(figBounds.equals(styleBounds))) {
      bboxField.setText(
          figBounds.x + "," + figBounds.y + "," + figBounds.width + "," + figBounds.height);
    }

    // Change the fill colour

    if (target.getFilled()) {
      Color c = target.getFillColor();
      fillField.setSelectedItem(c);
      if (c != null && !fillField.getSelectedItem().equals(c)) {
        fillField.insertItemAt(c, fillField.getItemCount() - 1);
        fillField.setSelectedItem(c);
      }
    } else {
      fillField.setSelectedIndex(0);
    }

    // Change the line colour

    if (target.getLineWidth() > 0) {
      Color c = target.getLineColor();
      lineField.setSelectedItem(c);
      if (c != null && !lineField.getSelectedItem().equals(c)) {
        lineField.insertItemAt(c, lineField.getItemCount() - 1);
        lineField.setSelectedItem(c);
      }
    } else {
      lineField.setSelectedIndex(0);
    }
  }
  public void updateLocation(JComponent container) {
    final Rectangle rec = container.getVisibleRect();

    final Dimension iconSize = getPreferredSize();

    final Rectangle newBounds =
        new Rectangle(rec.x + rec.width - iconSize.width, rec.y, iconSize.width, iconSize.height);
    if (!newBounds.equals(getBounds())) {
      setBounds(newBounds);
      container.repaint();
    }
  }
 public static boolean safeRestoreWindow(final Window frame, final Rectangle bounds) {
   final GraphicsEnvironment graphicsEnvironment =
       GraphicsEnvironment.getLocalGraphicsEnvironment();
   final GraphicsDevice[] devices = graphicsEnvironment.getScreenDevices();
   for (int i = 0; i < devices.length; i++) {
     final GraphicsDevice device = devices[i];
     final Rectangle rectangle = device.getDefaultConfiguration().getBounds();
     if (rectangle.contains(bounds) || rectangle.equals(bounds)) {
       DebugLog.log("Found a usable screen-configuration: Restoring frame to " + bounds);
       frame.setBounds(bounds);
       return true;
     }
   }
   return false;
 }
示例#13
0
 @Override
 public boolean equals(Object obj) {
   if (!super.equals(obj)) return false;
   if (obj == null || getClass() != obj.getClass()) return false;
   final BoxTextElemStyle other = (BoxTextElemStyle) obj;
   if (!text.equals(other.text)) return false;
   if (boxProvider != null) {
     if (!boxProvider.equals(other.boxProvider)) return false;
   } else if (other.boxProvider != null) return false;
   else {
     if (!box.equals(other.box)) return false;
   }
   if (hAlign != other.hAlign) return false;
   if (vAlign != other.vAlign) return false;
   return true;
 }
        @Override
        public void componentResized(ComponentEvent e) {
          initViewBounds = getVisibleRect();
          Rectangle newView =
              new Rectangle(
                  viewBounds.x, viewBounds.y, initViewBounds.width, initViewBounds.height);

          if (!newView.equals(viewBounds)) {
            setViewBounds(newView);
            if (debugBounds) {
              logger.debug("Viewport resized!"); // $NON-NLS-1$
              logger.debug("viewBounds = " + viewBounds); // $NON-NLS-1$
              logger.debug("getVisibleRect() = " + getVisibleRect()); // $NON-NLS-1$
              logger.debug("getBounds() = " + getBounds()); // $NON-NLS-1$
            }
          }
        }
  public void paint(Graphics g) {
    // repaint the whole transformer in case the view component was repainted
    Rectangle clipBounds = g.getClipBounds();
    if (clipBounds != null && !clipBounds.equals(visibleRect)) {
      repaint();
    }
    // clear the background
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());

    if (view != null && at.getDeterminant() != 0) {
      Graphics2D g2 = (Graphics2D) g.create();
      Insets insets = getInsets();
      Rectangle bounds = getBounds();

      // don't forget about insets
      bounds.x += insets.left;
      bounds.y += insets.top;
      bounds.width -= insets.left + insets.right;
      bounds.height -= insets.top + insets.bottom;
      double centerX1 = bounds.getCenterX();
      double centerY1 = bounds.getCenterY();

      Rectangle tb = getTransformedSize();
      double centerX2 = tb.getCenterX();
      double centerY2 = tb.getCenterY();

      // set antialiasing by default
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      if (renderingHints != null) {
        g2.addRenderingHints(renderingHints);
      }
      // translate it to the center of the view component again
      double tx = centerX1 - centerX2 - getX();
      double ty = centerY1 - centerY2 - getY();
      g2.translate((int) tx, (int) ty);
      g2.transform(at);
      view.paint(g2);
      g2.dispose();
    }
    // paint the border
    paintBorder(g);
  }
  /**
   * Returns a contiguous <code>Raster</code> of data over the specified <code>Rectangle</code>. If
   * the region is a sub-region of a single tile, then a child of that tile will be returned. If the
   * region overlaps more than one tile and has 8 bits per sample, then a pixel interleaved Raster
   * having band offsets 0,1,... will be returned. Otherwise the Raster returned by <code>
   * im.copyData(null)</code> will be returned.
   */
  private static final Raster getContiguousData(RenderedImage im, Rectangle region) {
    if (im == null) {
      throw new IllegalArgumentException("im == null");
    } else if (region == null) {
      throw new IllegalArgumentException("region == null");
    }

    Raster raster;
    if (im.getNumXTiles() == 1 && im.getNumYTiles() == 1) {
      // Image is not tiled so just get a reference to the tile.
      raster = im.getTile(im.getMinTileX(), im.getMinTileY());

      // Ensure result has requested coverage.
      Rectangle bounds = raster.getBounds();
      if (!bounds.equals(region)) {
        raster =
            raster.createChild(
                region.x, region.y, region.width, region.height, region.x, region.y, null);
      }
    } else {
      // Image is tiled.

      // Create an interleaved raster for copying for 8-bit case.
      // This ensures that for RGB data the band offsets are {0,1,2}.
      SampleModel sampleModel = im.getSampleModel();
      WritableRaster target =
          sampleModel.getSampleSize(0) == 8
              ? Raster.createInterleavedRaster(
                  DataBuffer.TYPE_BYTE,
                  im.getWidth(),
                  im.getHeight(),
                  sampleModel.getNumBands(),
                  new Point(im.getMinX(), im.getMinY()))
              : null;

      // Copy the data.
      raster = im.copyData(target);
    }

    return raster;
  }
示例#17
0
  @Override
  protected void computeRect(
      final PlanarImage[] sources, final WritableRaster dest, final Rectangle destRect) {
    final PlanarImage source = sources[0];
    final Rectangle bounds = destRect.intersection(source.getBounds());
    if (!destRect.equals(bounds)) {
      // TODO: Check if this case occurs sometime, and fill pixel values if it does.
      //       If it happen to occurs, we will need to fix other GeoTools operations
      //       as well.
      Logging.getLogger(TransformException.class)
          .warning("Bounds mismatch: " + destRect + " and " + bounds);
    }
    WritableRectIter iterator = RectIterFactory.createWritable(dest, bounds);

    // TODO: Detect if source and destination rasters are the same. If they are
    //       the same, we should skip this block. Iteration will then be faster.
    iterator = TransfertRectIter.create(RectIterFactory.create(source, bounds), iterator);

    if (!iterator.finishedBands()) {
      do {
        recode(iterator);
      } while (!iterator.nextBandDone());
    }
  }
示例#18
0
  /**
   * @param g
   * @param s get the boundaryvalues for the shape
   */
  public static void paintTexture(Graphics2D g, Shape s, DrawingPad pad) {
    Rectangle r = s.getBounds();
    if (r.height <= 0 || r.width <= 0) return;
    /**
     * when the height and width of the symbol is greater than 0 then GraphicsConfiguration is set
     * to DeviceConnfiguration
     */
    GraphicsConfiguration config = g.getDeviceConfiguration();
    BufferedImage strip = (BufferedImage) pad.getImage();

    /** creates an object gstrip for drawing horizontal and vertical strip */
    Graphics2D gStrip = strip.createGraphics();

    horStrip(gStrip, strip, 0, r.width, 0);
    gStrip.dispose();

    Shape prevClip = g.getClip();
    if (!r.equals(s)) {
      g.clip(s);
    }

    vertStrip(g, strip, r.y, r.height, r.x);
    g.setClip(prevClip);
  }
  public void show(Component owner, int aScreenX, int aScreenY, final boolean considerForcedXY) {
    if (ApplicationManagerEx.getApplicationEx() != null
        && ApplicationManager.getApplication().isHeadlessEnvironment()) return;
    if (isDisposed()) {
      throw new IllegalStateException(
          "Popup was already disposed. Recreate a new instance to show again");
    }

    assert ApplicationManager.getApplication().isDispatchThread();

    addActivity();

    final boolean shouldShow = beforeShow();
    if (!shouldShow) {
      removeActivity();
      return;
    }

    prepareToShow();

    if (myInStack) {
      myFocusTrackback = new FocusTrackback(this, owner, true);
      myFocusTrackback.setMustBeShown(true);
    }

    Dimension sizeToSet = null;

    if (myDimensionServiceKey != null) {
      sizeToSet = DimensionService.getInstance().getSize(myDimensionServiceKey, myProject);
    }

    if (myForcedSize != null) {
      sizeToSet = myForcedSize;
    }

    if (myMinSize == null) {
      myMinSize = myContent.getMinimumSize();
    }

    if (sizeToSet == null) {
      sizeToSet = myContent.getPreferredSize();
    }

    if (sizeToSet != null) {
      sizeToSet.width = Math.max(sizeToSet.width, myMinSize.width);
      sizeToSet.height = Math.max(sizeToSet.height, myMinSize.height);

      myContent.setSize(sizeToSet);
      myContent.setPreferredSize(sizeToSet);
    }

    Point xy = new Point(aScreenX, aScreenY);
    boolean adjustXY = true;
    if (myDimensionServiceKey != null) {
      final Point storedLocation =
          DimensionService.getInstance().getLocation(myDimensionServiceKey, myProject);
      if (storedLocation != null) {
        xy = storedLocation;
        adjustXY = false;
      }
    }

    if (adjustXY) {
      final Insets insets = myContent.getInsets();
      if (insets != null) {
        xy.x -= insets.left;
        xy.y -= insets.top;
      }
    }

    if (considerForcedXY && myForcedLocation != null) {
      xy = myForcedLocation;
    }

    if (myLocateByContent) {
      final Dimension captionSize = myHeaderPanel.getPreferredSize();
      xy.y -= captionSize.height;
    }

    Rectangle targetBounds = new Rectangle(xy, myContent.getPreferredSize());
    Insets insets = myPopupBorder.getBorderInsets(myContent);
    if (insets != null) {
      targetBounds.x += insets.left;
      targetBounds.y += insets.top;
    }

    Rectangle original = new Rectangle(targetBounds);
    if (myLocateWithinScreen) {
      ScreenUtil.moveRectangleToFitTheScreen(targetBounds);
    }

    if (myMouseOutCanceller != null) {
      myMouseOutCanceller.myEverEntered = targetBounds.equals(original);
    }

    myOwner = IdeFrameImpl.findNearestModalComponent(owner);
    if (myOwner == null) {
      myOwner = owner;
    }

    myRequestorComponent = owner;

    boolean forcedDialog = (SystemInfo.isMac && !(myOwner instanceof IdeFrame)) || myMayBeParent;

    PopupComponent.Factory factory = getFactory(myForcedHeavyweight || myResizable, forcedDialog);
    myNativePopup = factory.isNativePopup();
    myPopup = factory.getPopup(myOwner, myContent, targetBounds.x, targetBounds.y);

    if (myResizable) {
      final JRootPane root = myContent.getRootPane();
      final IdeGlassPaneImpl glass = new IdeGlassPaneImpl(root);
      root.setGlassPane(glass);

      final ResizeComponentListener resizeListener = new ResizeComponentListener(this, glass);
      glass.addMousePreprocessor(resizeListener, this);
      glass.addMouseMotionPreprocessor(resizeListener, this);
    }

    if (myCaption != null && myMovable) {
      final MoveComponentListener moveListener =
          new MoveComponentListener(myCaption) {
            public void mousePressed(final MouseEvent e) {
              super.mousePressed(e);
              if (e.isConsumed()) return;

              if (UIUtil.isCloseClick(e)) {
                if (myCaption.isWithinPanel(e)) {
                  cancel();
                }
              }
            }
          };
      ListenerUtil.addMouseListener(myCaption, moveListener);
      ListenerUtil.addMouseMotionListener(myCaption, moveListener);
      final MyContentPanel saved = myContent;
      Disposer.register(
          this,
          new Disposable() {
            public void dispose() {
              ListenerUtil.removeMouseListener(saved, moveListener);
              ListenerUtil.removeMouseMotionListener(saved, moveListener);
            }
          });
    }

    for (JBPopupListener listener : myListeners) {
      listener.beforeShown(new LightweightWindowEvent(this));
    }

    myPopup.setRequestFocus(myRequestFocus);
    myPopup.show();

    final Window window = SwingUtilities.getWindowAncestor(myContent);

    myWindowListener = new MyWindowListener();
    window.addWindowListener(myWindowListener);

    if (myFocusable) {
      window.setFocusableWindowState(true);
      window.setFocusable(true);
    }

    myWindow = updateMaskAndAlpha(window);

    if (myWindow instanceof JWindow) {
      ((JWindow) myWindow).getRootPane().putClientProperty(KEY, this);
    }

    if (myWindow != null) {
      // dialogwrapper-based popups do this internally through peer,
      // for other popups like jdialog-based we should exclude them manually, but
      // we still have to be able to use IdeFrame as parent
      if (!myMayBeParent && !(myWindow instanceof Frame)) {
        WindowManager.getInstance().doNotSuggestAsParent(myWindow);
      }
    }

    final Runnable afterShow =
        new Runnable() {
          public void run() {
            if (myPreferredFocusedComponent != null && myInStack && myFocusable) {
              myFocusTrackback.registerFocusComponent(myPreferredFocusedComponent);
            }

            removeActivity();

            afterShow();
          }
        };

    if (myRequestFocus) {
      getFocusManager()
          .requestFocus(
              new FocusCommand() {
                @Override
                public ActionCallback run() {
                  if (isDisposed()) {
                    removeActivity();
                    return new ActionCallback.Done();
                  }

                  _requestFocus();

                  final ActionCallback result = new ActionCallback();

                  final Runnable afterShowRunnable =
                      new Runnable() {
                        @Override
                        public void run() {
                          afterShow.run();
                          result.setDone();
                        }
                      };
                  if (myNativePopup) {
                    final FocusRequestor furtherRequestor = getFocusManager().getFurtherRequestor();
                    SwingUtilities.invokeLater(
                        new Runnable() {
                          @Override
                          public void run() {
                            if (isDisposed()) {
                              result.setRejected();
                              return;
                            }

                            furtherRequestor
                                .requestFocus(
                                    new FocusCommand() {
                                      @Override
                                      public ActionCallback run() {
                                        if (isDisposed()) {
                                          return new ActionCallback.Rejected();
                                        }

                                        _requestFocus();

                                        afterShowRunnable.run();

                                        return new ActionCallback.Done();
                                      }
                                    },
                                    true)
                                .notify(result)
                                .doWhenProcessed(
                                    new Runnable() {
                                      @Override
                                      public void run() {
                                        removeActivity();
                                      }
                                    });
                          }
                        });
                  } else {
                    afterShowRunnable.run();
                  }

                  return result;
                }
              },
              true)
          .doWhenRejected(
              new Runnable() {
                @Override
                public void run() {
                  afterShow.run();
                }
              });
    } else {
      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              if (isDisposed()) {
                removeActivity();
                return;
              }

              afterShow.run();
            }
          });
    }
  }
示例#20
0
  public RawRenderedImage(
      RawImageInputStream iis, RawImageReader reader, ImageReadParam param, int imageIndex)
      throws IOException {
    this.iis = iis;
    this.reader = reader;
    this.param = param;
    this.imageIndex = imageIndex;
    this.position = iis.getImageOffset(imageIndex);
    this.originalDimension = iis.getImageDimension(imageIndex);

    ImageTypeSpecifier type = iis.getImageType();
    sampleModel = originalSampleModel = type.getSampleModel();
    colorModel = type.getColorModel();

    // If the destination band is set used it
    sourceBands = (param == null) ? null : param.getSourceBands();

    if (sourceBands == null) {
      nComp = originalSampleModel.getNumBands();
      sourceBands = new int[nComp];
      for (int i = 0; i < nComp; i++) sourceBands[i] = i;
    } else {
      sampleModel = originalSampleModel.createSubsetSampleModel(sourceBands);
      colorModel = ImageUtil.createColorModel(null, sampleModel);
    }

    nComp = sourceBands.length;

    destinationBands = (param == null) ? null : param.getDestinationBands();
    if (destinationBands == null) {
      destinationBands = new int[nComp];
      for (int i = 0; i < nComp; i++) destinationBands[i] = i;
    }

    Dimension dim = iis.getImageDimension(imageIndex);
    this.width = dim.width;
    this.height = dim.height;

    Rectangle sourceRegion = new Rectangle(0, 0, this.width, this.height);

    originalRegion = (Rectangle) sourceRegion.clone();

    destinationRegion = (Rectangle) sourceRegion.clone();

    if (param != null) {
      RawImageReader.computeRegionsWrapper(
          param, this.width, this.height, param.getDestination(), sourceRegion, destinationRegion);
      scaleX = param.getSourceXSubsampling();
      scaleY = param.getSourceYSubsampling();
      xOffset = param.getSubsamplingXOffset();
      yOffset = param.getSubsamplingYOffset();
    }

    sourceOrigin = new Point(sourceRegion.x, sourceRegion.y);
    if (!destinationRegion.equals(sourceRegion)) noTransform = false;

    this.tileDataSize = ImageUtil.getTileSize(originalSampleModel);

    this.tileWidth = originalSampleModel.getWidth();
    this.tileHeight = originalSampleModel.getHeight();
    this.tileGridXOffset = destinationRegion.x;
    this.tileGridYOffset = destinationRegion.y;
    this.originalNumXTiles = getNumXTiles();

    this.width = destinationRegion.width;
    this.height = destinationRegion.height;
    this.minX = destinationRegion.x;
    this.minY = destinationRegion.y;

    sampleModel = sampleModel.createCompatibleSampleModel(tileWidth, tileHeight);

    maxXTile = originalDimension.width / tileWidth;
    maxYTile = originalDimension.height / tileHeight;
  }
  private void dragFrameFaster(JComponent f, int newX, int newY) {

    Rectangle previousBounds =
        new Rectangle(currentBounds.x, currentBounds.y, currentBounds.width, currentBounds.height);

    // move the frame
    currentBounds.x = newX;
    currentBounds.y = newY;

    if (didDrag) {
      // Only initiate cleanup if we have actually done a drag.
      emergencyCleanup(f);
    } else {
      didDrag = true;
      // We reset the danger field as until now we haven't actually
      // moved the internal frame so we don't need to initiate repaint.
      ((JInternalFrame) f).danger = false;
    }

    boolean floaterCollision = isFloaterCollision(previousBounds, currentBounds);

    // System.out.println(previousBounds);
    JComponent parent = (JComponent) f.getParent();
    Rectangle visBounds = previousBounds.intersection(desktopBounds);
    //  System.out.println(previousBounds);

    // System.out.println(visBounds);

    RepaintManager currentManager = RepaintManager.currentManager(f);

    currentManager.beginPaint();
    try {
      if (!floaterCollision) {
        currentManager.copyArea(
            parent,
            desktopGraphics,
            visBounds.x,
            visBounds.y,
            visBounds.width,
            visBounds.height,
            newX - previousBounds.x,
            newY - previousBounds.y,
            true);
      }

      f.setBounds(currentBounds);

      if (floaterCollision) {
        // since we couldn't blit we just redraw as fast as possible
        // the isDragging mucking is to avoid activating emergency
        // cleanup
        ((JInternalFrame) f).isDragging = false;
        parent.paintImmediately(currentBounds);
        ((JInternalFrame) f).isDragging = true;
      }

      // fake out the repaint manager.  We'll take care of everything

      currentManager.markCompletelyClean(parent);
      currentManager.markCompletelyClean(f);

      // compute the minimal newly exposed area
      // if the rects intersect then we use computeDifference.  Otherwise
      // we'll repaint the entire previous bounds
      Rectangle[] dirtyRects = null;
      if (previousBounds.intersects(currentBounds)) {
        dirtyRects = SwingUtilities.computeDifference(previousBounds, currentBounds);
      } else {
        dirtyRects = new Rectangle[1];
        dirtyRects[0] = previousBounds;
        //  System.out.println("no intersection");
      }
      ;

      // Fix the damage
      for (int i = 0; i < dirtyRects.length; i++) {
        parent.paintImmediately(dirtyRects[i]);
      }

      // new areas of blit were exposed
      if (!(visBounds.equals(previousBounds))) {
        dirtyRects = SwingUtilities.computeDifference(previousBounds, desktopBounds);
        for (int i = 0; i < dirtyRects.length; i++) {
          dirtyRects[i].x += newX - previousBounds.x;
          dirtyRects[i].y += newY - previousBounds.y;
          ((JInternalFrame) f).isDragging = false;

          parent.paintImmediately(dirtyRects[i]);
          ((JInternalFrame) f).isDragging = true;

          // System.out.println(dirtyRects[i]);
        }
      }
    } finally {
      currentManager.endPaint();
    }

    // update window if it's non-opaque
    Window topLevel = SwingUtilities.getWindowAncestor(f);
    Toolkit tk = Toolkit.getDefaultToolkit();
    if (!AWTAccessor.getWindowAccessor().isOpaque(topLevel)
        && (tk instanceof SunToolkit)
        && ((SunToolkit) tk).needUpdateWindow()) {
      AWTAccessor.getWindowAccessor().updateWindow(topLevel);
    }
  }
  protected boolean canDirectlyAccessGraphics() {
    // TODO: what about popup windows / tooltips???

    // TODO: some of the queries could be cached instead of polling,
    // for example isShowing(), isOpaque(), getParent() etc.

    //////        // Shouldn't access graphics - no buffering would cause flickering
    //////        if (bufferType == BUFFER_NONE) return false;

    // Cannot access graphics - there are some child components
    if (getComponentCount() != 0) return false;

    // Cannot access graphics - component doesn't fully control its area
    if (!isOpaque()) return false;

    // Cannot access graphics - not in Swing tree
    if (!(getParent() instanceof JComponent)) return false;

    // Cannot access graphics - component not showing, doesn't make sense
    if (!isShowing()) return false;

    // Cannot access graphics - component area is not up-to-date
    Rectangle dirtyRegion =
        RepaintManager.currentManager(this).getDirtyRegion((JComponent) getParent());
    if (dirtyRegion != null && dirtyRegion.width > 0 && dirtyRegion.height > 0) return false;

    // --- Reused from JViewport -------------------------------------------

    Rectangle clip = new Rectangle(0, 0, getWidth(), getHeight());
    Rectangle oldClip = new Rectangle();
    Rectangle tmp2 = null;
    Container parent;
    Component lastParent = null;
    int x, y, w, h;

    for (parent = this;
        parent != null && isLightweightComponent(parent);
        parent = parent.getParent()) {
      x = parent.getX();
      y = parent.getY();
      w = parent.getWidth();
      h = parent.getHeight();

      oldClip.setBounds(clip);
      SwingUtilities.computeIntersection(0, 0, w, h, clip);
      if (!clip.equals(oldClip)) return false;

      if (lastParent != null
          && parent instanceof JComponent
          && !((JComponent) parent).isOptimizedDrawingEnabled()) {
        Component comps[] = parent.getComponents();
        int index = 0;

        for (int i = comps.length - 1; i >= 0; i--) {
          if (comps[i] == lastParent) {
            index = i - 1;
            break;
          }
        }

        while (index >= 0) {
          tmp2 = comps[index].getBounds(tmp2);
          if (tmp2.intersects(clip)) return false;
          index--;
        }
      }
      clip.x += x;
      clip.y += y;
      lastParent = parent;
    }

    // No Window parent.
    if (parent == null) return false;

    return true;
  }
示例#23
0
  public static void main(String args[]) throws Exception {

    try {
      UIManager.setLookAndFeel(new NimbusLookAndFeel());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    SwingUtilities.invokeAndWait(
        () -> {
          JPanel panel0 = new JPanel();
          JPanel panel2 = new JPanel();
          BadPane badPane = new BadPane();
          badPane.add("zero", panel0);
          badPane.add("one", null); // no component
          badPane.add("", panel2); // no title
          badPane.add("", null); // no component, no title
          // but give it that via a tabComponent
          JPanel tabComponent = new JPanel();
          JLabel tabComponentLabel = new JLabel("three");
          tabComponent.add(tabComponentLabel);
          badPane.setTabComponentAt(3, tabComponent);
          JFrame frame = new JFrame();
          frame.add(badPane);
          frame.setSize(300, 300);
          frame.setVisible(true);

          try {
            AccessibleContext ac = badPane.getAccessibleContext();
            Accessible page0 = ac.getAccessibleChild(0);
            if (page0 == null) {
              // Not something being tested, but checking anyway
              throw new RuntimeException("getAccessibleChild(0) is null");
            }
            Accessible page1 = ac.getAccessibleChild(1);
            if (page1 == null) {
              // Not something being tested, but checking anyway
              throw new RuntimeException("getAccessibleChild(1) is null");
            }
            Accessible page2 = ac.getAccessibleChild(2);
            Accessible page3 = ac.getAccessibleChild(3);
            // page0 - page3 are JTabbedPane.Page, a private inner class
            // and is an AccessibleContext
            // and implements Accessible and AccessibleComponent
            AccessibleContext pac0 = page0.getAccessibleContext();
            AccessibleContext pac1 = page1.getAccessibleContext();
            AccessibleContext pac2 = page2.getAccessibleContext();
            AccessibleContext pac3 = page3.getAccessibleContext();

            // test Page.getBounds
            // ensure no IndexOutOfBoundsException
            Rectangle r0 = pac0.getAccessibleComponent().getBounds();
            // make sure second Bounds is different than first
            Rectangle r1 = pac1.getAccessibleComponent().getBounds();
            if (r1.equals(r0)) {
              String msg = "Second tab should not have same bounds as first tab";
              throw new RuntimeException(msg);
            }

            // test Page.getAccessibleStateSet
            // At this point page 0 is selected
            AccessibleStateSet accSS0 = pac0.getAccessibleStateSet();
            if (!accSS0.contains(AccessibleState.SELECTED)) {
              String msg = "Empty title -> AccessibleState.SELECTED not set";
              throw new RuntimeException(msg);
            }
            // select second tab
            badPane.setSelectedIndex(1);
            AccessibleStateSet accSS1 = pac1.getAccessibleStateSet();
            if (!accSS1.contains(AccessibleState.SELECTED)) {
              String msg = "Second tab selected but AccessibleState.SELECTED not set";
              throw new RuntimeException(msg);
            }
            // select third tab
            badPane.setSelectedIndex(2);
            AccessibleStateSet accSS2 = pac2.getAccessibleStateSet();
            if (!accSS1.contains(AccessibleState.SELECTED)) {
              String msg = "Third tab selected but AccessibleState.SELECTED not set";
              throw new RuntimeException(msg);
            }
            // select fourth tab
            badPane.setSelectedIndex(3);
            AccessibleStateSet accSS3 = pac3.getAccessibleStateSet();
            if (!accSS1.contains(AccessibleState.SELECTED)) {
              String msg = "Fourth tab selected but AccessibleState.SELECTED not set";
              throw new RuntimeException(msg);
            }

            // test Page.getAccessibleIndexInParent
            if (pac0.getAccessibleIndexInParent() == -1) {
              String msg = "Empty title -> negative AccessibleIndexInParent";
              throw new RuntimeException(msg);
            }
            if (pac0.getAccessibleIndexInParent() != 0) {
              String msg = "first tab is not at index 0 in parent";
              throw new RuntimeException(msg);
            }
            if (pac1.getAccessibleIndexInParent() != 1) {
              String msg = "second tab (null component) is not at index 1 in parent";
              throw new RuntimeException(msg);
            }
            if (pac2.getAccessibleIndexInParent() != 2) {
              String msg = "third tab (empty title) string is not at index 2 in parent";
              throw new RuntimeException(msg);
            }
            if (pac3.getAccessibleIndexInParent() != 3) {
              String msg =
                  "fourth tab (empty title, null component, has tabComponent) string is not at index 3 in parent";
              throw new RuntimeException(msg);
            }

            // test Page.getAccessibleName
            String accName = pac0.getAccessibleName();
            if (!accName.equals("zero")) {
              String msg = "Empty title -> empty AccessibleName";
              throw new RuntimeException(msg);
            }
            // test Page.getAccessibleName when component is null
            accName = pac1.getAccessibleName();
            if (!accName.equals("one")) {
              String msg = "AccessibleName of null panel not 'one'";
              throw new RuntimeException(msg);
            }

            // test Page.setDisplayedMnemonicIndex
            //  Empty title -> IllegalArgumnetException
            badPane.setDisplayedMnemonicIndexAt(0, 1);

            // test Page.updateDisplayedMnemonicIndex
            badPane.setMnemonicAt(0, KeyEvent.VK_Z);
            if (badPane.getDisplayedMnemonicIndexAt(0) == -1) {
              String msg = "Empty title -> getDisplayedMnemonicIndexAt failure";
              throw new RuntimeException(msg);
            }
          } catch (Exception e) {
            exception = e;
          }
        });
    if (exception != null) {
      System.out.println("Test failed: " + exception.getMessage());
      throw exception;
    } else {
      System.out.println("Test passed.");
    }
  }
示例#24
0
  /**
   * Applies the band select operation to a grid coverage.
   *
   * @param cropEnvelope the target envelope; always not null
   * @param cropROI the target ROI shape; nullable
   * @param roiTolerance; as read from op's params
   * @param sourceCoverage is the source {@link GridCoverage2D} that we want to crop.
   * @param hints A set of rendering hints, or {@code null} if none.
   * @param sourceGridToWorldTransform is the 2d grid-to-world transform for the source coverage.
   * @return The result as a grid coverage.
   */
  private static GridCoverage2D buildResult(
      final GeneralEnvelope cropEnvelope,
      final Geometry cropROI,
      final double roiTolerance,
      final boolean forceMosaic,
      final Hints hints,
      final GridCoverage2D sourceCoverage,
      final AffineTransform sourceGridToWorldTransform) {

    //
    // Getting the source coverage and its child geolocation objects
    //
    final RenderedImage sourceImage = sourceCoverage.getRenderedImage();
    final GridGeometry2D sourceGridGeometry = ((GridGeometry2D) sourceCoverage.getGridGeometry());
    final GridEnvelope2D sourceGridRange = sourceGridGeometry.getGridRange2D();

    //
    // Now we try to understand if we have a simple scale and translate or a
    // more elaborated grid-to-world transformation n which case a simple
    // crop could not be enough, but we may need a more elaborated chain of
    // operation in order to do a good job. As an instance if we
    // have a rotation which is not multiple of PI/2 we have to use
    // the mosaic with a ROI
    //
    final boolean isSimpleTransform =
        CoverageUtilities.isSimpleGridToWorldTransform(sourceGridToWorldTransform, EPS);

    // Do we need to explode the Palette to RGB(A)?
    //
    int actionTaken = 0;

    // //
    //
    // Layout
    //
    // //
    final RenderingHints targetHints = new RenderingHints(null);
    if (hints != null) targetHints.add(hints);
    final ImageLayout layout = initLayout(sourceImage, targetHints);
    targetHints.put(JAI.KEY_IMAGE_LAYOUT, layout);

    //
    // prepare the processor to use for this operation
    //
    final JAI processor = OperationJAI.getJAI(targetHints);
    final boolean useProvidedProcessor = !processor.equals(JAI.getDefaultInstance());

    try {

      if (cropROI != null) {
        // replace the cropEnvelope with the envelope of the intersection
        // of the ROI and the cropEnvelope.
        // Remember that envelope(intersection(roi,cropEnvelope)) != intersection(cropEnvelope,
        // envelope(roi))
        final Polygon modelSpaceROI = FeatureUtilities.getPolygon(cropEnvelope, GFACTORY);
        Geometry intersection = IntersectUtils.intersection(cropROI, modelSpaceROI);
        Envelope2D e2d =
            JTS.getEnvelope2D(
                intersection.getEnvelopeInternal(), cropEnvelope.getCoordinateReferenceSystem());
        GeneralEnvelope ge = new GeneralEnvelope((org.opengis.geometry.Envelope) e2d);
        cropEnvelope.setEnvelope(ge);
      }

      // //
      //
      // Build the new range by keeping into
      // account translation of grid geometry constructor for respecting
      // OGC PIXEL-IS-CENTER ImageDatum assumption.
      //
      // //
      final AffineTransform sourceWorldToGridTransform = sourceGridToWorldTransform.createInverse();

      // //
      //
      // finalRasterArea will hold the smallest rectangular integer raster area that contains the
      // floating point raster
      // area which we obtain when applying the world-to-grid transform to the cropEnvelope. Note
      // that we need to intersect
      // such an area with the area covered by the source coverage in order to be sure we do not try
      // to crop outside the
      // bounds of the source raster.
      //
      // //
      final Rectangle2D finalRasterAreaDouble =
          XAffineTransform.transform(
              sourceWorldToGridTransform, cropEnvelope.toRectangle2D(), null);
      final Rectangle finalRasterArea = finalRasterAreaDouble.getBounds();

      // intersection with the original range in order to not try to crop outside the image bounds
      Rectangle.intersect(finalRasterArea, sourceGridRange, finalRasterArea);
      if (finalRasterArea.isEmpty())
        throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP));

      // //
      //
      // It is worth to point out that doing a crop the G2W transform
      // should not change while the envelope might change as
      // a consequence of the rounding of the underlying image datum
      // which uses integer factors or in case the G2W is very
      // complex. Note that we will always strive to
      // conserve the original grid-to-world transform.
      //
      // //

      // we do not have to crop in this case (should not really happen at
      // this time)
      if (finalRasterArea.equals(sourceGridRange) && isSimpleTransform && cropROI == null)
        return sourceCoverage;

      // //
      //
      // if I get here I have something to crop
      // using the world-to-grid transform for going from envelope to the
      // new grid range.
      //
      // //
      final double minX = finalRasterArea.getMinX();
      final double minY = finalRasterArea.getMinY();
      final double width = finalRasterArea.getWidth();
      final double height = finalRasterArea.getHeight();

      // //
      //
      // Check if we need to use mosaic or crop
      //
      // //
      final PlanarImage croppedImage;
      final ParameterBlock pbj = new ParameterBlock();
      pbj.addSource(sourceImage);
      java.awt.Polygon rasterSpaceROI = null;
      String operatioName = null;
      if (!isSimpleTransform || cropROI != null) {
        // /////////////////////////////////////////////////////////////////////
        //
        // We don't have a simple scale and translate transform, JAI
        // crop MAY NOT suffice. Let's decide whether or not we'll use
        // the Mosaic.
        //
        // /////////////////////////////////////////////////////////////////////
        Polygon modelSpaceROI = FeatureUtilities.getPolygon(cropEnvelope, GFACTORY);

        // //
        //
        // Now convert this polygon back into a shape for the source
        // raster space.
        //
        // //
        final List<Point2D> points = new ArrayList<Point2D>(5);
        rasterSpaceROI =
            FeatureUtilities.convertPolygonToPointArray(
                modelSpaceROI, ProjectiveTransform.create(sourceWorldToGridTransform), points);
        if (rasterSpaceROI == null || rasterSpaceROI.getBounds().isEmpty())
          if (finalRasterArea.isEmpty())
            throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP));
        final boolean doMosaic =
            forceMosaic
                ? true
                : decideJAIOperation(roiTolerance, rasterSpaceROI.getBounds2D(), points);
        if (doMosaic || cropROI != null) {
          // prepare the params for the mosaic
          final ROI[] roiarr;
          try {
            if (cropROI != null) {
              final LiteShape2 cropRoiLS2 =
                  new LiteShape2(
                      cropROI, ProjectiveTransform.create(sourceWorldToGridTransform), null, false);
              ROI cropRS = new ROIShape(cropRoiLS2);
              Rectangle2D rt = cropRoiLS2.getBounds2D();
              if (!hasIntegerBounds(rt)) {
                // Approximate Geometry
                Geometry geo = (Geometry) cropRoiLS2.getGeometry().clone();
                transformGeometry(geo);
                cropRS = new ROIShape(new LiteShape2(geo, null, null, false));
              }
              roiarr = new ROI[] {cropRS};
            } else {
              final ROIShape roi = new ROIShape(rasterSpaceROI);
              roiarr = new ROI[] {roi};
            }
          } catch (FactoryException ex) {
            throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP), ex);
          }
          pbj.add(MosaicDescriptor.MOSAIC_TYPE_OVERLAY);
          pbj.add(null);
          pbj.add(roiarr);
          pbj.add(null);
          pbj.add(CoverageUtilities.getBackgroundValues(sourceCoverage));

          // prepare the final layout
          final Rectangle bounds = rasterSpaceROI.getBounds2D().getBounds();
          Rectangle.intersect(bounds, sourceGridRange, bounds);
          if (bounds.isEmpty()) throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP));

          // we do not have to crop in this case (should not really happen at
          // this time)
          if (!doMosaic && bounds.getBounds().equals(sourceGridRange) && isSimpleTransform)
            return sourceCoverage;

          // nice trick, we use the layout to do the actual crop
          final Rectangle boundsInt = bounds.getBounds();
          layout.setMinX(boundsInt.x);
          layout.setWidth(boundsInt.width);
          layout.setMinY(boundsInt.y);
          layout.setHeight(boundsInt.height);
          operatioName = "Mosaic";
        }
      }

      // do we still have to set the operation name? If so that means we have to go for crop.
      if (operatioName == null) {
        // executing the crop
        pbj.add((float) minX);
        pbj.add((float) minY);
        pbj.add((float) width);
        pbj.add((float) height);
        operatioName = "GTCrop";
      }
      // //
      //
      // Apply operation
      //
      // //
      if (!useProvidedProcessor) {
        croppedImage = JAI.create(operatioName, pbj, targetHints);
      } else {
        croppedImage = processor.createNS(operatioName, pbj, targetHints);
      }

      // conserve the input grid to world transformation
      Map sourceProperties = sourceCoverage.getProperties();
      Map properties = null;
      if (sourceProperties != null && !sourceProperties.isEmpty()) {
        properties = new HashMap(sourceProperties);
      }
      if (rasterSpaceROI != null) {
        if (properties != null) {
          properties.put("GC_ROI", rasterSpaceROI);
        } else {
          properties = Collections.singletonMap("GC_ROI", rasterSpaceROI);
        }
      }

      return new GridCoverageFactory(hints)
          .create(
              sourceCoverage.getName(),
              croppedImage,
              new GridGeometry2D(
                  new GridEnvelope2D(croppedImage.getBounds()),
                  sourceGridGeometry.getGridToCRS2D(PixelOrientation.CENTER),
                  sourceCoverage.getCoordinateReferenceSystem()),
              (GridSampleDimension[])
                  (actionTaken == 1 ? null : sourceCoverage.getSampleDimensions().clone()),
              new GridCoverage[] {sourceCoverage},
              properties);

    } catch (TransformException e) {
      throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP), e);
    } catch (NoninvertibleTransformException e) {
      throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP), e);
    }
  }
示例#25
0
  private void initializeRead(int imageIndex, J2KImageReadParamJava param, J2KMetadata metadata) {
    try {
      iis.mark();
      in = new IISRandomAccessIO(iis);

      // **** File Format ****
      // If the codestream is wrapped in the jp2 fileformat, Read the
      // file format wrapper
      ff = new FileFormatReader(in, metadata);
      ff.readFileFormat();
      in.seek(ff.getFirstCodeStreamPos());

      hi = new HeaderInfo();
      try {
        hd = new HeaderDecoder(in, j2krparam, hi);
      } catch (EOFException e) {
        throw new RuntimeException(I18N.getString("J2KReadState2"));
      } catch (IOException ioe) {
        throw new RuntimeException(ioe);
      }

      this.width = hd.getImgWidth();
      this.height = hd.getImgHeight();

      Rectangle sourceRegion = param.getSourceRegion();
      sourceOrigin = new Point();
      sourceRegion = new Rectangle(hd.getImgULX(), hd.getImgULY(), this.width, this.height);

      // if the subsample rate for components are not consistent
      boolean compConsistent = true;
      stepX = hd.getCompSubsX(0);
      stepY = hd.getCompSubsY(0);
      for (int i = 1; i < nComp; i++) {
        if (stepX != hd.getCompSubsX(i) || stepY != hd.getCompSubsY(i))
          throw new RuntimeException(I18N.getString("J2KReadState12"));
      }

      // Get minimum number of resolution levels available across
      // all tile-components.
      int minResLevels = hd.getDecoderSpecs().dls.getMin();

      // Set current resolution level.
      this.resolution = param != null ? param.getResolution() : minResLevels;
      if (resolution < 0 || resolution > minResLevels) {
        resolution = minResLevels;
      }

      // Convert source region to lower resolution level.
      if (resolution != minResLevels || stepX != 1 || stepY != 1) {
        sourceRegion =
            J2KImageReader.getReducedRect(sourceRegion, minResLevels, resolution, stepX, stepY);
      }

      destinationRegion = (Rectangle) sourceRegion.clone();

      J2KImageReader.computeRegionsWrapper(
          param,
          false,
          this.width,
          this.height,
          param.getDestination(),
          sourceRegion,
          destinationRegion);

      sourceOrigin = new Point(sourceRegion.x, sourceRegion.y);
      scaleX = param.getSourceXSubsampling();
      scaleY = param.getSourceYSubsampling();
      xOffset = param.getSubsamplingXOffset();
      yOffset = param.getSubsamplingYOffset();

      this.width = destinationRegion.width;
      this.height = destinationRegion.height;

      Point tileOffset = hd.getTilingOrigin(null);

      this.tileWidth = hd.getNomTileWidth();
      this.tileHeight = hd.getNomTileHeight();

      // Convert tile 0 to lower resolution level.
      if (resolution != minResLevels || stepX != 1 || stepY != 1) {
        Rectangle tileRect = new Rectangle(tileOffset);
        tileRect.width = tileWidth;
        tileRect.height = tileHeight;
        tileRect = J2KImageReader.getReducedRect(tileRect, minResLevels, resolution, stepX, stepY);
        tileOffset = tileRect.getLocation();
        tileWidth = tileRect.width;
        tileHeight = tileRect.height;
      }

      tileXOffset = tileOffset.x;
      tileYOffset = tileOffset.y;

      // Set the tile step sizes. These values are used because it
      // is possible that tiles will be empty. In particular at lower
      // resolution levels when subsampling is used this may be the
      // case. This method of calculation will work at least for
      // Profile-0 images.
      if (tileWidth * (1 << (minResLevels - resolution)) * stepX > hd.getNomTileWidth()) {
        tileStepX =
            (tileWidth * (1 << (minResLevels - resolution)) * stepX + hd.getNomTileWidth() - 1)
                / hd.getNomTileWidth();
      } else {
        tileStepX = 1;
      }

      if (tileHeight * (1 << (minResLevels - resolution)) * stepY > hd.getNomTileHeight()) {
        tileStepY =
            (tileHeight * (1 << (minResLevels - resolution)) * stepY + hd.getNomTileHeight() - 1)
                / hd.getNomTileHeight();
      } else {
        tileStepY = 1;
      }

      if (!destinationRegion.equals(sourceRegion)) noTransform = false;

      // **** Header decoder ****
      // Instantiate header decoder and read main header
      decSpec = hd.getDecoderSpecs();

      // **** Instantiate decoding chain ****
      // Get demixed bitdepths
      nComp = hd.getNumComps();

      int[] depth = new int[nComp];
      for (int i = 0; i < nComp; i++) depth[i] = hd.getOriginalBitDepth(i);

      // Get channel mapping
      ChannelDefinitionBox cdb = null;
      if (metadata != null)
        cdb = (ChannelDefinitionBox) metadata.getElement("JPEG2000ChannelDefinitionBox");

      channelMap = new int[nComp];
      if (cdb != null && metadata.getElement("JPEG2000PaletteBox") == null) {
        short[] assoc = cdb.getAssociation();
        short[] types = cdb.getTypes();
        short[] channels = cdb.getChannel();

        for (int i = 0; i < types.length; i++)
          if (types[i] == 0) channelMap[channels[i]] = assoc[i] - 1;
          else if (types[i] == 1 || types[i] == 2) channelMap[channels[i]] = channels[i];
      } else {
        for (int i = 0; i < nComp; i++) channelMap[i] = i;
      }

      // **** Bitstream reader ****
      try {
        boolean logJJ2000Messages = Boolean.getBoolean("jj2000.j2k.decoder.log");
        breader =
            BitstreamReaderAgent.createInstance(in, hd, j2krparam, decSpec, logJJ2000Messages, hi);
      } catch (IOException e) {
        throw new RuntimeException(
            I18N.getString("J2KReadState3")
                + " "
                + ((e.getMessage() != null) ? (":\n" + e.getMessage()) : ""));
      } catch (IllegalArgumentException e) {
        throw new RuntimeException(
            I18N.getString("J2KReadState4")
                + " "
                + ((e.getMessage() != null) ? (":\n" + e.getMessage()) : ""));
      }

      // **** Entropy decoder ****
      try {
        entdec = hd.createEntropyDecoder(breader, j2krparam);
      } catch (IllegalArgumentException e) {
        throw new RuntimeException(
            I18N.getString("J2KReadState5")
                + " "
                + ((e.getMessage() != null) ? (":\n" + e.getMessage()) : ""));
      }

      // **** ROI de-scaler ****
      try {
        roids = hd.createROIDeScaler(entdec, j2krparam, decSpec);
      } catch (IllegalArgumentException e) {
        throw new RuntimeException(
            I18N.getString("J2KReadState6")
                + " "
                + ((e.getMessage() != null) ? (":\n" + e.getMessage()) : ""));
      }

      // **** Dequantizer ****
      try {
        deq = hd.createDequantizer(roids, depth, decSpec);
      } catch (IllegalArgumentException e) {
        throw new RuntimeException(
            I18N.getString("J2KReadState7")
                + " "
                + ((e.getMessage() != null) ? (":\n" + e.getMessage()) : ""));
      }

      // **** Inverse wavelet transform ***
      try {
        // full page inverse wavelet transform
        invWT = InverseWT.createInstance(deq, decSpec);
      } catch (IllegalArgumentException e) {
        throw new RuntimeException(
            I18N.getString("J2KReadState8")
                + " "
                + ((e.getMessage() != null) ? (":\n" + e.getMessage()) : ""));
      }

      int res = breader.getImgRes();
      int mrl = decSpec.dls.getMin();
      invWT.setImgResLevel(res);

      // **** Data converter **** (after inverse transform module)
      converter = new ImgDataConverter(invWT, 0);

      // **** Inverse component transformation ****
      ictransf = new InvCompTransf(converter, decSpec, depth);

      // If the destination band is set used it
      sourceBands = j2krparam.getSourceBands();

      if (sourceBands == null) {
        sourceBands = new int[nComp];
        for (int i = 0; i < nComp; i++) sourceBands[i] = i;
      }

      nComp = sourceBands.length;

      destinationBands = j2krparam.getDestinationBands();
      if (destinationBands == null) {
        destinationBands = new int[nComp];
        for (int i = 0; i < nComp; i++) destinationBands[i] = i;
      }

      J2KImageReader.checkReadParamBandSettingsWrapper(
          param, hd.getNumComps(), destinationBands.length);

      levelShift = new int[nComp];
      minValues = new int[nComp];
      maxValues = new int[nComp];
      fracBits = new int[nComp];
      dataBlocks = new DataBlkInt[nComp];

      depth = new int[nComp];
      bandOffsets = new int[nComp];
      maxDepth = 0;
      isSigned = false;
      for (int i = 0; i < nComp; i++) {
        depth[i] = hd.getOriginalBitDepth(sourceBands[i]);
        if (depth[i] > maxDepth) maxDepth = depth[i];
        dataBlocks[i] = new DataBlkInt();

        // XXX: may need to change if ChannelDefinition is used to
        // define the color channels, such as BGR order
        bandOffsets[i] = i;
        if (hd.isOriginalSigned(sourceBands[i])) isSigned = true;
        else {
          levelShift[i] = 1 << (ictransf.getNomRangeBits(sourceBands[i]) - 1);
        }

        // Get the number of bits in the image, and decide what the max
        // value should be, depending on whether it is signed or not
        int nomRangeBits = ictransf.getNomRangeBits(sourceBands[i]);
        maxValues[i] = (1 << (isSigned == true ? (nomRangeBits - 1) : nomRangeBits)) - 1;
        minValues[i] = isSigned ? -(maxValues[i] + 1) : 0;

        fracBits[i] = ictransf.getFixedPoint(sourceBands[i]);
      }

      iis.reset();
    } catch (IllegalArgumentException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (Error e) {
      if (e.getMessage() != null) throw new RuntimeException(e.getMessage(), e);
      else {
        throw new RuntimeException(I18N.getString("J2KReadState9"), e);
      }
    } catch (RuntimeException e) {
      if (e.getMessage() != null)
        throw new RuntimeException(I18N.getString("J2KReadState10") + " " + e.getMessage(), e);
      else {
        throw new RuntimeException(I18N.getString("J2KReadState10"), e);
      }
    } catch (Throwable e) {
      throw new RuntimeException(I18N.getString("J2KReadState10"), e);
    }
  }
示例#26
0
  public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    checkIndex(imageIndex);
    readHeader();

    if (iis == null) throw new IllegalStateException("input is null");

    BufferedImage img;

    clearAbortRequest();
    processImageStarted(imageIndex);

    if (param == null) param = getDefaultReadParam();

    sourceRegion = new Rectangle(0, 0, 0, 0);
    destinationRegion = new Rectangle(0, 0, 0, 0);

    computeRegions(
        param, this.width, this.height, param.getDestination(), sourceRegion, destinationRegion);

    scaleX = param.getSourceXSubsampling();
    scaleY = param.getSourceYSubsampling();

    // If the destination band is set used it
    sourceBands = param.getSourceBands();
    destBands = param.getDestinationBands();

    seleBand = (sourceBands != null) && (destBands != null);
    noTransform = destinationRegion.equals(new Rectangle(0, 0, width, height)) || seleBand;

    if (!seleBand) {
      sourceBands = new int[colorPlanes];
      destBands = new int[colorPlanes];
      for (int i = 0; i < colorPlanes; i++) destBands[i] = sourceBands[i] = i;
    }

    // If the destination is provided, then use it.  Otherwise, create new one
    bi = param.getDestination();

    // Get the image data.
    WritableRaster raster = null;

    if (bi == null) {
      if (sampleModel != null && colorModel != null) {
        sampleModel =
            sampleModel.createCompatibleSampleModel(
                destinationRegion.width + destinationRegion.x,
                destinationRegion.height + destinationRegion.y);
        if (seleBand) sampleModel = sampleModel.createSubsetSampleModel(sourceBands);
        raster = Raster.createWritableRaster(sampleModel, new Point(0, 0));
        bi = new BufferedImage(colorModel, raster, false, null);
      }
    } else {
      raster = bi.getWritableTile(0, 0);
      sampleModel = bi.getSampleModel();
      colorModel = bi.getColorModel();

      noTransform &= destinationRegion.equals(raster.getBounds());
    }

    byte bdata[] = null; // buffer for byte data

    if (sampleModel.getDataType() == DataBuffer.TYPE_BYTE)
      bdata = (byte[]) ((DataBufferByte) raster.getDataBuffer()).getData();

    readImage(bdata);

    if (abortRequested()) processReadAborted();
    else processImageComplete();

    return bi;
  }
示例#27
0
 private boolean sameBounds(Raster r1, Raster r2) {
   Rectangle r1Bounds = r1.getBounds();
   Rectangle r2Bounds = r2.getBounds();
   return (r1Bounds.equals(r1Bounds));
 }
    public void mouseDragged(MouseEvent ev) {
      Window w = (Window) ev.getSource();
      Point pt = ev.getPoint();

      if (isMovingWindow) {
        Point windowPt;
        try {
          windowPt = (Point) AccessController.doPrivileged(getLocationAction);
          windowPt.x = windowPt.x - dragOffsetX;
          windowPt.y = windowPt.y - dragOffsetY;
          w.setLocation(windowPt);
        } catch (PrivilegedActionException e) {
        }
      } else if (dragCursor != 0) {
        Rectangle r = w.getBounds();
        Rectangle startBounds = new Rectangle(r);
        Dimension min = w.getMinimumSize();

        switch (dragCursor) {
          case Cursor.E_RESIZE_CURSOR:
            adjust(r, min, 0, 0, pt.x + (dragWidth - dragOffsetX) - r.width, 0);
            break;
          case Cursor.S_RESIZE_CURSOR:
            adjust(r, min, 0, 0, 0, pt.y + (dragHeight - dragOffsetY) - r.height);
            break;
          case Cursor.N_RESIZE_CURSOR:
            adjust(r, min, 0, pt.y - dragOffsetY, 0, -(pt.y - dragOffsetY));
            break;
          case Cursor.W_RESIZE_CURSOR:
            adjust(r, min, pt.x - dragOffsetX, 0, -(pt.x - dragOffsetX), 0);
            break;
          case Cursor.NE_RESIZE_CURSOR:
            adjust(
                r,
                min,
                0,
                pt.y - dragOffsetY,
                pt.x + (dragWidth - dragOffsetX) - r.width,
                -(pt.y - dragOffsetY));
            break;
          case Cursor.SE_RESIZE_CURSOR:
            adjust(
                r,
                min,
                0,
                0,
                pt.x + (dragWidth - dragOffsetX) - r.width,
                pt.y + (dragHeight - dragOffsetY) - r.height);
            break;
          case Cursor.NW_RESIZE_CURSOR:
            adjust(
                r,
                min,
                pt.x - dragOffsetX,
                pt.y - dragOffsetY,
                -(pt.x - dragOffsetX),
                -(pt.y - dragOffsetY));
            break;
          case Cursor.SW_RESIZE_CURSOR:
            adjust(
                r,
                min,
                pt.x - dragOffsetX,
                0,
                -(pt.x - dragOffsetX),
                pt.y + (dragHeight - dragOffsetY) - r.height);
            break;
          default:
            break;
        }
        if (!r.equals(startBounds)) {
          w.setBounds(r);
          // Defer repaint/validate on mouseReleased unless dynamic
          // layout is active.
          if (Toolkit.getDefaultToolkit().isDynamicLayoutActive()) {
            w.validate();
            getRootPane().repaint();
          }
        }
      }
    }
  public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param)
      throws IOException {
    if (stream == null) {
      throw new IllegalStateException(I18N.getString("WBMPImageWriter3"));
    }

    if (image == null) {
      throw new IllegalArgumentException(I18N.getString("WBMPImageWriter4"));
    }

    clearAbortRequest();
    processImageStarted(0);
    if (param == null) param = getDefaultWriteParam();

    RenderedImage input = null;
    Raster inputRaster = null;
    boolean writeRaster = image.hasRaster();
    Rectangle sourceRegion = param.getSourceRegion();
    SampleModel sampleModel = null;

    if (writeRaster) {
      inputRaster = image.getRaster();
      sampleModel = inputRaster.getSampleModel();
    } else {
      input = image.getRenderedImage();
      sampleModel = input.getSampleModel();

      inputRaster = input.getData();
    }

    checkSampleModel(sampleModel);
    if (sourceRegion == null) sourceRegion = inputRaster.getBounds();
    else sourceRegion = sourceRegion.intersection(inputRaster.getBounds());

    if (sourceRegion.isEmpty()) throw new RuntimeException(I18N.getString("WBMPImageWriter1"));

    int scaleX = param.getSourceXSubsampling();
    int scaleY = param.getSourceYSubsampling();
    int xOffset = param.getSubsamplingXOffset();
    int yOffset = param.getSubsamplingYOffset();

    sourceRegion.translate(xOffset, yOffset);
    sourceRegion.width -= xOffset;
    sourceRegion.height -= yOffset;

    int minX = sourceRegion.x / scaleX;
    int minY = sourceRegion.y / scaleY;
    int w = (sourceRegion.width + scaleX - 1) / scaleX;
    int h = (sourceRegion.height + scaleY - 1) / scaleY;

    Rectangle destinationRegion = new Rectangle(minX, minY, w, h);
    sampleModel = sampleModel.createCompatibleSampleModel(w, h);

    SampleModel destSM = sampleModel;

    // If the data are not formatted nominally then reformat.
    if (sampleModel.getDataType() != DataBuffer.TYPE_BYTE
        || !(sampleModel instanceof MultiPixelPackedSampleModel)
        || ((MultiPixelPackedSampleModel) sampleModel).getDataBitOffset() != 0) {
      destSM = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, w, h, 1, w + 7 >> 3, 0);
    }

    if (!destinationRegion.equals(sourceRegion)) {
      if (scaleX == 1 && scaleY == 1)
        inputRaster =
            inputRaster.createChild(
                inputRaster.getMinX(), inputRaster.getMinY(), w, h, minX, minY, null);
      else {
        WritableRaster ras = Raster.createWritableRaster(destSM, new Point(minX, minY));

        byte[] data = ((DataBufferByte) ras.getDataBuffer()).getData();

        for (int j = minY, y = sourceRegion.y, k = 0; j < minY + h; j++, y += scaleY) {

          for (int i = 0, x = sourceRegion.x; i < w; i++, x += scaleX) {
            int v = inputRaster.getSample(x, y, 0);
            data[k + (i >> 3)] |= v << (7 - (i & 7));
          }
          k += w + 7 >> 3;
        }
        inputRaster = ras;
      }
    }

    // If the data are not formatted nominally then reformat.
    if (!destSM.equals(inputRaster.getSampleModel())) {
      WritableRaster raster =
          Raster.createWritableRaster(
              destSM, new Point(inputRaster.getMinX(), inputRaster.getMinY()));
      raster.setRect(inputRaster);
      inputRaster = raster;
    }

    // Check whether the image is white-is-zero.
    boolean isWhiteZero = false;
    if (!writeRaster && input.getColorModel() instanceof IndexColorModel) {
      IndexColorModel icm = (IndexColorModel) input.getColorModel();
      isWhiteZero = icm.getRed(0) > icm.getRed(1);
    }

    // Get the line stride, bytes per row, and data array.
    int lineStride = ((MultiPixelPackedSampleModel) destSM).getScanlineStride();
    int bytesPerRow = (w + 7) / 8;
    byte[] bdata = ((DataBufferByte) inputRaster.getDataBuffer()).getData();

    // Write WBMP header.
    stream.write(0); // TypeField
    stream.write(0); // FixHeaderField
    stream.write(intToMultiByte(w)); // width
    stream.write(intToMultiByte(h)); // height

    // Write the data.
    if (!isWhiteZero && lineStride == bytesPerRow) {
      // Write the entire image.
      stream.write(bdata, 0, h * bytesPerRow);
      processImageProgress(100.0F);
    } else {
      // Write the image row-by-row.
      int offset = 0;
      if (!isWhiteZero) {
        // Black-is-zero
        for (int row = 0; row < h; row++) {
          if (abortRequested()) break;
          stream.write(bdata, offset, bytesPerRow);
          offset += lineStride;
          processImageProgress(100.0F * row / h);
        }
      } else {
        // White-is-zero: need to invert data.
        byte[] inverted = new byte[bytesPerRow];
        for (int row = 0; row < h; row++) {
          if (abortRequested()) break;
          for (int col = 0; col < bytesPerRow; col++) {
            inverted[col] = (byte) (~(bdata[col + offset]));
          }
          stream.write(inverted, 0, bytesPerRow);
          offset += lineStride;
          processImageProgress(100.0F * row / h);
        }
      }
    }

    if (abortRequested()) processWriteAborted();
    else {
      processImageComplete();
      stream.flushBefore(stream.getStreamPosition());
    }
  }