예제 #1
0
 /**
  * Returns the receiver's image data. This is the icon that is associated with the receiver in the
  * operating system.
  *
  * @return the image data for the program, may be null
  */
 public ImageData getImageData() {
   NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init();
   try {
     NSWorkspace workspace = NSWorkspace.sharedWorkspace();
     NSString fullPath;
     if (this.fullPath != null) {
       fullPath = NSString.stringWith(this.fullPath);
     } else {
       fullPath = workspace.fullPathForApplication(NSString.stringWith(name));
     }
     if (fullPath != null) {
       NSImage nsImage = workspace.iconForFile(fullPath);
       if (nsImage != null) {
         NSSize size = new NSSize();
         size.width = size.height = 16;
         nsImage.setSize(size);
         nsImage.retain();
         Image image = Image.cocoa_new(Display.getCurrent(), SWT.BITMAP, nsImage);
         ImageData imageData = image.getImageData();
         image.dispose();
         return imageData;
       }
     }
     return null;
   } finally {
     pool.release();
   }
 }
 /** Frees the resources */
 void freeResources() {
   if (images != null) {
     for (Image image : images) {
       if (image != null) image.dispose();
     }
     images = null;
   }
 }
 public static void main(String[] args) {
   final Display display = new Display();
   final Shell shell = new Shell(display);
   shell.setLayout(new FillLayout());
   final StyledText styledText = new StyledText(shell, SWT.WRAP | SWT.BORDER);
   styledText.setText(text);
   FontData data = display.getSystemFont().getFontData()[0];
   Font font = new Font(display, data.getName(), 16, SWT.BOLD);
   styledText.setFont(font);
   styledText.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
   styledText.addListener(
       SWT.Resize,
       new Listener() {
         public void handleEvent(Event event) {
           Rectangle rect = styledText.getClientArea();
           Image newImage = new Image(display, 1, Math.max(1, rect.height));
           GC gc = new GC(newImage);
           gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
           gc.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
           gc.fillGradientRectangle(rect.x, rect.y, 1, rect.height, true);
           gc.dispose();
           styledText.setBackgroundImage(newImage);
           if (oldImage != null) oldImage.dispose();
           oldImage = newImage;
         }
       });
   shell.setSize(700, 400);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) display.sleep();
   }
   if (oldImage != null) oldImage.dispose();
   font.dispose();
   display.dispose();
 }
예제 #4
0
 /**
  * This implementation of <code>nativeToJava</code> converts a platform specific representation of
  * an image to java <code>ImageData</code>.
  *
  * @param transferData the platform specific representation of the data to be converted
  * @return a java <code>ImageData</code> of the image if the conversion was successful; otherwise
  *     null
  * @see Transfer#javaToNative
  */
 public Object nativeToJava(TransferData transferData) {
   ImageData imgData = null;
   if (transferData.length > 0) {
     long /*int*/ loader = OS.gdk_pixbuf_loader_new();
     try {
       OS.gdk_pixbuf_loader_write(loader, transferData.pValue, transferData.length, null);
       OS.gdk_pixbuf_loader_close(loader, null);
       long /*int*/ pixbuf = OS.gdk_pixbuf_loader_get_pixbuf(loader);
       if (pixbuf != 0) {
         Image img = Image.gtk_new_from_pixbuf(Display.getCurrent(), SWT.BITMAP, pixbuf);
         imgData = img.getImageData();
         img.dispose();
       }
     } finally {
       OS.g_object_unref(loader);
     }
   }
   return imgData;
 }
예제 #5
0
  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(2, false));

    final Text text = new Text(shell, SWT.SEARCH | SWT.ICON_CANCEL);
    Image image = null;
    if ((text.getStyle() & SWT.ICON_CANCEL) == 0) {
      image = display.getSystemImage(SWT.ICON_ERROR);
      ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
      ToolItem item = new ToolItem(toolBar, SWT.PUSH);
      item.setImage(image);
      item.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              text.setText("");
              System.out.println("Search cancelled");
            }
          });
    }
    text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    text.setText("Search text");
    text.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetDefaultSelected(SelectionEvent e) {
            if (e.detail == SWT.CANCEL) {
              System.out.println("Search cancelled");
            } else {
              System.out.println("Searching for: " + text.getText() + "...");
            }
          }
        });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) display.sleep();
    }
    if (image != null) image.dispose();
    display.dispose();
  }
예제 #6
0
  public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Widget");

    final Table table = new Table(shell, SWT.MULTI);
    table.setLinesVisible(true);
    table.setBounds(10, 10, 100, 100);
    for (int i = 0; i < 9; i++) {
      new TableItem(table, SWT.NONE).setText("item" + i);
    }

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Capture");
    button.pack();
    button.setLocation(10, 140);
    button.addListener(
        SWT.Selection,
        event -> {
          Point tableSize = table.getSize();
          GC gc = new GC(table);
          final Image image = new Image(display, tableSize.x, tableSize.y);
          gc.copyArea(image, 0, 0);
          gc.dispose();

          Shell popup = new Shell(shell);
          popup.setText("Image");
          popup.addListener(SWT.Close, e -> image.dispose());

          Canvas canvas = new Canvas(popup, SWT.NONE);
          canvas.setBounds(10, 10, tableSize.x + 10, tableSize.y + 10);
          canvas.addPaintListener(e -> e.gc.drawImage(image, 0, 0));
          popup.pack();
          popup.open();
        });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) display.sleep();
    }
    display.dispose();
  }
예제 #7
0
 public static void main(String[] args) {
   final Display display = new Display();
   final Image image = new Image(display, 16, 16);
   GC gc = new GC(image);
   gc.setBackground(display.getSystemColor(SWT.COLOR_RED));
   gc.fillRectangle(image.getBounds());
   gc.dispose();
   final Shell shell = new Shell(display);
   shell.setText("Lazy Table");
   shell.setLayout(new FillLayout());
   final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);
   table.setSize(200, 200);
   Thread thread =
       new Thread() {
         @Override
         public void run() {
           for (int i = 0; i < 20000; i++) {
             if (table.isDisposed()) return;
             final int[] index = new int[] {i};
             display.syncExec(
                 () -> {
                   if (table.isDisposed()) return;
                   TableItem item = new TableItem(table, SWT.NONE);
                   item.setText("Table Item " + index[0]);
                   item.setImage(image);
                 });
           }
         }
       };
   thread.start();
   shell.setSize(200, 200);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) display.sleep();
   }
   image.dispose();
   display.dispose();
 }
예제 #8
0
  /**
   * This implementation of <code>javaToNative</code> converts an ImageData object represented by
   * java <code>ImageData</code> to a platform specific representation.
   *
   * @param object a java <code>ImageData</code> containing the ImageData to be converted
   * @param transferData an empty <code>TransferData</code> object that will be filled in on return
   *     with the platform specific format of the data
   * @see Transfer#nativeToJava
   */
  public void javaToNative(Object object, TransferData transferData) {
    if (!checkImage(object) || !isSupportedType(transferData)) {
      DND.error(DND.ERROR_INVALID_DATA);
    }
    if (OS.GTK_VERSION < OS.VERSION(2, 4, 0)) return;

    ImageData imgData = (ImageData) object;
    if (imgData == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
    Image image = new Image(Display.getCurrent(), imgData);
    long /*int*/ pixbuf = ImageList.createPixbuf(image);
    if (pixbuf != 0) {
      String typeStr = "";
      if (transferData.type == JPEG_ID) typeStr = "jpeg";
      else if (transferData.type == PNG_ID) typeStr = "png";
      else if (transferData.type == BMP_ID) typeStr = "bmp";
      else if (transferData.type == EPS_ID) typeStr = "eps";
      else if (transferData.type == PCX_ID) typeStr = "pcx";
      else if (transferData.type == PPM_ID) typeStr = "ppm";
      else if (transferData.type == RGB_ID) typeStr = "rgb";
      else if (transferData.type == TGA_ID) typeStr = "tga";
      else if (transferData.type == XBM_ID) typeStr = "xbm";
      else if (transferData.type == XPM_ID) typeStr = "xpm";
      else if (transferData.type == XV_ID) typeStr = "xv";
      byte[] type = Converter.wcsToMbcs(null, typeStr, true);
      long /*int*/[] buffer = new long /*int*/[1];
      long /*int*/[] len = new long /*int*/[1];
      if (type == null) return;
      OS.gdk_pixbuf_save_to_bufferv(pixbuf, buffer, len, type, null, null, null);
      OS.g_object_unref(pixbuf);
      transferData.pValue = buffer[0];
      transferData.length = (int) (len[0] + 3) / 4 * 4;
      transferData.result = 1;
      transferData.format = 32;
    }
    image.dispose();
  }
예제 #9
0
  /** Compute the minimum size. */
  private Point getTotalSize(Image image, String text) {
    Point size = new Point(0, 0);

    if (image != null) {
      Rectangle r = image.getBounds();
      size.x += r.width;
      size.y += r.height;
    }

    GC gc = new GC(this);
    if (text != null && text.length() > 0) {
      Point e = gc.textExtent(text, DRAW_FLAGS);
      size.x += e.x;
      size.y = Math.max(size.y, e.y);
      if (image != null) size.x += GAP;
    } else {
      size.y = Math.max(size.y, gc.getFontMetrics().getHeight());
    }
    gc.dispose();

    return size;
  }
예제 #10
0
  public static void main(String[] args) {
    final Display display = new Display();
    final Image image = display.getSystemImage(SWT.ICON_INFORMATION);
    final Shell shell = new Shell(display, SWT.NO_TRIM);
    Region region = new Region();
    final ImageData imageData = image.getImageData();
    if (imageData.alphaData != null) {
      Rectangle pixel = new Rectangle(0, 0, 1, 1);
      for (int y = 0; y < imageData.height; y++) {
        for (int x = 0; x < imageData.width; x++) {
          if (imageData.getAlpha(x, y) == 255) {
            pixel.x = imageData.x + x;
            pixel.y = imageData.y + y;
            region.add(pixel);
          }
        }
      }
    } else {
      ImageData mask = imageData.getTransparencyMask();
      Rectangle pixel = new Rectangle(0, 0, 1, 1);
      for (int y = 0; y < mask.height; y++) {
        for (int x = 0; x < mask.width; x++) {
          if (mask.getPixel(x, y) != 0) {
            pixel.x = imageData.x + x;
            pixel.y = imageData.y + y;
            region.add(pixel);
          }
        }
      }
    }
    shell.setRegion(region);

    Listener l =
        new Listener() {
          /** The x/y of the MouseDown, relative to top-left of the shell. */
          int startX, startY;

          @Override
          public void handleEvent(Event e) {
            if (e.type == SWT.KeyDown && e.character == SWT.ESC) {
              shell.dispose();
            }
            if (e.type == SWT.MouseDown && e.button == 1) {
              Point p = shell.toDisplay(e.x, e.y);
              Point loc = shell.getLocation();
              startX = p.x - loc.x;
              startY = p.y - loc.y;
            }
            if (e.type == SWT.MouseMove && (e.stateMask & SWT.BUTTON1) != 0) {
              Point p = shell.toDisplay(e.x, e.y);
              p.x -= startX;
              p.y -= startY;
              shell.setLocation(p);
            }
            if (e.type == SWT.Paint) {
              e.gc.drawImage(image, imageData.x, imageData.y);
            }
          }
        };
    shell.addListener(SWT.KeyDown, l);
    shell.addListener(SWT.MouseDown, l);
    shell.addListener(SWT.MouseMove, l);
    shell.addListener(SWT.Paint, l);

    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) display.sleep();
    }
    region.dispose();
    image.dispose();
    display.dispose();
  }
예제 #11
0
 void paint(Event event) {
   if (row == null) return;
   int columnIndex = column == null ? 0 : table.indexOf(column);
   GC gc = event.gc;
   gc.setBackground(getBackground());
   gc.setForeground(getForeground());
   gc.fillRectangle(event.x, event.y, event.width, event.height);
   int x = 0;
   Point size = getSize();
   Image image = row.getImage(columnIndex);
   if (image != null) {
     Rectangle imageSize = image.getBounds();
     int imageY = (size.y - imageSize.height) / 2;
     gc.drawImage(image, x, imageY);
     x += imageSize.width;
   }
   String text = row.getText(columnIndex);
   if (text.length() > 0) {
     Rectangle bounds = row.getBounds(columnIndex);
     Point extent = gc.stringExtent(text);
     // Temporary code - need a better way to determine table trim
     String platform = SWT.getPlatform();
     if ("win32".equals(platform)) { // $NON-NLS-1$
       if (table.getColumnCount() == 0 || columnIndex == 0) {
         x += 2;
       } else {
         int alignmnent = column.getAlignment();
         switch (alignmnent) {
           case SWT.LEFT:
             x += 6;
             break;
           case SWT.RIGHT:
             x = bounds.width - extent.x - 6;
             break;
           case SWT.CENTER:
             x += (bounds.width - x - extent.x) / 2;
             break;
         }
       }
     } else {
       if (table.getColumnCount() == 0) {
         x += 5;
       } else {
         int alignmnent = column.getAlignment();
         switch (alignmnent) {
           case SWT.LEFT:
             x += 5;
             break;
           case SWT.RIGHT:
             x = bounds.width - extent.x - 2;
             break;
           case SWT.CENTER:
             x += (bounds.width - x - extent.x) / 2 + 2;
             break;
         }
       }
     }
     int textY = (size.y - extent.y) / 2;
     gc.drawString(text, x, textY);
   }
   if (isFocusControl()) {
     Display display = getDisplay();
     gc.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
     gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
     gc.drawFocus(0, 0, size.x, size.y);
   }
 }
예제 #12
0
  Image getDragSourceImage(DragSourceEvent event) {
    if (dragSourceImage != null) dragSourceImage.dispose();
    dragSourceImage = null;

    Table table = (Table) control;
    if (OS.GTK_VERSION < OS.VERSION(2, 2, 0)) return null;
    // TEMPORARY CODE
    if (table.isListening(SWT.EraseItem) || table.isListening(SWT.PaintItem)) return null;
    /*
     * Bug in GTK.  gtk_tree_selection_get_selected_rows() segmentation faults
     * in versions smaller than 2.2.4 if the model is NULL.  The fix is
     * to give a valid pointer instead.
     */
    long /*int*/ handle = table.handle;
    long /*int*/ selection = OS.gtk_tree_view_get_selection(handle);
    long /*int*/[] model = OS.GTK_VERSION < OS.VERSION(2, 2, 4) ? new long /*int*/[1] : null;
    long /*int*/ list = OS.gtk_tree_selection_get_selected_rows(selection, model);
    if (list == 0) return null;
    int count = Math.min(10, OS.g_list_length(list));

    Display display = table.getDisplay();
    if (count == 1) {
      long /*int*/ path = OS.g_list_nth_data(list, 0);
      long /*int*/ pixmap = OS.gtk_tree_view_create_row_drag_icon(handle, path);
      dragSourceImage = Image.gtk_new(display, SWT.ICON, pixmap, 0);
    } else {
      int width = 0, height = 0;
      int[] w = new int[1], h = new int[1];
      int[] yy = new int[count], hh = new int[count];
      long /*int*/[] pixmaps = new long /*int*/[count];
      GdkRectangle rect = new GdkRectangle();
      for (int i = 0; i < count; i++) {
        long /*int*/ path = OS.g_list_nth_data(list, i);
        OS.gtk_tree_view_get_cell_area(handle, path, 0, rect);
        pixmaps[i] = OS.gtk_tree_view_create_row_drag_icon(handle, path);
        OS.gdk_drawable_get_size(pixmaps[i], w, h);
        width = Math.max(width, w[0]);
        height = rect.y + h[0] - yy[0];
        yy[i] = rect.y;
        hh[i] = h[0];
      }
      long /*int*/ source = OS.gdk_pixmap_new(OS.GDK_ROOT_PARENT(), width, height, -1);
      long /*int*/ gcSource = OS.gdk_gc_new(source);
      long /*int*/ mask = OS.gdk_pixmap_new(OS.GDK_ROOT_PARENT(), width, height, 1);
      long /*int*/ gcMask = OS.gdk_gc_new(mask);
      GdkColor color = new GdkColor();
      color.pixel = 0;
      OS.gdk_gc_set_foreground(gcMask, color);
      OS.gdk_draw_rectangle(mask, gcMask, 1, 0, 0, width, height);
      color.pixel = 1;
      OS.gdk_gc_set_foreground(gcMask, color);
      for (int i = 0; i < count; i++) {
        OS.gdk_draw_drawable(source, gcSource, pixmaps[i], 0, 0, 0, yy[i] - yy[0], -1, -1);
        OS.gdk_draw_rectangle(mask, gcMask, 1, 0, yy[i] - yy[0], width, hh[i]);
        OS.g_object_unref(pixmaps[i]);
      }
      OS.g_object_unref(gcSource);
      OS.g_object_unref(gcMask);
      dragSourceImage = Image.gtk_new(display, SWT.ICON, source, mask);
    }
    OS.g_list_free(list);

    return dragSourceImage;
  }
예제 #13
0
 /**
  * This implementation of <code>dragFinished</code> disposes the image that was created in <code>
  * TableDragSourceEffect.dragStart</code>.
  *
  * <p>Subclasses that override this method should call <code>super.dragFinished(event)</code> to
  * dispose the image in the default implementation.
  *
  * @param event the information associated with the drag finished event
  */
 public void dragFinished(DragSourceEvent event) {
   if (dragSourceImage != null) dragSourceImage.dispose();
   dragSourceImage = null;
 }
  public static void main(String[] args) {
    Shell shell = new Shell();
    Display display = shell.getDisplay();
    shell.setLayout(new FillLayout());
    shell.setText("ExpandBar Example");

    Menu menubar = new Menu(shell, SWT.BAR);
    shell.setMenuBar(menubar);
    MenuItem fileItem = new MenuItem(menubar, SWT.CASCADE);
    fileItem.setText("&File");
    Menu submenu = new Menu(shell, SWT.DROP_DOWN);
    fileItem.setMenu(submenu);
    item = new MenuItem(submenu, SWT.PUSH);
    item.setText("New ExpandItem");

    bar = new ExpandBar(shell, SWT.V_SCROLL);
    image = display.getSystemImage(SWT.ICON_QUESTION);

    // First item
    Composite composite = new Composite(bar, SWT.NONE);
    Menu popupmenu = new Menu(shell, SWT.POP_UP);
    MenuItem popupItem = new MenuItem(popupmenu, SWT.PUSH);
    popupItem.setText("Popup");
    composite.setMenu(popupmenu);

    GridLayout layout = new GridLayout(2, false);
    layout.marginLeft = layout.marginTop = layout.marginRight = layout.marginBottom = 10;
    layout.verticalSpacing = 10;
    composite.setLayout(layout);
    Label label = new Label(composite, SWT.NONE);
    label.setImage(display.getSystemImage(SWT.ICON_ERROR));
    label = new Label(composite, SWT.NONE);
    label.setText("SWT.ICON_ERROR");
    label = new Label(composite, SWT.NONE);
    label.setImage(display.getSystemImage(SWT.ICON_INFORMATION));
    label = new Label(composite, SWT.NONE);
    label.setText("SWT.ICON_INFORMATION");
    label = new Label(composite, SWT.NONE);
    label.setImage(display.getSystemImage(SWT.ICON_WARNING));
    label = new Label(composite, SWT.NONE);
    label.setText("SWT.ICON_WARNING");
    label = new Label(composite, SWT.NONE);
    label.setImage(display.getSystemImage(SWT.ICON_QUESTION));
    label = new Label(composite, SWT.NONE);
    label.setText("SWT.ICON_QUESTION");
    ExpandItem item1 = new ExpandItem(bar, SWT.NONE);
    item1.setText("What is your favorite icon");
    item1.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
    item1.setControl(composite);
    item1.setImage(image);

    // Second item
    composite = new Composite(bar, SWT.NONE);
    layout = new GridLayout(2, true);
    layout.marginLeft = layout.marginTop = layout.marginRight = layout.marginBottom = 10;
    layout.verticalSpacing = 10;
    composite.setLayout(layout);
    Button button1 = new Button(composite, SWT.PUSH);
    button1.setText("Button 1");
    Button button2 = new Button(composite, SWT.PUSH);
    button2.setText("Button 2");

    ExpandItem item0 = new ExpandItem(bar, SWT.NONE);
    item0.setText("What is your favorite button");
    item0.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
    item0.setControl(composite);
    item0.setImage(image);
    item0.setExpanded(false);

    item.addListener(
        SWT.Selection,
        new Listener() {
          @Override
          public void handleEvent(Event e) {
            ExpandItem item2 = new ExpandItem(bar, SWT.NONE);
            Composite composite = new Composite(bar, SWT.NONE);
            GridLayout layout = new GridLayout(2, false);
            composite.setLayout(layout);
            Label label = new Label(composite, SWT.NONE);
            label.setText("What is your name?");
            Composite pcomposite = new Composite(composite, SWT.NONE);
            Text text = new Text(pcomposite, SWT.NONE);
            item2.setText("New Question");
            text.pack();
            composite.pack();
            Point size = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
            item2.setHeight(size.y);
            item2.setControl(composite);
            item2.setImage(image);
            item2.setExpanded(true);
          }
        });

    bar.setSpacing(8);
    shell.setSize(400, 550);
    shell.open();
    System.out.println("------------------------------");
    System.out.println("getSize: " + button1.getSize());
    System.out.println("getBounds: " + button1.getBounds());
    System.out.println("computeSize: " + button1.computeSize(SWT.DEFAULT, SWT.DEFAULT));
    System.out.println("getLocation: " + button1.getLocation());

    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    image.dispose();
    display.dispose();
  }
예제 #15
0
  void onPaint(PaintEvent event) {
    Rectangle rect = getClientArea();
    if (rect.width == 0 || rect.height == 0) return;

    boolean shortenText = false;
    String t = text;
    Image img = image;
    int availableWidth = Math.max(0, rect.width - (leftMargin + rightMargin));
    Point extent = getTotalSize(img, t);
    if (extent.x > availableWidth) {
      img = null;
      extent = getTotalSize(img, t);
      if (extent.x > availableWidth) {
        shortenText = true;
      }
    }

    GC gc = event.gc;
    String[] lines = text == null ? null : splitString(text);

    // shorten the text
    if (shortenText) {
      extent.x = 0;
      for (int i = 0; i < lines.length; i++) {
        Point e = gc.textExtent(lines[i], DRAW_FLAGS);
        if (e.x > availableWidth) {
          lines[i] = shortenText(gc, lines[i], availableWidth);
          extent.x = Math.max(extent.x, getTotalSize(null, lines[i]).x);
        } else {
          extent.x = Math.max(extent.x, e.x);
        }
      }
      if (appToolTipText == null) {
        super.setToolTipText(text);
      }
    } else {
      super.setToolTipText(appToolTipText);
    }

    // determine horizontal position
    int x = rect.x + leftMargin;
    if (align == SWT.CENTER) {
      x = (rect.width - extent.x) / 2;
    }
    if (align == SWT.RIGHT) {
      x = rect.width - rightMargin - extent.x;
    }

    // draw a background image behind the text
    try {
      if (backgroundImage != null) {
        // draw a background image behind the text
        Rectangle imageRect = backgroundImage.getBounds();
        // tile image to fill space
        gc.setBackground(getBackground());
        gc.fillRectangle(rect);
        int xPos = 0;
        while (xPos < rect.width) {
          int yPos = 0;
          while (yPos < rect.height) {
            gc.drawImage(backgroundImage, xPos, yPos);
            yPos += imageRect.height;
          }
          xPos += imageRect.width;
        }
      } else if (gradientColors != null) {
        // draw a gradient behind the text
        final Color oldBackground = gc.getBackground();
        if (gradientColors.length == 1) {
          if (gradientColors[0] != null) gc.setBackground(gradientColors[0]);
          gc.fillRectangle(0, 0, rect.width, rect.height);
        } else {
          final Color oldForeground = gc.getForeground();
          Color lastColor = gradientColors[0];
          if (lastColor == null) lastColor = oldBackground;
          int pos = 0;
          for (int i = 0; i < gradientPercents.length; ++i) {
            gc.setForeground(lastColor);
            lastColor = gradientColors[i + 1];
            if (lastColor == null) lastColor = oldBackground;
            gc.setBackground(lastColor);
            if (gradientVertical) {
              final int gradientHeight = (gradientPercents[i] * rect.height / 100) - pos;
              gc.fillGradientRectangle(0, pos, rect.width, gradientHeight, true);
              pos += gradientHeight;
            } else {
              final int gradientWidth = (gradientPercents[i] * rect.width / 100) - pos;
              gc.fillGradientRectangle(pos, 0, gradientWidth, rect.height, false);
              pos += gradientWidth;
            }
          }
          if (gradientVertical && pos < rect.height) {
            gc.setBackground(getBackground());
            gc.fillRectangle(0, pos, rect.width, rect.height - pos);
          }
          if (!gradientVertical && pos < rect.width) {
            gc.setBackground(getBackground());
            gc.fillRectangle(pos, 0, rect.width - pos, rect.height);
          }
          gc.setForeground(oldForeground);
        }
        gc.setBackground(oldBackground);
      } else {
        if (background != null || (getStyle() & SWT.DOUBLE_BUFFERED) == 0) {
          gc.setBackground(getBackground());
          gc.fillRectangle(rect);
        }
      }
    } catch (SWTException e) {
      if ((getStyle() & SWT.DOUBLE_BUFFERED) == 0) {
        gc.setBackground(getBackground());
        gc.fillRectangle(rect);
      }
    }

    // draw border
    int style = getStyle();
    if ((style & SWT.SHADOW_IN) != 0 || (style & SWT.SHADOW_OUT) != 0) {
      paintBorder(gc, rect);
    }

    /*
     * Compute text height and image height. If image height is more than
     * the text height, draw image starting from top margin. Else draw text
     * starting from top margin.
     */
    Rectangle imageRect = null;
    int lineHeight = 0, textHeight = 0, imageHeight = 0;

    if (img != null) {
      imageRect = img.getBounds();
      imageHeight = imageRect.height;
    }
    if (lines != null) {
      lineHeight = gc.getFontMetrics().getHeight();
      textHeight = lines.length * lineHeight;
    }

    int imageY = 0, midPoint = 0, lineY = 0;
    if (imageHeight > textHeight) {
      if (topMargin == DEFAULT_MARGIN && bottomMargin == DEFAULT_MARGIN)
        imageY = rect.y + (rect.height - imageHeight) / 2;
      else imageY = topMargin;
      midPoint = imageY + imageHeight / 2;
      lineY = midPoint - textHeight / 2;
    } else {
      if (topMargin == DEFAULT_MARGIN && bottomMargin == DEFAULT_MARGIN)
        lineY = rect.y + (rect.height - textHeight) / 2;
      else lineY = topMargin;
      midPoint = lineY + textHeight / 2;
      imageY = midPoint - imageHeight / 2;
    }

    // draw the image
    if (img != null) {
      gc.drawImage(
          img, 0, 0, imageRect.width, imageHeight, x, imageY, imageRect.width, imageHeight);
      x += imageRect.width + GAP;
      extent.x -= imageRect.width + GAP;
    }

    // draw the text
    if (lines != null) {
      gc.setForeground(getForeground());
      for (int i = 0; i < lines.length; i++) {
        int lineX = x;
        if (lines.length > 1) {
          if (align == SWT.CENTER) {
            int lineWidth = gc.textExtent(lines[i], DRAW_FLAGS).x;
            lineX = x + Math.max(0, (extent.x - lineWidth) / 2);
          }
          if (align == SWT.RIGHT) {
            int lineWidth = gc.textExtent(lines[i], DRAW_FLAGS).x;
            lineX = Math.max(x, rect.x + rect.width - rightMargin - lineWidth);
          }
        }
        gc.drawText(lines[i], lineX, lineY, DRAW_FLAGS);
        lineY += lineHeight;
      }
    }
  }
예제 #16
0
  private void drag(Event dragEvent) {
    DNDEvent event = new DNDEvent();
    event.widget = this;
    event.x = dragEvent.x;
    event.y = dragEvent.y;
    event.time = OS.GetMessageTime();
    event.doit = true;
    notifyListeners(DND.DragStart, event);
    if (!event.doit || transferAgents == null || transferAgents.length == 0) return;

    int[] pdwEffect = new int[1];
    int operations = opToOs(getStyle());
    Display display = control.getDisplay();
    String key = "org.eclipse.swt.internal.win32.runMessagesInIdle"; // $NON-NLS-1$
    Object oldValue = display.getData(key);
    display.setData(key, Boolean.TRUE);
    ImageList imagelist = null;
    Image image = event.image;
    hwndDrag = 0;
    topControl = null;
    if (image != null) {
      imagelist = new ImageList(SWT.NONE);
      imagelist.add(image);
      topControl = control.getShell();
      /*
       * Bug in Windows. The image is inverted if the shell is RIGHT_TO_LEFT.
       * The fix is to create a transparent window that covers the shell client
       * area and use it during the drag to prevent the image from being inverted.
       * On XP if the shell is RTL, the image is not displayed.
       */
      int offsetX = event.offsetX;
      hwndDrag = topControl.handle;
      if ((topControl.getStyle() & SWT.RIGHT_TO_LEFT) != 0) {
        offsetX = image.getBounds().width - offsetX;
        RECT rect = new RECT();
        OS.GetClientRect(topControl.handle, rect);
        hwndDrag =
            OS.CreateWindowEx(
                OS.WS_EX_TRANSPARENT | OS.WS_EX_NOINHERITLAYOUT,
                WindowClass,
                null,
                OS.WS_CHILD | OS.WS_CLIPSIBLINGS,
                0,
                0,
                rect.right - rect.left,
                rect.bottom - rect.top,
                topControl.handle,
                0,
                OS.GetModuleHandle(null),
                null);
        OS.ShowWindow(hwndDrag, OS.SW_SHOW);
      }
      OS.ImageList_BeginDrag(imagelist.getHandle(), 0, offsetX, event.offsetY);
      /*
       * Feature in Windows. When ImageList_DragEnter() is called,
       * it takes a snapshot of the screen  If a drag is started
       * when another window is in front, then the snapshot will
       * contain part of the other window, causing pixel corruption.
       * The fix is to force all paints to be delivered before
       * calling ImageList_DragEnter().
       */
      if (OS.IsWinCE) {
        OS.UpdateWindow(topControl.handle);
      } else {
        int flags = OS.RDW_UPDATENOW | OS.RDW_ALLCHILDREN;
        OS.RedrawWindow(topControl.handle, null, 0, flags);
      }
      POINT pt = new POINT();
      pt.x = dragEvent.x;
      pt.y = dragEvent.y;
      OS.MapWindowPoints(control.handle, 0, pt, 1);
      RECT rect = new RECT();
      OS.GetWindowRect(hwndDrag, rect);
      OS.ImageList_DragEnter(hwndDrag, pt.x - rect.left, pt.y - rect.top);
    }
    int result = COM.DRAGDROP_S_CANCEL;
    try {
      result =
          COM.DoDragDrop(iDataObject.getAddress(), iDropSource.getAddress(), operations, pdwEffect);
    } finally {
      // ensure that we don't leave transparent window around
      if (hwndDrag != 0) {
        OS.ImageList_DragLeave(hwndDrag);
        OS.ImageList_EndDrag();
        imagelist.dispose();
        if (hwndDrag != topControl.handle) OS.DestroyWindow(hwndDrag);
        hwndDrag = 0;
        topControl = null;
      }
      display.setData(key, oldValue);
    }
    int operation = osToOp(pdwEffect[0]);
    if (dataEffect == DND.DROP_MOVE) {
      operation =
          (operation == DND.DROP_NONE || operation == DND.DROP_COPY)
              ? DND.DROP_TARGET_MOVE
              : DND.DROP_MOVE;
    } else {
      if (dataEffect != DND.DROP_NONE) {
        operation = dataEffect;
      }
    }
    event = new DNDEvent();
    event.widget = this;
    event.time = OS.GetMessageTime();
    event.doit = (result == COM.DRAGDROP_S_DROP);
    event.detail = operation;
    notifyListeners(DND.DragEnd, event);
    dataEffect = DND.DROP_NONE;
  }
예제 #17
0
  public static void main(String[] args) {
    final Display display = new Display();
    final Clipboard clipboard = new Clipboard(display);
    final Shell shell = new Shell(display, SWT.SHELL_TRIM);
    shell.setLayout(new GridLayout());
    shell.setText("Clipboard ImageTransfer");

    final Button imageButton = new Button(shell, SWT.NONE);
    GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
    gd.minimumHeight = 400;
    gd.minimumWidth = 600;
    imageButton.setLayoutData(gd);

    final Text imageText = new Text(shell, SWT.BORDER);
    imageText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

    Composite buttons = new Composite(shell, SWT.NONE);
    buttons.setLayout(new GridLayout(4, true));
    Button button = new Button(buttons, SWT.PUSH);
    button.setText("Open");
    button.addListener(
        SWT.Selection,
        event -> {
          FileDialog dialog = new FileDialog(shell, SWT.OPEN);
          dialog.setText("Open an image file or cancel");
          String string = dialog.open();
          if (string != null) {
            imageButton.setText("");
            Image image = imageButton.getImage();
            if (image != null) image.dispose();
            image = new Image(display, string);
            imageButton.setImage(image);
            imageText.setText(string);
          }
        });

    button = new Button(buttons, SWT.PUSH);
    button.setText("Copy");
    button.addListener(
        SWT.Selection,
        event -> {
          Image image = imageButton.getImage();
          if (image != null) {
            ImageTransfer imageTransfer = ImageTransfer.getInstance();
            TextTransfer textTransfer = TextTransfer.getInstance();
            clipboard.setContents(
                new Object[] {image.getImageData(), imageText.getText()},
                new Transfer[] {imageTransfer, textTransfer});
          }
        });

    button = new Button(buttons, SWT.PUSH);
    button.setText("Paste");
    button.addListener(
        SWT.Selection,
        event -> {
          ImageData imageData = (ImageData) clipboard.getContents(ImageTransfer.getInstance());
          if (imageData != null) {
            imageButton.setText("");
            Image image = imageButton.getImage();
            if (image != null) image.dispose();
            image = new Image(display, imageData);
            imageButton.setImage(image);
          } else {
            imageButton.setText("No image");
            imageButton.setImage(null);
          }
          String text = (String) clipboard.getContents(TextTransfer.getInstance());
          if (text != null) {
            imageText.setText(text);
          } else {
            imageText.setText("");
          }
        });

    button = new Button(buttons, SWT.PUSH);
    button.setText("Clear");
    button.addListener(
        SWT.Selection,
        event -> {
          imageButton.setText("");
          Image image = imageButton.getImage();
          if (image != null) image.dispose();
          imageButton.setImage(null);
          imageText.setText("");
        });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) display.sleep();
    }
    display.dispose();
  }