Esempio n. 1
0
  /**
   * Prints the specified page on the specified graphics using <code>pageForm</code> for the page
   * format.
   *
   * @param g The graphics to paint the graph on.
   * @param printFormat The page format to use for printing.
   * @param page The page to print
   * @return Returns {@link Printable#PAGE_EXISTS} or {@link Printable#NO_SUCH_PAGE}.
   */
  public int print(Graphics g, PageFormat printFormat, int page) {
    Dimension pSize = graph.getPreferredSize();
    int w = (int) (printFormat.getWidth() * pageScale);
    int h = (int) (printFormat.getHeight() * pageScale);
    int cols = (int) Math.max(Math.ceil((double) (pSize.width - 5) / (double) w), 1);
    int rows = (int) Math.max(Math.ceil((double) (pSize.height - 5) / (double) h), 1);
    if (page < cols * rows) {

      // Configures graph for printing
      RepaintManager currentManager = RepaintManager.currentManager(this);
      currentManager.setDoubleBufferingEnabled(false);
      double oldScale = getGraph().getScale();
      getGraph().setScale(1 / pageScale);
      int dx = (int) ((page % cols) * printFormat.getWidth());
      int dy = (int) ((page % rows) * printFormat.getHeight());
      g.translate(-dx, -dy);
      g.setClip(dx, dy, (int) (dx + printFormat.getWidth()), (int) (dy + printFormat.getHeight()));

      // Prints the graph on the graphics.
      getGraph().paint(g);

      // Restores graph
      g.translate(dx, dy);
      graph.setScale(oldScale);
      currentManager.setDoubleBufferingEnabled(true);
      return PAGE_EXISTS;
    } else {
      return NO_SUCH_PAGE;
    }
  }
 /**
  * Now, in this function, that will be called manually at the end of each operation, we repaint
  * the whole drawing area.
  */
 public void paintAll() {
   super.addDirtyRegion(
       drawingArea,
       drawingArea.getX(),
       drawingArea.getY(),
       drawingArea.getWidth(),
       drawingArea.getHeight());
   super.paintDirtyRegions();
 }
 /**
  * A helper method that performs some cleanup and disconnects the component from the AWT and the
  * Swing-Framework to avoid memory-leaks.
  */
 protected final void cleanUp() {
   if (component instanceof JComponent && isOwnPeerConnected() == false) {
     final JComponent jc = (JComponent) component;
     RepaintManager.currentManager(jc).removeInvalidComponent(jc);
     RepaintManager.currentManager(jc).markCompletelyClean(jc);
   }
   contentPane.removeAll();
   RepaintManager.currentManager(contentPane).removeInvalidComponent(contentPane);
   RepaintManager.currentManager(contentPane).markCompletelyClean(contentPane);
   peerSupply.dispose();
 }
Esempio n. 4
0
 /** [Internal] */
 public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
   if (pi >= 1) {
     return Printable.NO_SUCH_PAGE;
   }
   RepaintManager currentManager = RepaintManager.currentManager(this);
   currentManager.setDoubleBufferingEnabled(false);
   Graphics2D g2 = (Graphics2D) g;
   initState(g2, true);
   g2.translate((int) (pf.getImageableX() + 1), (int) (pf.getImageableY() + 1));
   g2.scale(printScale, printScale);
   doBuffer(g2, true, null);
   currentManager.setDoubleBufferingEnabled(true);
   return Printable.PAGE_EXISTS;
 }
Esempio n. 5
0
  /**
   * Obtains a {@code TranslucentRepaintManager} from the specified manager. If the current manager
   * is a {@code TranslucentRepaintManager} or a {@code ForwardingRepaintManager} that contains a
   * {@code TranslucentRepaintManager}, then the passed in manager is returned. Otherwise a new
   * repaint manager is created and returned.
   *
   * @param delegate the current repaint manager
   * @return a non-{@code null} {@code TranslucentRepaintManager}
   * @throws NullPointerException if {@code delegate} is {@code null}
   */
  static RepaintManager getTranslucentRepaintManager(RepaintManager delegate) {
    RepaintManager manager = delegate;

    while (manager != null
        && !manager.getClass().isAnnotationPresent(TranslucentRepaintManager.class)) {
      if (manager instanceof ForwardingRepaintManager) {
        manager = ((ForwardingRepaintManager) manager).getDelegateManager();
      } else {
        manager = null;
      }
    }

    return manager == null ? new RepaintManagerX(delegate) : delegate;
  }
 /** Initialize this plugin. */
 public synchronized void initialize() throws PluginException {
   _resources =
       new PluginResources(
           "net.sourceforge.squirrel_sql.plugins.swing-violation.swing-violation", this);
   EDTViolationRepaintManager manager = new EDTViolationRepaintManager(true, getApplication());
   RepaintManager.setCurrentManager(manager);
 }
Esempio n. 7
0
  public void propertyChange(PropertyChangeEvent event) {
    debug(this + " " + "propertyChange: " + event.getSource() + " " + event.getPropertyName());

    if (event.getSource() == searchnav) {
      String changeName = event.getPropertyName();
      if (changeName.equals("helpModel")) {

        reloadData((HelpModel) event.getNewValue());

      } else if (changeName.equals("font")) {
        debug("Font change");
        Font newFont = (Font) event.getNewValue();
        searchparams.setFont(newFont);
        RepaintManager.currentManager(searchparams).markCompletelyDirty(searchparams);
        tree.setFont(newFont);
        RepaintManager.currentManager(tree).markCompletelyDirty(tree);
      }
      // changes to UI property?
    }
  }
 @Override
 public void mouseMoved(MouseEvent e) {
   Point p =
       SwingUtilities.convertPoint(
           e.getComponent(), e.getX(), e.getY(), VsketchPreviewPane.this);
   boolean visible = buttonVisible;
   buttonVisible =
       p.getX() > getFitModeButtonX() - 40
           && p.getX() < getFitModeButtonX() + getFitModeButtonWidth();
   buttonVisible &=
       p.getY() > getFitModeButtonY() - 40
           && p.getY() < getFitModeButtonY() + getFitModeButtonHeight();
   if (visible != buttonVisible) {
     RepaintManager rm = RepaintManager.currentManager(VsketchPreviewPane.this);
     rm.addDirtyRegion(
         VsketchPreviewPane.this,
         getFitModeButtonX(),
         getFitModeButtonY(),
         getFitModeButtonWidth(),
         getFitModeButtonHeight());
   }
 }
Esempio n. 9
0
  /** Creates a new, blank {@code G2DGLCanvas} using the given OpenGL capabilities. */
  public GLG2DCanvas(GLCapabilities capabilities) {
    canvas = createGLComponent(capabilities, null);

    /*
     * Set both canvas and drawableComponent to be the same size, but we never
     * draw the drawableComponent except into the canvas.
     */
    setLayout(new GLOverlayLayout());
    add((Component) canvas);

    setGLDrawing(true);

    RepaintManager.setCurrentManager(GLAwareRepaintManager.INSTANCE);
  }
Esempio n. 10
0
  @Override
  public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
    try {
      throw new Exception();
    } catch (Exception exc) {
      StringBuffer sb = new StringBuffer();
      StackTraceElement[] stack = exc.getStackTrace();
      int count = 0;
      for (StackTraceElement stackEntry : stack) {
        if (count++ > 8) break;
        sb.append("\t");
        sb.append(stackEntry.getClassName() + ".");
        sb.append(stackEntry.getMethodName() + " [");
        sb.append(stackEntry.getLineNumber() + "]");
        sb.append("\n");
      }
      System.out.println("**** Repaint stack ****");
      System.out.println(sb.toString());
    }

    super.addDirtyRegion(c, x, y, w, h);
  }
 public static void main(String[] args) throws Exception {
   // set CheckThreadViolationRepaintManager
   RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
   // Valid code
   SwingUtilities.invokeAndWait(
       new Runnable() {
         public void run() {
           test();
         }
       });
   System.out.println("Valid code passed...");
   repaintTest();
   System.out.println("Repaint test - correct code");
   // Invalide code (stack trace expected)
   //        test();
   SwingUtilities.invokeAndWait(
       new Runnable() {
         public void run() {
           imageUpdateTest();
         }
       });
 }
Esempio n. 12
0
  public ApplicationImpl(
      boolean isInternal,
      boolean isUnitTestMode,
      boolean isHeadless,
      boolean isCommandLine,
      @NotNull String appName) {
    super(null);

    getPicoContainer().registerComponentInstance(Application.class, this);

    CommonBundle.assertKeyIsFound = isUnitTestMode;

    if ((isInternal || isUnitTestMode)
        && !Comparing.equal("off", System.getProperty("idea.disposer.debug"))) {
      Disposer.setDebugMode(true);
    }
    myStartTime = System.currentTimeMillis();
    myName = appName;
    ApplicationManagerEx.setApplication(this);

    PluginsFacade.INSTANCE =
        new PluginsFacade() {
          public IdeaPluginDescriptor getPlugin(PluginId id) {
            return PluginManager.getPlugin(id);
          }

          public IdeaPluginDescriptor[] getPlugins() {
            return PluginManager.getPlugins();
          }
        };

    if (!isUnitTestMode && !isHeadless) {
      Toolkit.getDefaultToolkit().getSystemEventQueue().push(IdeEventQueue.getInstance());
      if (Patches.SUN_BUG_ID_6209673) {
        RepaintManager.setCurrentManager(new IdeRepaintManager());
      }
      IconLoader.activate();
    }

    myIsInternal = isInternal;
    myTestModeFlag = isUnitTestMode;
    myHeadlessMode = isHeadless;
    myCommandLineMode = isCommandLine;

    loadApplicationComponents();

    if (myTestModeFlag) {
      registerShutdownHook();
    }

    if (!isUnitTestMode && !isHeadless) {
      Disposer.register(this, Disposer.newDisposable(), "ui");

      StartupUtil.addExternalInstanceListener(
          new Consumer<List<String>>() {
            @Override
            public void consume(final List<String> args) {
              invokeLater(
                  new Runnable() {
                    @Override
                    public void run() {
                      final Project project = CommandLineProcessor.processExternalCommandLine(args);
                      final IdeFrame frame;
                      if (project != null) {
                        frame = WindowManager.getInstance().getIdeFrame(project);
                      } else {
                        frame = WindowManager.getInstance().getAllFrames()[0];
                      }
                      ((IdeFrameImpl) frame).requestFocus();
                    }
                  });
            }
          });
    }

    final String s = System.getProperty("jb.restart.code");
    if (s != null) {
      try {
        myRestartCode = Integer.parseInt(s);
      } catch (NumberFormatException ignore) {
      }
    }
  }
 @Override
 public void addDirtyRegion(JComponent component, int x, int y, int w, int h) {
   checkThreadViolations(component);
   super.addDirtyRegion(component, x, y, w, h);
 }
 @Override
 public synchronized void addInvalidComponent(JComponent component) {
   checkThreadViolations(component);
   super.addInvalidComponent(component);
 }
Esempio n. 15
0
		public MainPanel() {
			RepaintManager.currentManager(this).setDoubleBufferingEnabled(true);
			this.setOpaque(true);
			this.setVisible(false);
		}
  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;
  }
 public synchronized void addInvalidComponent(JComponent component) {
   checkEDTRule(component);
   super.addInvalidComponent(component);
 }
 public synchronized void addDirtyRegion(JComponent component, int x, int y, int w, int h) {
   checkEDTRule(component);
   super.addDirtyRegion(component, x, y, w, h);
 }
Esempio n. 19
0
 public static void enableDoubleBuffering(Component c) {
   RepaintManager currentManager = RepaintManager.currentManager(c);
   currentManager.setDoubleBufferingEnabled(true);
 }
Esempio n. 20
0
  public static void startPrinting(
      IApplication application,
      Pageable pageable,
      PrinterJob a_printerJob,
      String a_preferredPrinterName,
      boolean showPrinterSelectDialog,
      boolean avoidDialogs) {
    RepaintManager currentManager =
        RepaintManager.currentManager(application.getPrintingRendererParent().getParent());
    boolean isDoubleBufferingEnabled = false;
    try {
      if (currentManager != null) {
        isDoubleBufferingEnabled = currentManager.isDoubleBufferingEnabled();
      }

      if (a_printerJob != null) {
        // for plugin printing
        a_printerJob.setPageable(pageable);
        a_printerJob.setJobName("Servoy Print"); // $NON-NLS-1$
        if (showPrinterSelectDialog) {
          if (!a_printerJob.printDialog()) {
            return;
          }
          SwingHelper.dispatchEvents(100); // hide dialog
        }
        if (currentManager != null) {
          currentManager.setDoubleBufferingEnabled(false);
        }
        a_printerJob.print();
      } else {
        // by default we use old system for mac, new is not always working
        boolean useSystemPrintDialog =
            Utils.getAsBoolean(
                application
                    .getSettings()
                    .getProperty(
                        "useSystemPrintDialog",
                        "" + Utils.isAppleMacOS())); // $NON-NLS-1$//$NON-NLS-2$
        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        if (capablePrintServices == null) {
          capablePrintServices = PrintServiceLookup.lookupPrintServices(flavor, pras);
        }

        PrintService service = null;
        if (capablePrintServices == null || capablePrintServices.length == 0) {
          if (avoidDialogs) {
            Debug.warn("Cannot find capable print services. Print aborted.");
            return;
          } else {
            JOptionPane.showConfirmDialog(
                ((ISmartClientApplication) application).getMainApplicationFrame(),
                application.getI18NMessage("servoy.print.msg.noPrintersFound"),
                application.getI18NMessage(
                    "servoy.print.printing.title"), //$NON-NLS-1$ //$NON-NLS-2$
                JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE);
            capablePrintServices = new PrintService[0];
            showPrinterSelectDialog = true; // must show select printer and if none found show this
            useSystemPrintDialog =
                true; // we leave to system to show no printers are found, important for apple mac
          }
        } else {
          service = capablePrintServices[0]; // default select
        }

        PrintService systemDefaultPrinter = PrintServiceLookup.lookupDefaultPrintService();
        if (systemDefaultPrinter != null) {
          // check if system default printer is in capable list
          for (PrintService ps : capablePrintServices) {
            if (ps.getName().equalsIgnoreCase(systemDefaultPrinter.getName())) {
              service = systemDefaultPrinter;
              break;
            }
          }
        }

        boolean didFindPrinter = true; // want custom preferred printer
        if (a_preferredPrinterName != null) {
          didFindPrinter = false;
          for (PrintService ps : capablePrintServices) {
            if (ps.getName().equalsIgnoreCase(a_preferredPrinterName)) {
              didFindPrinter = true;
              service = ps;
              break;
            }
          }
        }

        if (!didFindPrinter) {
          if (avoidDialogs) {
            Debug.warn(
                "Cannot find capable printer for preferred form printer name '"
                    + a_preferredPrinterName
                    + "'. Trying to use default/any capable printer.");
          } else {
            showPrinterSelectDialog = true; // did not found the prefered , do show
          }
        }

        if (!useSystemPrintDialog) {
          if (showPrinterSelectDialog) {
            JFrame frame = ((ISmartClientApplication) application).getMainApplicationFrame();
            GraphicsConfiguration gc = frame.getGraphicsConfiguration();
            Point loc = frame.getLocation();
            service =
                ServiceUI.printDialog(
                    gc, loc.x + 50, loc.y + 50, capablePrintServices, service, flavor, pras);
          }
          if (service != null) {
            if (currentManager != null) {
              currentManager.setDoubleBufferingEnabled(false);
            }
            DocPrintJob job = service.createPrintJob();
            DocAttributeSet das = new HashDocAttributeSet();
            Doc doc = new SimpleDoc(pageable, flavor, das);
            if (job != null) {
              job.print(doc, pras);
            } else {
              // for example if the print service cancels (e.g. print to pdf and then user cancel
              // when choosing save location)
              application.reportWarning(
                  application.getI18NMessage(
                      "servoy.print.error.cannotPrintDocument")); //$NON-NLS-1$
            }
          }
        } else {
          a_printerJob = PrinterJob.getPrinterJob();
          a_printerJob.setPageable(pageable);
          a_printerJob.setJobName("Servoy Print"); // $NON-NLS-1$
          if (service != null) {
            a_printerJob.setPrintService(service);
          }
          if (showPrinterSelectDialog) {
            if (!a_printerJob.printDialog()) {
              return;
            }
            SwingHelper.dispatchEvents(100); // hide dialog
          }
          if (currentManager != null) {
            currentManager.setDoubleBufferingEnabled(false);
          }
          a_printerJob.print();
        }
      }
    } catch (Exception ex) {
      application.reportError(
          application.getI18NMessage("servoy.print.error.cannotPrintDocument"), ex); // $NON-NLS-1$
    } finally {
      if (currentManager != null) {
        currentManager.setDoubleBufferingEnabled(isDoubleBufferingEnabled);
      }
    }
  }