@Override
  protected Control createContent(FormToolkit toolkit, Composite parent) {
    attributesComposite = toolkit.createComposite(parent);
    attributesComposite.addListener(
        SWT.MouseDown,
        new Listener() {
          public void handleEvent(Event event) {
            Control focus = event.display.getFocusControl();
            if (focus instanceof Text && ((Text) focus).getEditable() == false) {
              getManagedForm().getForm().setFocus();
            }
          }
        });

    GridLayout attributesLayout = EditorUtil.createSectionClientLayout();
    attributesLayout.numColumns = 4;
    attributesLayout.horizontalSpacing = 9;
    attributesLayout.verticalSpacing = 6;
    attributesComposite.setLayout(attributesLayout);

    GridData attributesData = new GridData(GridData.FILL_BOTH);
    attributesData.horizontalSpan = 1;
    attributesData.grabExcessVerticalSpace = false;
    attributesComposite.setLayoutData(attributesData);

    createAttributeControls(attributesComposite, toolkit, attributesLayout.numColumns);
    toolkit.paintBordersFor(attributesComposite);

    return attributesComposite;
  }
Ejemplo n.º 2
0
  /**
   * Creates a new ProxyControl as a child of the given parent. This is an invisible dummy control.
   * If given a target, the ProxyControl will update the bounds of the target to match the bounds of
   * the dummy control.
   *
   * @param parent parent composite
   */
  public ProxyControl(Composite parent) {
    // Create the invisible dummy composite
    control = new Composite(parent, SWT.NO_BACKGROUND);
    control.setVisible(false);

    // Attach a layout to the dummy composite. This is used to make the preferred
    // size of the dummy match the preferred size of the target.
    control.setLayout(
        new Layout() {
          protected void layout(Composite composite, boolean flushCache) {
            ProxyControl.this.layout();
            // does nothing. The bounds of the target are updated by the controlListener
          }

          protected Point computeSize(
              Composite composite, int wHint, int hHint, boolean flushCache) {
            if (target == null) {
              // Note: If we returned (0,0), SWT would ignore the result and use a default value.
              return new Point(1, 1);
            }

            return target.computeSize(wHint, hHint);
          }
        });

    // Attach listeners to the dummy
    control.addDisposeListener(disposeListener);
    control.addListener(SWT.Show, visibilityListener);
    control.addListener(SWT.Hide, visibilityListener);
  }
Ejemplo n.º 3
0
  /**
   * 添加窗口事件监听器
   *
   * @param winTitle
   * @param winToolbar
   * @param winStatusbar
   */
  private void addShellListener(Composite winTitle, Composite winToolbar, Composite winStatusbar) {
    Listener listener =
        new Listener() {
          int startX, startY;

          public void handleEvent(Event e) {
            if (e.type == SWT.MouseDown && e.button == 1) {
              startX = e.x;
              startY = e.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;

              if (p.x + startX < 0) return;
              if (p.y + startY < 0) return;
              int w = shell.getDisplay().getPrimaryMonitor().getBounds().width;
              int h = shell.getDisplay().getPrimaryMonitor().getBounds().height;
              if (p.x > w) return;
              if (p.y > h) return;

              shell.setLocation(p);
            }
          }
        };
    winTitle.addListener(SWT.MouseDown, listener);
    winTitle.addListener(SWT.MouseMove, listener);
    winToolbar.addListener(SWT.MouseDown, listener);
    winToolbar.addListener(SWT.MouseMove, listener);
    winStatusbar.addListener(SWT.MouseDown, listener);
    winStatusbar.addListener(SWT.MouseMove, listener);
    shell.addListener(
        SWT.KeyUp,
        new Listener() {

          @Override
          public void handleEvent(Event e) {
            if (e.keyCode == SWT.ESC) {
              shell.close();
              shell.dispose();
            }
          }
        });
  }
Ejemplo n.º 4
0
 @Override
 public void addListener(int eventType, Listener listener) {
   boolean wasListening = isListening(eventType);
   super.addListener(eventType, listener);
   boolean isListening = isListening(eventType);
   String remoteType = eventTypeToString(eventType);
   if (remoteType != null && !wasListening && isListening) {
     getRemoteObject().listen(remoteType, true);
   }
 }
Ejemplo n.º 5
0
 @Override
 public void addListener(int eventType, Listener listener) {
   // TODO evtl. erst ausführen, wenn alles wirklich geladen wurde, um
   // evtl. falsche Mauskoordinaten zu verhindern und so ein Fehlverhalten
   // im InformationControl vorzeugen
   if (EventDelegator.mustDelegate(eventType, this)) {
     this.browser.addListener(eventType, listener);
   } else {
     super.addListener(eventType, listener);
   }
 }
Ejemplo n.º 6
0
  private void initialize(Composite composite) {
    panel = new Composite(composite, SWT.NULL);
    panel.setLayout(new GridLayout(2, false));

    legend_panel_sc = new ScrolledComposite(panel, SWT.V_SCROLL);
    legend_panel_sc.setExpandHorizontal(true);
    legend_panel_sc.setExpandVertical(true);
    GridLayout layout = new GridLayout();
    layout.horizontalSpacing = 0;
    layout.verticalSpacing = 0;
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    legend_panel_sc.setLayout(layout);
    GridData gridData = new GridData(GridData.FILL_VERTICAL);
    legend_panel_sc.setLayoutData(gridData);

    legend_panel = new Group(legend_panel_sc, SWT.NULL);
    legend_panel.setText(MessageText.getString("label.tags"));

    legend_panel.setLayout(new GridLayout());

    legend_panel_sc.setContent(legend_panel);
    legend_panel_sc.addControlListener(
        new ControlAdapter() {
          public void controlResized(ControlEvent e) {
            legend_panel_sc.setMinSize(legend_panel.computeSize(SWT.DEFAULT, SWT.DEFAULT));
          }
        });

    speed_panel = new Composite(panel, SWT.NULL);
    speed_panel.setLayout(new GridLayout());
    gridData = new GridData(GridData.FILL_BOTH);
    speed_panel.setLayoutData(gridData);

    build();

    TagManager tm = TagManagerFactory.getTagManager();

    tm.addTagManagerListener(this, false);

    for (TagType tt : tm.getTagTypes()) {

      tt.addTagTypeListener(this, false);
    }

    panel.addListener(
        SWT.Activate,
        new Listener() {
          public void handleEvent(Event event) {
            refresh(true);
          }
        });
  }
  /**
   * This method generates the dependency graph and sets an {@link EditorPart} to show the graph's
   * window.
   */
  @Override
  public void createPartControl(final Composite parent) {
    initGeneratorAndHandler(parent);
    editorComposite = new Composite(parent, SWT.NO_BACKGROUND | SWT.EMBEDDED);
    window = SWT_AWT.new_Frame(editorComposite);
    windowSize = new Dimension(parent.getSize().x, parent.getSize().y);

    parent.addListener(
        SWT.Resize,
        new Listener() {
          @Override
          public void handleEvent(org.eclipse.swt.widgets.Event event) {
            Point tmpSize = parent.getSize();
            windowSize = new Dimension(tmpSize.x, tmpSize.y);
            if (handler != null) {
              handler.changeWindowSize(windowSize);
            }
            if (window != null && drawArea != null) {
              drawArea.setPreferredSize(windowSize);
              window.setPreferredSize(windowSize);
              window.repaint();
            }
          }
        });

    project = ((IFileEditorInput) getEditorInput()).getFile().getProject();
    setPartName(getPartName() + " - " + project.getName());

    // get a reference to the satellite viewer
    satView =
        (SatelliteView)
            PlatformUI.getWorkbench()
                .getActiveWorkbenchWindow()
                .getActivePage()
                .findView(SatelliteView.ID);
    if (satView != null) {
      satView.setEditor(this);
    } else {
      try {
        satView =
            (SatelliteView)
                PlatformUI.getWorkbench()
                    .getActiveWorkbenchWindow()
                    .getActivePage()
                    .showView(SatelliteView.ID);
        satView.setEditor(this);
      } catch (PartInitException e) {
        errorHandler.reportException("Error while opening the view", e);
      }
    }
    initWindow();
  }
  private void loadPhotos() {
    if (selectedPhotosFilesList == null) {
      selectedPhotosFilesList = new ArrayList<String>();
    } else {
      selectedPhotosFilesList.clear();
    }

    if (thumbnailWidgetList == null) {
      thumbnailWidgetList = new ArrayList<ThumbnailWidget>();
    } else {
      thumbnailWidgetList.clear();
    }

    ImagesGridView imagesGridView =
        (ImagesGridView)
            Activator.getView(
                PlatformUI.getWorkbench().getActiveWorkbenchWindow(), ImagesGridView.ID);
    Composite thumbnailGridComposite = imagesGridView.getThumbnailGridComposite();
    for (Control control : thumbnailGridComposite.getChildren()) {
      control.dispose();
    }
    int gridWidth = thumbnailGridComposite.getBounds().width;
    int numberOfColumns = gridWidth / 200 - 1;

    GridLayout thumbnailGridCompositeGL = new GridLayout(numberOfColumns, true);
    thumbnailGridComposite.setLayout(thumbnailGridCompositeGL);
    GridData thumbnailGridCompositeGD = new GridData(GridData.FILL_BOTH);
    thumbnailGridCompositeGD.horizontalSpan = 2;
    thumbnailGridComposite.setLayoutData(thumbnailGridCompositeGD);
    if (loadedPhotosList != null && loadedPhotosList.size() > 0) {
      // begin add photo composite, check and text fields
      for (ListIterator<String> selectedPhotosIterator = loadedPhotosList.listIterator();
          selectedPhotosIterator.hasNext(); ) {
        String selectedPhotoFilePath = selectedPhotosIterator.next();
        // check if the file has a valid imagesList
        final Image thumbnail;
        try {
          thumbnail = new Image(Display.getDefault(), selectedPhotoFilePath);
        } catch (SWTException ex) {
          selectedPhotosIterator.remove();
          continue;
        }
        Composite imageParentComposite = new Composite(thumbnailGridComposite, SWT.BORDER);
        GridLayout imageParentCompositeGridLayout = new GridLayout(2, false);
        imageParentComposite.setLayout(imageParentCompositeGridLayout);
        GridData imageParentCompositeGridData = new GridData();
        imageParentCompositeGridData.grabExcessHorizontalSpace = true;
        imageParentComposite.setLayoutData(imageParentCompositeGridData);

        final Composite imageComposite = new Composite(imageParentComposite, SWT.BORDER);
        GridData imageCompositeGridData = new GridData(175, 200);
        imageCompositeGridData.horizontalSpan = 2;
        imageComposite.setLayoutData(imageCompositeGridData);

        imageComposite.addMouseListener(
            new MouseListener() {
              @Override
              public void mouseUp(MouseEvent e) {}

              @Override
              public void mouseDown(MouseEvent e) {}

              @Override
              public void mouseDoubleClick(MouseEvent e) {
                String selectedPhotosFile =
                    ((ThumbnailWidget) imageComposite.getData()).getSelectedPhotoFilePath();
                Dialog dialog =
                    new OriginalSizeImageDialog(
                        Display.getDefault().getActiveShell(),
                        new Image[] {new Image(Display.getDefault(), selectedPhotosFile)});
                dialog.open();
              }
            });

        ResizeImageListener comp1Listener =
            new ResizeImageListener(thumbnail, imageComposite, true);
        imageComposite.addListener(SWT.Dispose, comp1Listener);
        imageComposite.addListener(SWT.Paint, comp1Listener);

        final Button checkBox = new Button(imageParentComposite, SWT.CHECK);
        Text imageDescriptionText = new Text(imageParentComposite, SWT.BORDER);
        GridData imageDescriptionTextGridData = new GridData(GridData.FILL_HORIZONTAL);
        imageDescriptionTextGridData.grabExcessHorizontalSpace = true;
        imageDescriptionText.setLayoutData(imageDescriptionTextGridData);

        ThumbnailWidget thumbnailWidget = new ThumbnailWidget();
        thumbnailWidget.setImageParentComposite(imageParentComposite);
        thumbnailWidget.setImageComposite(imageComposite);
        thumbnailWidget.setImageDescriptionText(imageDescriptionText);
        thumbnailWidget.setImage(thumbnail);
        thumbnailWidget.setCheckBox(checkBox);
        thumbnailWidget.setSelectedPhotoFilePath(selectedPhotoFilePath);

        checkBox.setData(thumbnailWidget);
        imageDescriptionText.setData(thumbnailWidget);
        imageComposite.setData(thumbnailWidget);

        thumbnailWidgetList.add(thumbnailWidget);

        checkBox.addSelectionListener(
            new SelectionListener() {
              @Override
              public void widgetSelected(SelectionEvent e) {
                String selectedPhotosFile =
                    ((ThumbnailWidget) checkBox.getData()).getSelectedPhotoFilePath();
                if (checkBox.getSelection()) {
                  selectedPhotosFilesList.add(selectedPhotosFile);
                } else {
                  selectedPhotosFilesList.remove(selectedPhotosFile);
                }
              }

              @Override
              public void widgetDefaultSelected(SelectionEvent e) {}
            });
      }
      // end add photo composite, check and text fields
      ScrolledComposite thumbnailGridScrolledComposite =
          imagesGridView.getViewerScrolledComposite();

      Point size = thumbnailGridComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
      thumbnailGridScrolledComposite.setMinSize(size);

      thumbnailGridScrolledComposite.setContent(thumbnailGridComposite);
      thumbnailGridScrolledComposite.layout(true);
    }
    // show image grid view
    try {
      PlatformUI.getWorkbench()
          .getActiveWorkbenchWindow()
          .getActivePage()
          .showView(ImagesGridView.ID);
    } catch (PartInitException e1) {
      e1.printStackTrace();
    }
  }
Ejemplo n.º 9
0
  /**
   * Creates a new <code>java.awt.Frame</code>. This frame is the root for the AWT components that
   * will be embedded within the composite. In order for the embedding to succeed, the composite
   * must have been created with the SWT.EMBEDDED style.
   *
   * <p>IMPORTANT: As of JDK1.5, the embedded frame does not receive mouse events. When a
   * lightweight component is added as a child of the embedded frame, the cursor does not change. In
   * order to work around both these problems, it is strongly recommended that a heavyweight
   * component such as <code>java.awt.Panel</code> be added to the frame as the root of all
   * components.
   *
   * @param parent the parent <code>Composite</code> of the new <code>java.awt.Frame</code>
   * @return a <code>java.awt.Frame</code> to be the parent of the embedded AWT components
   * @exception IllegalArgumentException
   *     <ul>
   *       <li>ERROR_NULL_ARGUMENT - if the parent is null
   *       <li>ERROR_INVALID_ARGUMENT - if the parent Composite does not have the SWT.EMBEDDED style
   *     </ul>
   *
   * @since 3.0
   */
  public static Frame new_Frame(final Composite parent) {
    if (parent == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
    if ((parent.getStyle() & SWT.EMBEDDED) == 0) {
      SWT.error(SWT.ERROR_INVALID_ARGUMENT);
    }

    final int /*long*/ handle = parent.view.id;

    Class clazz = null;
    try {
      String className =
          embeddedFrameClass != null ? embeddedFrameClass : "apple.awt.CEmbeddedFrame";
      if (embeddedFrameClass == null) {
        clazz = Class.forName(className, true, ClassLoader.getSystemClassLoader());
      } else {
        clazz = Class.forName(className);
      }
    } catch (ClassNotFoundException cne) {
      SWT.error(SWT.ERROR_NOT_IMPLEMENTED, cne);
    } catch (Throwable e) {
      SWT.error(SWT.ERROR_UNSPECIFIED, e, " [Error while starting AWT]");
    }

    initializeSwing();
    Object value = null;
    Constructor constructor = null;
    try {
      constructor = clazz.getConstructor(new Class[] {long.class});
      value = constructor.newInstance(new Object[] {new Long(handle)});
    } catch (Throwable e) {
      SWT.error(SWT.ERROR_NOT_IMPLEMENTED, e);
    }
    final Frame frame = (Frame) value;
    frame.addNotify();

    parent.setData(EMBEDDED_FRAME_KEY, frame);

    /* Forward the iconify and deiconify events */
    final Listener shellListener =
        new Listener() {
          public void handleEvent(Event e) {
            switch (e.type) {
              case SWT.Deiconify:
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_DEICONIFIED));
                      }
                    });
                break;
              case SWT.Iconify:
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_ICONIFIED));
                      }
                    });
                break;
            }
          }
        };
    Shell shell = parent.getShell();
    shell.addListener(SWT.Deiconify, shellListener);
    shell.addListener(SWT.Iconify, shellListener);

    /*
     * Generate the appropriate events to activate and deactivate
     * the embedded frame. This is needed in order to make keyboard
     * focus work properly for lightweights.
     */
    Listener listener =
        new Listener() {
          public void handleEvent(Event e) {
            switch (e.type) {
              case SWT.Dispose:
                Shell shell = parent.getShell();
                shell.removeListener(SWT.Deiconify, shellListener);
                shell.removeListener(SWT.Iconify, shellListener);
                parent.setVisible(false);
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        try {
                          frame.dispose();
                        } catch (Throwable e) {
                        }
                      }
                    });
                break;
              case SWT.FocusIn:
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        if (frame.isActive()) return;
                        try {
                          Class clazz = frame.getClass();
                          Method method =
                              clazz.getMethod(
                                  "synthesizeWindowActivation", new Class[] {boolean.class});
                          if (method != null)
                            method.invoke(frame, new Object[] {new Boolean(true)});
                        } catch (Throwable e) {
                          e.printStackTrace();
                        }
                      }
                    });
                break;
              case SWT.Deactivate:
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        if (!frame.isActive()) return;
                        try {
                          Class clazz = frame.getClass();
                          Method method =
                              clazz.getMethod(
                                  "synthesizeWindowActivation", new Class[] {boolean.class});
                          if (method != null)
                            method.invoke(frame, new Object[] {new Boolean(false)});
                        } catch (Throwable e) {
                          e.printStackTrace();
                        }
                      }
                    });
                break;
            }
          }
        };

    parent.addListener(SWT.FocusIn, listener);
    parent.addListener(SWT.Deactivate, listener);
    parent.addListener(SWT.Dispose, listener);

    parent
        .getDisplay()
        .asyncExec(
            new Runnable() {
              public void run() {
                if (parent.isDisposed()) return;
                final Rectangle clientArea = parent.getClientArea();
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        frame.setSize(clientArea.width, clientArea.height);
                        frame.validate();

                        // Bug in Cocoa AWT? For some reason the frame isn't showing up on first
                        // draw.
                        // Toggling visibility seems to be the only thing that works.
                        frame.setVisible(false);
                        frame.setVisible(true);
                      }
                    });
              }
            });

    return frame;
  }
  private void createLanguagesGroup(Composite parent) {
    final Group langGroup =
        NSISWizardDialogUtil.createGroup(
            parent, 1, "language.support.group.label", null, false); // $NON-NLS-1$
    GridData data = (GridData) langGroup.getLayoutData();
    data.verticalAlignment = SWT.FILL;
    data.grabExcessVerticalSpace = true;
    data.horizontalAlignment = SWT.FILL;
    data.grabExcessHorizontalSpace = true;

    NSISWizardSettings settings = mWizard.getSettings();

    final Button enableLangSupport =
        NSISWizardDialogUtil.createCheckBox(
            langGroup,
            "enable.language.support.label",
            settings.isEnableLanguageSupport(),
            true,
            null,
            false); //$NON-NLS-1$
    enableLangSupport.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            boolean selection = enableLangSupport.getSelection();
            mWizard.getSettings().setEnableLanguageSupport(selection);
            validateField(LANG_CHECK);
          }
        });

    final MasterSlaveController m = new MasterSlaveController(enableLangSupport);

    final Composite listsComposite = new Composite(langGroup, SWT.NONE);
    data = new GridData(SWT.FILL, SWT.FILL, true, true);
    listsComposite.setLayoutData(data);

    GridLayout layout = new GridLayout(2, true);
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    listsComposite.setLayout(layout);

    java.util.List<NSISLanguage> selectedLanguages = settings.getLanguages();
    if (selectedLanguages.isEmpty()) {
      NSISLanguage defaultLanguage = NSISLanguageManager.getInstance().getDefaultLanguage();
      if (defaultLanguage != null) {
        selectedLanguages.add(defaultLanguage);
      }
    }
    java.util.List<NSISLanguage> availableLanguages =
        NSISLanguageManager.getInstance().getLanguages();
    availableLanguages.removeAll(selectedLanguages);

    Composite leftComposite = new Composite(listsComposite, SWT.NONE);
    leftComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    layout = new GridLayout(2, false);
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    leftComposite.setLayout(layout);

    ((GridData)
                NSISWizardDialogUtil.createLabel(
                        leftComposite,
                        "available.languages.label", //$NON-NLS-1$
                        true,
                        m,
                        false)
                    .getLayoutData())
            .horizontalSpan =
        2;

    final List availableLangList =
        new List(leftComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
    data = new GridData(SWT.FILL, SWT.FILL, true, true);
    Dialog.applyDialogFont(availableLangList);
    data.heightHint = Common.calculateControlSize(availableLangList, 0, 12).y;
    availableLangList.setLayoutData(data);
    m.addSlave(availableLangList);

    final ListViewer availableLangViewer = new ListViewer(availableLangList);
    CollectionContentProvider collectionContentProvider = new CollectionContentProvider();
    availableLangViewer.setContentProvider(collectionContentProvider);
    availableLangViewer.setInput(availableLanguages);
    availableLangViewer.setSorter(new ViewerSorter(cLanguageCollator));

    final Composite buttonsComposite1 = new Composite(leftComposite, SWT.NONE);
    layout = new GridLayout(1, false);
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    buttonsComposite1.setLayout(layout);
    data = new GridData(SWT.FILL, SWT.CENTER, false, false);
    buttonsComposite1.setLayoutData(data);

    final Button allRightButton = new Button(buttonsComposite1, SWT.PUSH);
    data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    allRightButton.setLayoutData(data);
    allRightButton.setImage(
        EclipseNSISPlugin.getImageManager()
            .getImage(EclipseNSISPlugin.getResourceString("all.right.icon"))); // $NON-NLS-1$
    allRightButton.setToolTipText(
        EclipseNSISPlugin.getResourceString("all.right.tooltip")); // $NON-NLS-1$

    final Button rightButton = new Button(buttonsComposite1, SWT.PUSH);
    data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    rightButton.setLayoutData(data);
    rightButton.setImage(
        EclipseNSISPlugin.getImageManager()
            .getImage(EclipseNSISPlugin.getResourceString("right.icon"))); // $NON-NLS-1$
    rightButton.setToolTipText(EclipseNSISPlugin.getResourceString("right.tooltip")); // $NON-NLS-1$

    final Button leftButton = new Button(buttonsComposite1, SWT.PUSH);
    data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    leftButton.setLayoutData(data);
    leftButton.setImage(
        EclipseNSISPlugin.getImageManager()
            .getImage(EclipseNSISPlugin.getResourceString("left.icon"))); // $NON-NLS-1$
    leftButton.setToolTipText(EclipseNSISPlugin.getResourceString("left.tooltip")); // $NON-NLS-1$

    final Button allLeftButton = new Button(buttonsComposite1, SWT.PUSH);
    data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    allLeftButton.setLayoutData(data);
    allLeftButton.setImage(
        EclipseNSISPlugin.getImageManager()
            .getImage(EclipseNSISPlugin.getResourceString("all.left.icon"))); // $NON-NLS-1$
    allLeftButton.setToolTipText(
        EclipseNSISPlugin.getResourceString("all.left.tooltip")); // $NON-NLS-1$

    Composite rightComposite = new Composite(listsComposite, SWT.NONE);
    rightComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    layout = new GridLayout(2, false);
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    rightComposite.setLayout(layout);

    ((GridData)
                NSISWizardDialogUtil.createLabel(
                        rightComposite,
                        "selected.languages.label", //$NON-NLS-1$
                        true,
                        m,
                        isScriptWizard())
                    .getLayoutData())
            .horizontalSpan =
        2;

    final List selectedLangList =
        new List(rightComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
    data = new GridData(SWT.FILL, SWT.FILL, true, true);
    Dialog.applyDialogFont(selectedLangList);
    data.heightHint = Common.calculateControlSize(selectedLangList, 0, 12).y;
    selectedLangList.setLayoutData(data);
    m.addSlave(selectedLangList);

    final ListViewer selectedLangViewer = new ListViewer(selectedLangList);
    selectedLangViewer.setContentProvider(collectionContentProvider);
    selectedLangViewer.setInput(selectedLanguages);

    final ListViewerUpDownMover<java.util.List<NSISLanguage>, NSISLanguage> mover =
        new ListViewerUpDownMover<java.util.List<NSISLanguage>, NSISLanguage>() {
          @Override
          @SuppressWarnings("unchecked")
          protected java.util.List<NSISLanguage> getAllElements() {
            return (java.util.List<NSISLanguage>) ((ListViewer) getViewer()).getInput();
          }

          @Override
          protected void updateStructuredViewerInput(
              java.util.List<NSISLanguage> input,
              java.util.List<NSISLanguage> elements,
              java.util.List<NSISLanguage> move,
              boolean isDown) {
            (input).clear();
            (input).addAll(elements);
          }
        };

    mover.setViewer(selectedLangViewer);

    final Composite buttonsComposite2 = new Composite(rightComposite, SWT.NONE);
    layout = new GridLayout(1, false);
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    buttonsComposite2.setLayout(layout);
    data = new GridData(SWT.FILL, SWT.CENTER, false, false);
    buttonsComposite2.setLayoutData(data);

    final Button upButton = new Button(buttonsComposite2, SWT.PUSH);
    data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    upButton.setLayoutData(data);
    upButton.setImage(
        EclipseNSISPlugin.getImageManager()
            .getImage(EclipseNSISPlugin.getResourceString("up.icon"))); // $NON-NLS-1$
    upButton.setToolTipText(EclipseNSISPlugin.getResourceString("up.tooltip")); // $NON-NLS-1$
    m.addSlave(upButton);

    final Button downButton = new Button(buttonsComposite2, SWT.PUSH);
    data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    downButton.setLayoutData(data);
    downButton.setImage(
        EclipseNSISPlugin.getImageManager()
            .getImage(EclipseNSISPlugin.getResourceString("down.icon"))); // $NON-NLS-1$
    downButton.setToolTipText(EclipseNSISPlugin.getResourceString("down.tooltip")); // $NON-NLS-1$
    m.addSlave(downButton);

    Composite langOptions = langGroup;
    boolean showSupportedLangOption =
        NSISPreferences.getInstance().getNSISVersion().compareTo(INSISVersions.VERSION_2_26) >= 0;
    if (showSupportedLangOption) {
      langOptions = new Composite(langGroup, SWT.None);
      layout = new GridLayout(2, false);
      layout.marginHeight = 0;
      layout.marginWidth = 0;
      langOptions.setLayout(layout);
      data = new GridData(SWT.FILL, SWT.FILL, true, false);
      langOptions.setLayoutData(data);
    }

    final Button selectLang =
        NSISWizardDialogUtil.createCheckBox(
            langOptions,
            "select.language.label",
            settings.isSelectLanguage(),
            true,
            m,
            false); //$NON-NLS-1$

    final Button displaySupported;
    if (showSupportedLangOption) {
      ((GridData) selectLang.getLayoutData()).horizontalSpan = 1;
      displaySupported =
          NSISWizardDialogUtil.createCheckBox(
              langOptions,
              "display.supported.languages.label",
              settings.isDisplaySupportedLanguages(), // $NON-NLS-1$
              true,
              m,
              false);
      ((GridData) displaySupported.getLayoutData()).horizontalSpan = 1;
      displaySupported.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              mWizard.getSettings().setDisplaySupportedLanguages(displaySupported.getSelection());
            }
          });
    } else {
      displaySupported = null;
    }

    final MasterSlaveEnabler mse =
        new MasterSlaveEnabler() {
          public void enabled(Control control, boolean flag) {}

          @SuppressWarnings("unchecked")
          public boolean canEnable(Control control) {
            NSISWizardSettings settings = mWizard.getSettings();

            if (control == allRightButton) {
              return settings.isEnableLanguageSupport()
                  && availableLangViewer.getList().getItemCount() > 0;
            } else if (control == rightButton) {
              return settings.isEnableLanguageSupport()
                  && !availableLangViewer.getSelection().isEmpty();
            } else if (control == allLeftButton) {
              return settings.isEnableLanguageSupport()
                  && selectedLangViewer.getList().getItemCount() > 0;
            } else if (control == leftButton) {
              return settings.isEnableLanguageSupport()
                  && !selectedLangViewer.getSelection().isEmpty();
            } else if (control == upButton) {
              return settings.isEnableLanguageSupport() && mover.canMoveUp();
            } else if (control == downButton) {
              return settings.isEnableLanguageSupport() && mover.canMoveDown();
            } else if (control == selectLang) {
              java.util.List<NSISLanguage> selectedLanguages =
                  (java.util.List<NSISLanguage>) selectedLangViewer.getInput();
              return settings.getInstallerType() != INSTALLER_TYPE_SILENT
                  && settings.isEnableLanguageSupport()
                  && selectedLanguages.size() > 1;
            } else if (control == displaySupported && displaySupported != null) {
              java.util.List<NSISLanguage> selectedLanguages =
                  (java.util.List<NSISLanguage>) selectedLangViewer.getInput();
              return settings.getInstallerType() != INSTALLER_TYPE_SILENT
                  && settings.isEnableLanguageSupport()
                  && selectedLanguages.size() > 1
                  && selectLang.getSelection();
            } else {
              return true;
            }
          }
        };
    m.addSlave(rightButton, mse);
    m.addSlave(allRightButton, mse);
    m.addSlave(leftButton, mse);
    m.addSlave(allLeftButton, mse);
    m.setEnabler(upButton, mse);
    m.setEnabler(downButton, mse);
    m.setEnabler(selectLang, mse);
    if (displaySupported != null) {
      m.setEnabler(displaySupported, mse);
    }

    selectLang.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            mWizard.getSettings().setSelectLanguage(selectLang.getSelection());
            if (displaySupported != null) {
              displaySupported.setEnabled(mse.canEnable(displaySupported));
            }
          }
        });

    final Runnable langRunnable =
        new Runnable() {
          public void run() {
            availableLangViewer.refresh(false);
            selectedLangViewer.refresh(false);
            allRightButton.setEnabled(mse.canEnable(allRightButton));
            allLeftButton.setEnabled(mse.canEnable(allLeftButton));
            rightButton.setEnabled(mse.canEnable(rightButton));
            leftButton.setEnabled(mse.canEnable(leftButton));
            upButton.setEnabled(mse.canEnable(upButton));
            downButton.setEnabled(mse.canEnable(downButton));
            selectLang.setEnabled(mse.canEnable(selectLang));
            if (displaySupported != null) {
              displaySupported.setEnabled(mse.canEnable(displaySupported));
            }
            setPageComplete(validateField(LANG_CHECK));
          }
        };

    rightButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent se) {
            moveAcross(
                availableLangViewer,
                selectedLangViewer,
                Common.makeGenericList(
                    NSISLanguage.class,
                    ((IStructuredSelection) availableLangViewer.getSelection()).toList()));
            langRunnable.run();
          }
        });
    allRightButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          @SuppressWarnings("unchecked")
          public void widgetSelected(SelectionEvent se) {
            moveAcross(
                availableLangViewer,
                selectedLangViewer,
                (java.util.List<NSISLanguage>) availableLangViewer.getInput());
            langRunnable.run();
          }
        });
    leftButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent se) {
            moveAcross(
                selectedLangViewer,
                availableLangViewer,
                Common.makeGenericList(
                    NSISLanguage.class,
                    ((IStructuredSelection) selectedLangViewer.getSelection()).toList()));
            langRunnable.run();
          }
        });
    allLeftButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          @SuppressWarnings("unchecked")
          public void widgetSelected(SelectionEvent se) {
            moveAcross(
                selectedLangViewer,
                availableLangViewer,
                (java.util.List<NSISLanguage>) selectedLangViewer.getInput());
            langRunnable.run();
          }
        });
    upButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent se) {
            mover.moveUp();
            langRunnable.run();
          }
        });
    downButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent se) {
            mover.moveDown();
            langRunnable.run();
          }
        });

    availableLangViewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          public void selectionChanged(SelectionChangedEvent event) {
            rightButton.setEnabled(mse.canEnable(rightButton));
            allRightButton.setEnabled(mse.canEnable(allRightButton));
          }
        });
    availableLangViewer
        .getList()
        .addSelectionListener(
            new SelectionAdapter() {
              @Override
              public void widgetDefaultSelected(SelectionEvent event) {
                IStructuredSelection sel =
                    (IStructuredSelection) availableLangViewer.getSelection();
                if (!sel.isEmpty()) {
                  moveAcross(
                      availableLangViewer,
                      selectedLangViewer,
                      Common.makeGenericList(NSISLanguage.class, sel.toList()));
                  selectedLangViewer.reveal(sel.getFirstElement());
                  langRunnable.run();
                }
              }
            });
    selectedLangViewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          public void selectionChanged(SelectionChangedEvent event) {
            leftButton.setEnabled(mse.canEnable(leftButton));
            allLeftButton.setEnabled(mse.canEnable(allLeftButton));
            upButton.setEnabled(mse.canEnable(upButton));
            downButton.setEnabled(mse.canEnable(downButton));
            selectLang.setEnabled(mse.canEnable(selectLang));
            if (displaySupported != null) {
              displaySupported.setEnabled(mse.canEnable(displaySupported));
            }
          }
        });
    selectedLangViewer
        .getList()
        .addSelectionListener(
            new SelectionAdapter() {
              @Override
              public void widgetDefaultSelected(SelectionEvent event) {
                IStructuredSelection sel = (IStructuredSelection) selectedLangViewer.getSelection();
                if (!sel.isEmpty()) {
                  moveAcross(
                      selectedLangViewer,
                      availableLangViewer,
                      Common.makeGenericList(NSISLanguage.class, sel.toList()));
                  availableLangViewer.reveal(sel.getFirstElement());
                  langRunnable.run();
                }
              }
            });

    m.updateSlaves();

    listsComposite.addListener(
        SWT.Resize,
        new Listener() {
          boolean init = false;

          public void handleEvent(Event e) {
            if (!init) {
              // Stupid hack so that the height hint doesn't get changed
              // on the first resize,
              // i.e., when the page is drawn for the first time.
              init = true;
            } else {
              Point size = listsComposite.getSize();
              GridLayout layout = (GridLayout) listsComposite.getLayout();
              int heightHint = size.y - 2 * layout.marginHeight;
              ((GridData) availableLangList.getLayoutData()).heightHint = heightHint;
              ((GridData) selectedLangList.getLayoutData()).heightHint = heightHint;
              int totalWidth = size.x - 2 * layout.marginWidth - 3 * layout.horizontalSpacing;
              int listWidth = (int) (totalWidth * 0.4);
              int buttonWidth = (int) (0.5 * (totalWidth - 2 * listWidth));
              size = availableLangList.computeSize(listWidth, SWT.DEFAULT);
              int delta = 0;
              if (size.x > listWidth) {
                delta = size.x - listWidth;
                listWidth = listWidth - delta;
              }
              ((GridData) availableLangList.getLayoutData()).widthHint = listWidth;
              ((GridData) buttonsComposite1.getLayoutData()).widthHint =
                  totalWidth - 2 * (listWidth + delta) - buttonWidth;
              ((GridData) selectedLangList.getLayoutData()).widthHint = listWidth;
              ((GridData) buttonsComposite2.getLayoutData()).widthHint = buttonWidth;
              listsComposite.layout();
            }
          }
        });

    addPageChangedRunnable(
        new Runnable() {
          public void run() {
            if (isCurrentPage()) {
              selectLang.setEnabled(mse.canEnable(selectLang));
              if (displaySupported != null) {
                displaySupported.setEnabled(mse.canEnable(displaySupported));
              }
            }
          }
        });

    mWizard.addSettingsListener(
        new INSISWizardSettingsListener() {
          public void settingsChanged(
              NSISWizardSettings oldSettings, NSISWizardSettings newSettings) {
            enableLangSupport.setSelection(newSettings.isEnableLanguageSupport());
            m.updateSlaves();
            selectLang.setSelection(newSettings.isSelectLanguage());
            if (displaySupported != null) {
              displaySupported.setSelection(newSettings.isDisplaySupportedLanguages());
            }
            java.util.List<NSISLanguage> selectedLanguages = newSettings.getLanguages();
            java.util.List<NSISLanguage> availableLanguages =
                NSISLanguageManager.getInstance().getLanguages();
            if (selectedLanguages.isEmpty()) {
              NSISWizardWelcomePage welcomePage =
                  (NSISWizardWelcomePage) mWizard.getPage(NSISWizardWelcomePage.NAME);
              if (welcomePage != null) {
                if (!welcomePage.isCreateFromTemplate()) {
                  NSISLanguage defaultLanguage =
                      NSISLanguageManager.getInstance().getDefaultLanguage();
                  if (defaultLanguage != null && availableLanguages.contains(defaultLanguage)) {
                    selectedLanguages.add(defaultLanguage);
                  }
                }
              }
            }
            selectedLangViewer.setInput(selectedLanguages);
            availableLanguages.removeAll(selectedLanguages);
            availableLangViewer.setInput(availableLanguages);
          }
        });
  }
Ejemplo n.º 11
0
 /**
  * Adds a {@link Listener} for the defined eventType. The listener will be notified when the event
  * occurs anywhere on the {@link Composite}. It doesn't matter if the {@link Composite} holds
  * controls or not.
  *
  * @since 0.10
  */
 public void addGroupedListener(int eventType, Listener listener)
     throws IllegalArgumentException, IllegalStateException {
   whenNull(listener).throwIllegalArgument("Listener must not be null");
   Composite facade = getFacade();
   facade.addListener(eventType, listener);
 }
Ejemplo n.º 12
0
  public Composite createSashForm(final Composite composite) {
    if (!tv.isTabViewsEnabled()) {
      tableComposite = tv.createMainPanel(composite);
      return tableComposite;
    }

    ConfigurationManager configMan = ConfigurationManager.getInstance();

    int iNumViews = 0;

    UIFunctionsSWT uiFunctions = UIFunctionsManagerSWT.getUIFunctionsSWT();
    UISWTViewEventListenerWrapper[] pluginViews = null;
    if (uiFunctions != null) {
      UISWTInstance pluginUI = uiFunctions.getUISWTInstance();

      if (pluginUI != null) {
        pluginViews = pluginUI.getViewListeners(tv.getTableID());
        iNumViews += pluginViews.length;
      }
    }

    if (iNumViews == 0) {
      tableComposite = tv.createMainPanel(composite);
      return tableComposite;
    }

    FormData formData;

    final Composite form = new Composite(composite, SWT.NONE);
    FormLayout flayout = new FormLayout();
    flayout.marginHeight = 0;
    flayout.marginWidth = 0;
    form.setLayout(flayout);
    GridData gridData;
    gridData = new GridData(GridData.FILL_BOTH);
    form.setLayoutData(gridData);

    // Create them in reverse order, so we can have the table auto-grow, and
    // set the tabFolder's height manually

    final int TABHEIGHT = 20;
    tabFolder = new CTabFolder(form, SWT.TOP | SWT.BORDER);
    tabFolder.setMinimizeVisible(true);
    tabFolder.setTabHeight(TABHEIGHT);
    final int iFolderHeightAdj = tabFolder.computeSize(SWT.DEFAULT, 0).y;

    final Sash sash = new Sash(form, SWT.HORIZONTAL);

    tableComposite = tv.createMainPanel(form);
    Composite cFixLayout = tableComposite;
    while (cFixLayout != null && cFixLayout.getParent() != form) {
      cFixLayout = cFixLayout.getParent();
    }
    if (cFixLayout == null) {
      cFixLayout = tableComposite;
    }
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;
    layout.horizontalSpacing = 0;
    layout.verticalSpacing = 0;
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    cFixLayout.setLayout(layout);

    // FormData for Folder
    formData = new FormData();
    formData.left = new FormAttachment(0, 0);
    formData.right = new FormAttachment(100, 0);
    formData.bottom = new FormAttachment(100, 0);
    int iSplitAt = configMan.getIntParameter(tv.getPropertiesPrefix() + ".SplitAt", 3000);
    // Was stored at whole
    if (iSplitAt < 100) {
      iSplitAt *= 100;
    }

    double pct = iSplitAt / 10000.0;
    if (pct < 0.03) {
      pct = 0.03;
    } else if (pct > 0.97) {
      pct = 0.97;
    }

    // height will be set on first resize call
    sash.setData("PCT", new Double(pct));
    tabFolder.setLayoutData(formData);
    final FormData tabFolderData = formData;

    // FormData for Sash
    formData = new FormData();
    formData.left = new FormAttachment(0, 0);
    formData.right = new FormAttachment(100, 0);
    formData.bottom = new FormAttachment(tabFolder);
    formData.height = 5;
    sash.setLayoutData(formData);

    // FormData for table Composite
    formData = new FormData();
    formData.left = new FormAttachment(0, 0);
    formData.right = new FormAttachment(100, 0);
    formData.top = new FormAttachment(0, 0);
    formData.bottom = new FormAttachment(sash);
    cFixLayout.setLayoutData(formData);

    // Listeners to size the folder
    sash.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            final boolean FASTDRAG = true;

            if (FASTDRAG && e.detail == SWT.DRAG) {
              return;
            }

            if (tabFolder.getMinimized()) {
              tabFolder.setMinimized(false);
              refreshSelectedSubView();
              ConfigurationManager configMan = ConfigurationManager.getInstance();
              configMan.setParameter(tv.getPropertiesPrefix() + ".subViews.minimized", false);
            }

            Rectangle area = form.getClientArea();
            tabFolderData.height = area.height - e.y - e.height - iFolderHeightAdj;
            form.layout();

            Double l = new Double((double) tabFolder.getBounds().height / form.getBounds().height);
            sash.setData("PCT", l);
            if (e.detail != SWT.DRAG) {
              ConfigurationManager configMan = ConfigurationManager.getInstance();
              configMan.setParameter(
                  tv.getPropertiesPrefix() + ".SplitAt", (int) (l.doubleValue() * 10000));
            }
          }
        });

    final CTabFolder2Adapter folderListener =
        new CTabFolder2Adapter() {
          public void minimize(CTabFolderEvent event) {
            tabFolder.setMinimized(true);
            tabFolderData.height = iFolderHeightAdj;
            CTabItem[] items = tabFolder.getItems();
            for (int i = 0; i < items.length; i++) {
              CTabItem tabItem = items[i];
              tabItem.getControl().setVisible(false);
            }
            form.layout();

            UISWTViewCore view = getActiveSubView();
            if (view != null) {
              view.triggerEvent(UISWTViewEvent.TYPE_FOCUSLOST, null);
            }

            ConfigurationManager configMan = ConfigurationManager.getInstance();
            configMan.setParameter(tv.getPropertiesPrefix() + ".subViews.minimized", true);
          }

          public void restore(CTabFolderEvent event) {
            tabFolder.setMinimized(false);
            CTabItem selection = tabFolder.getSelection();
            if (selection != null) {
              selection.getControl().setVisible(true);
            }
            form.notifyListeners(SWT.Resize, null);

            UISWTViewCore view = getActiveSubView();
            if (view != null) {
              view.triggerEvent(UISWTViewEvent.TYPE_FOCUSGAINED, null);
            }
            refreshSelectedSubView();

            ConfigurationManager configMan = ConfigurationManager.getInstance();
            configMan.setParameter(tv.getPropertiesPrefix() + ".subViews.minimized", false);
          }
        };
    tabFolder.addCTabFolder2Listener(folderListener);

    tabFolder.addSelectionListener(
        new SelectionListener() {
          public void widgetSelected(SelectionEvent e) {
            // make sure its above
            try {
              ((CTabItem) e.item).getControl().setVisible(true);
              ((CTabItem) e.item).getControl().moveAbove(null);

              // TODO: Need to viewDeactivated old one
              UISWTViewCore view = getActiveSubView();
              if (view != null) {
                view.triggerEvent(UISWTViewEvent.TYPE_FOCUSGAINED, null);
              }

            } catch (Exception t) {
            }
          }

          public void widgetDefaultSelected(SelectionEvent e) {}
        });

    tabFolder.addMouseListener(
        new MouseAdapter() {
          public void mouseDown(MouseEvent e) {
            if (tabFolder.getMinimized()) {
              folderListener.restore(null);
              // If the user clicked down on the restore button, and we restore
              // before the CTabFolder does, CTabFolder will minimize us again
              // There's no way that I know of to determine if the mouse is
              // on that button!

              // one of these will tell tabFolder to cancel
              e.button = 0;
              tabFolder.notifyListeners(SWT.MouseExit, null);
            }
          }
        });

    form.addListener(
        SWT.Resize,
        new Listener() {
          public void handleEvent(Event e) {
            if (tabFolder.getMinimized()) {
              return;
            }

            Double l = (Double) sash.getData("PCT");
            if (l != null) {
              tabFolderData.height =
                  (int) (form.getBounds().height * l.doubleValue()) - iFolderHeightAdj;
              form.layout();
            }
          }
        });

    // Call plugin listeners
    if (pluginViews != null) {
      for (UISWTViewEventListenerWrapper l : pluginViews) {
        if (l != null) {
          try {
            UISWTViewImpl view = new UISWTViewImpl(tv.getTableID(), l.getViewID(), l, null);
            addTabView(view);
          } catch (Exception e) {
            // skip, plugin probably specifically asked to not be added
          }
        }
      }
    }

    if (configMan.getBooleanParameter(tv.getPropertiesPrefix() + ".subViews.minimized", false)) {
      tabFolder.setMinimized(true);
      tabFolderData.height = iFolderHeightAdj;
    } else {
      tabFolder.setMinimized(false);
    }

    tabFolder.setSelection(0);

    return form;
  }
  @Override
  protected Composite internalCreateControl(Composite parent, int widthHint) {

    final Composite box = new Composite(parent, SWT.NONE);
    GridLayout boxLayout = new GridLayout(2, false);
    boxLayout.horizontalSpacing = 4;
    boxLayout.marginWidth = 0;
    boxLayout.marginBottom = 0;
    boxLayout.marginHeight = 0;
    boxLayout.marginLeft = 0;
    boxLayout.marginRight = 0;
    boxLayout.marginTop = 0;
    box.setLayout(boxLayout);
    GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.widthHint = widthHint;
    box.setLayoutData(gridData);

    final boolean enabled = !variable.isDisabled();

    text = new Text(box, SWT.SINGLE | SWT.BORDER);
    text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    text.setText(variable.getValueAsString());
    text.setEnabled(enabled);
    final ModifyListener modifyListener =
        new ModifyListener() {
          @Override
          public void modifyText(ModifyEvent e) {
            variable.setValue(text.getText());
            box.getParent().notifyListeners(VariableChangeEvent.ID, new VariableChangeEvent(box));
          }
        };
    text.addModifyListener(modifyListener);

    final Button button = new Button(box, SWT.PUSH);
    button.setText("Browse...");
    button.setEnabled(enabled);

    button.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            DirectoryDialog dialog = new DirectoryDialog(button.getShell());
            dialog.setFilterPath(text.getText());
            dialog.setText("Directory Chooser");
            dialog.setMessage(variable.getLabel());

            String value = dialog.open();
            if (value != null && !value.equals(text.getText())) text.setText(value);
          }
        });

    setLabelEnabled(enabled);

    box.addListener(
        VariableChangeEvent.ID,
        new Listener() {
          @Override
          public void handleEvent(Event e) {
            if (((VariableChangeEvent) e).source == box) return;

            String value = variable.getValueAsString();
            if (!text.getText().equals(value)) {
              text.removeModifyListener(modifyListener);
              text.setText(value);
              text.addModifyListener(modifyListener);
            }

            final boolean enabled = !variable.isDisabled();
            text.setEnabled(enabled);
            button.setEnabled(enabled);
            setLabelEnabled(enabled);
          }
        });

    return box;
  }
Ejemplo n.º 14
0
  protected void createContents() {
    shlPonyTrivia = new Shell();
    shlPonyTrivia.setBackground(SWTResourceManager.getColor(255, 240, 245));
    shlPonyTrivia.setSize(800, 600);
    shlPonyTrivia.setText("Pony Trivia");
    shlPonyTrivia.setLayout(new FormLayout());
    shlPonyTrivia.setMinimumSize(shlPonyTrivia.getSize());

    final Label lblFlower = new Label(shlPonyTrivia, SWT.NONE);
    lblFlower.setBackground(SWTResourceManager.getColor(255, 240, 245));
    FormData fd_lblFlower = new FormData();
    fd_lblFlower.left = new FormAttachment(0, 10);
    lblFlower.setLayoutData(fd_lblFlower);
    lblFlower.setImage(
        SWTResourceManager.getImage(GameScreen.class, "/ponytrivia/gui/res/flower.gif"));

    final Label lblDevil = new Label(shlPonyTrivia, SWT.NONE);
    lblDevil.setBackground(SWTResourceManager.getColor(255, 240, 245));
    FormData fd_lblDevil = new FormData();
    fd_lblDevil.right = new FormAttachment(100, -10);
    fd_lblDevil.top = new FormAttachment(lblFlower, 0, SWT.TOP);
    lblDevil.setLayoutData(fd_lblDevil);
    lblDevil.setImage(
        SWTResourceManager.getImage(GameScreen.class, "/ponytrivia/gui/res/hell_boy.gif"));

    Composite composite = new Composite(shlPonyTrivia, SWT.NONE);
    composite.setBackground(SWTResourceManager.getColor(255, 240, 245));
    composite.setLocation(10, -227);
    composite.setLayout(new FormLayout());
    FormData fd_composite = new FormData();
    fd_composite.bottom = new FormAttachment(100, -10);
    fd_composite.left = new FormAttachment(0, 10);
    fd_composite.right = new FormAttachment(100, -10);
    composite.setLayoutData(fd_composite);

    final Button btnNext = new Button(composite, SWT.NONE);
    btnNext.setEnabled(false);
    FormData fd_btnNext = new FormData();
    fd_btnNext.right = new FormAttachment(100, -10);
    btnNext.setLayoutData(fd_btnNext);
    btnNext.setText("Next");

    final Button btnFiftyFifty = new Button(composite, SWT.NONE);
    fd_btnNext.left = new FormAttachment(btnFiftyFifty, 0, SWT.LEFT);
    btnFiftyFifty.setToolTipText("");
    FormData fd_btnFiftyFifty = new FormData();
    fd_btnFiftyFifty.right = new FormAttachment(100, -10);
    btnFiftyFifty.setLayoutData(fd_btnFiftyFifty);
    btnFiftyFifty.setImage(
        SWTResourceManager.getImage(GameScreen.class, "/ponytrivia/gui/res/lifebelt.gif"));

    Composite composite_1 = new Composite(composite, SWT.NONE);
    composite_1.setBackground(SWTResourceManager.getColor(255, 240, 245));
    fd_btnNext.top = new FormAttachment(composite_1, 4);
    fd_btnFiftyFifty.bottom = new FormAttachment(composite_1, -6);
    composite_1.setLayout(new FillLayout(SWT.VERTICAL));
    FormData fd_composite_1 = new FormData();
    fd_composite_1.left = new FormAttachment(0, 10);
    fd_composite_1.right = new FormAttachment(100, -10);
    fd_composite_1.top = new FormAttachment(0, 90);
    fd_composite_1.bottom = new FormAttachment(100, -44);
    composite_1.setLayoutData(fd_composite_1);

    SelectionAdapter enableNext =
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent arg0) {
            if (shlPonyTrivia.isDisposed()) {
              return;
            }
            btnNext.setEnabled(true);
          }
        };

    final Button btnAnswer_1 = new Button(composite_1, SWT.RADIO);
    btnAnswer_1.addSelectionListener(enableNext);
    btnAnswer_1.setText("Answer 1");
    btnAnswer_1.setBackground(SWTResourceManager.getColor(255, 240, 245));

    final Button btnAnswer_2 = new Button(composite_1, SWT.RADIO);
    btnAnswer_2.addSelectionListener(enableNext);
    btnAnswer_2.setText("Answer 2");
    btnAnswer_2.setBackground(SWTResourceManager.getColor(255, 240, 245));

    final Button btnAnswer_3 = new Button(composite_1, SWT.RADIO);
    btnAnswer_3.addSelectionListener(enableNext);
    btnAnswer_3.setText("Answer 3");
    btnAnswer_3.setBackground(SWTResourceManager.getColor(255, 240, 245));

    final Button btnAnswer_4 = new Button(composite_1, SWT.RADIO);
    btnAnswer_4.addSelectionListener(enableNext);
    btnAnswer_4.setText("Answer 4");
    btnAnswer_4.setBackground(SWTResourceManager.getColor(255, 240, 245));

    Composite composite_2 = new Composite(composite, SWT.NONE);
    FormData fd_composite_2 = new FormData();
    fd_composite_2.right = new FormAttachment(btnFiftyFifty, -6);
    fd_composite_2.bottom = new FormAttachment(0, 84);
    fd_composite_2.top = new FormAttachment(0, 10);
    fd_composite_2.left = new FormAttachment(0, 10);
    composite_2.setLayoutData(fd_composite_2);
    composite_2.setLayout(new FillLayout(SWT.HORIZONTAL));

    final Label lblQuestionText = new Label(composite_2, SWT.NONE);
    lblQuestionText.setBackground(SWTResourceManager.getColor(255, 240, 245));
    lblQuestionText.setText("Question Text");

    Composite composite_3 = new Composite(shlPonyTrivia, SWT.NONE);
    composite_3.setBackground(SWTResourceManager.getColor(255, 240, 245));
    fd_lblFlower.top = new FormAttachment(composite_3, 37);
    composite_3.setLayout(new FormLayout());
    FormData fd_composite_3 = new FormData();
    fd_composite_3.left = new FormAttachment(0);
    fd_composite_3.right = new FormAttachment(100);
    fd_composite_3.top = new FormAttachment(0, 10);
    fd_composite_3.bottom = new FormAttachment(0, 51);
    composite_3.setLayoutData(fd_composite_3);

    final Label lblTime = new Label(composite_3, SWT.NONE);
    lblTime.setBackground(SWTResourceManager.getColor(255, 240, 245));
    FormData fd_lblTime = new FormData();
    fd_lblTime.top = new FormAttachment(0, 10);
    fd_lblTime.left = new FormAttachment(0, 10);
    lblTime.setLayoutData(fd_lblTime);
    lblTime.setText("Remaining Time: 30");

    final Label lblScore = new Label(composite_3, SWT.NONE);
    lblScore.setBackground(SWTResourceManager.getColor(255, 240, 245));
    FormData fd_lblScore = new FormData();
    fd_lblScore.left = new FormAttachment(100, -89);
    fd_lblScore.top = new FormAttachment(lblTime, 0, SWT.TOP);
    fd_lblScore.right = new FormAttachment(100, -10);
    lblScore.setLayoutData(fd_lblScore);
    lblScore.setText("Score: 0");

    final Composite composite_4 = new Composite(shlPonyTrivia, SWT.NONE);
    composite_4.setBackground(SWTResourceManager.getColor(255, 240, 245));
    fd_composite.top = new FormAttachment(0, 222);
    composite_4.setLayout(null);
    FormData fd_composite_4 = new FormData();
    fd_composite_4.bottom = new FormAttachment(composite, -6);
    fd_composite_4.top = new FormAttachment(composite_3, 6);
    fd_composite_4.right = new FormAttachment(lblDevil, -6);
    fd_composite_4.left = new FormAttachment(lblFlower, 6);
    composite_4.setLayoutData(fd_composite_4);

    final Label lblGrass = new Label(composite_4, SWT.NONE);
    lblGrass.setBounds(10, 129, 589, 20);

    final Label lblPony = new Label(composite_4, SWT.NONE);
    lblPony.setBackground(SWTResourceManager.getColor(255, 240, 245));
    lblPony.setBounds(260, 37, 84, 86);
    lblPony.setAlignment(SWT.CENTER);
    lblPony.setImage(imgKitty1);
    lblGrass.setBackground(SWTResourceManager.getColor(0, 204, 102));

    ////////////////////////////////////////////////////////////////////////////////// 0/////////

    final Button answerButtons[] =
        new Button[] {btnAnswer_1, btnAnswer_2, btnAnswer_3, btnAnswer_4};

    composite_4.addListener(
        SWT.Resize,
        new Listener() {
          public void handleEvent(Event e) {
            if (shlPonyTrivia.isDisposed()) {
              return;
            }

            Rectangle r = lblGrass.getBounds();
            r.width = composite_4.getBounds().width - 6;
            lblGrass.setBounds(r);

            int x =
                (int)
                    ((lblGrass.getBounds().width / 2)
                        * (1 - ((double) gameState.pony_pos) / config.questions_to_win));
            lblPony.setLocation(x - lblPony.getBounds().width / 2, lblPony.getLocation().y);
          }
        });

    final Runnable updateTimeLabel =
        new Runnable() {
          private Color original = lblTime.getForeground();

          @Override
          public void run() {
            if (shlPonyTrivia.isDisposed()) {
              return;
            }
            lblTime.setText("Remaining time: " + Math.max(0, gameState.remaining_time));
            if (gameState.remaining_time <= config.alotted_time / 3) {
              lblTime.setForeground(display.getSystemColor(SWT.COLOR_RED));
            } else {
              lblTime.setForeground(original);
            }
          }
        };
    updateTimeLabel.run();

    final Color origButtonColor = btnAnswer_1.getBackground();

    final Runnable updateQuestion =
        new Runnable() {
          @Override
          public void run() {
            if (shlPonyTrivia.isDisposed()) {
              return;
            }
            QuestionInfo qi;
            qi = questionRegistry.getQuestion();
            lblQuestionText.setText(qi.questionText);
            for (int i = 0; i < answerButtons.length; i++) {
              Button btn = answerButtons[i];
              btn.setText(qi.answers.get(i));
              btn.setEnabled(true);
              btn.setBackground(origButtonColor);
              btn.setSelection(false);
            }
            gameState.correctAnswerIndex = qi.correctAnswerIndex;
          }
        };
    updateQuestion.run();

    final SelectionAdapter answerQuestion =
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent arg0) {
            if (shlPonyTrivia.isDisposed()) {
              return;
            }

            int delta = lblGrass.getBounds().width / (2 * config.questions_to_win);
            int timeout = 1000;
            gameState.enabled = false;
            btnNext.setEnabled(false);

            final Button correct = answerButtons[gameState.correctAnswerIndex];

            if (correct.getSelection()) {
              gameState.total_score +=
                  10 + (gameState.remaining_time < 0 ? 0 : gameState.remaining_time);
              delta = -delta;
              correct.setBackground(new Color(display, 150, 250, 150));
              lblPony.setImage(imgKitty1);
              gameState.pony_pos += 1;
            } else {
              gameState.total_score -= 10;
              correct.setBackground(new Color(display, 250, 150, 150));
              timeout = 1500;
              lblPony.setImage(imgKitty2);
              gameState.pony_pos -= 1;
            }
            if (gameState.total_score < 0) {
              gameState.total_score = 0;
            }
            lblScore.setText("Score: " + gameState.total_score);
            gameState.question_number += 1;

            gameState.turnsBeforeEnablingFiftyFifty -= 1;

            class AnimatePony implements Runnable {
              private int delta;
              private int cnt;
              private int timeout;
              private final int steps = 20;
              private Point origPony;
              private Point origFlower;
              private Point origDevil;

              public AnimatePony(int delta, int timeout) {
                this.delta = delta;
                this.timeout = timeout;
                cnt = 0;
                origPony = lblPony.getLocation();
                origFlower = lblFlower.getLocation();
                origDevil = lblDevil.getLocation();
              }

              @Override
              public void run() {
                cnt++;
                Point p = lblPony.getLocation();
                double height = Math.abs(Math.sin(((double) cnt / steps) * 3 * Math.PI));
                lblPony.setLocation(p.x + delta / steps, origPony.y - (int) (10 * height));

                if (delta < 0) {
                  lblFlower.setLocation(
                      origFlower.x,
                      origFlower.y - (int) (10 * Math.sin((double) cnt / steps * Math.PI)));
                } else {
                  lblDevil.setLocation(
                      origDevil.x,
                      origDevil.y - (int) (10 * Math.sin((double) cnt / steps * Math.PI)));
                }

                if (cnt < steps) {
                  display.timerExec(timeout / steps, this);
                }
              }
            }

            display.timerExec(0, new AnimatePony(delta, (int) (timeout * 0.9)));

            display.timerExec(
                timeout,
                new Runnable() {
                  @Override
                  public void run() {
                    if (gameState.pony_pos >= config.questions_to_win) {
                      shlPonyTrivia.setEnabled(false);

                      try {
                        insertHighscore.insert(config.playerId, gameState.total_score);
                        schema.commit();
                      } catch (SQLException e) {
                        e.printStackTrace();
                      }

                      WinScreen.run(display);
                      shlPonyTrivia.close();
                      return;
                    }
                    if (gameState.pony_pos <= -config.questions_to_win) {
                      shlPonyTrivia.setEnabled(false);

                      try {
                        insertHighscore.insert(config.playerId, gameState.total_score);
                        schema.commit();
                      } catch (SQLException e) {
                        e.printStackTrace();
                      }

                      LoseScreen.run(display);
                      shlPonyTrivia.close();
                      return;
                    }
                    if (gameState.turnsBeforeEnablingFiftyFifty <= 0) {
                      gameState.turnsBeforeEnablingFiftyFifty = 0;
                      btnFiftyFifty.setEnabled(true);
                    }
                    updateTimeLabel.run();
                    updateQuestion.run();
                    gameState.remaining_time = config.alotted_time;
                    gameState.enabled = true;
                  }
                });
          }
        };

    btnFiftyFifty.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent arg0) {
            if (shlPonyTrivia.isDisposed()) {
              return;
            }
            btnFiftyFifty.setEnabled(false);
            gameState.turnsBeforeEnablingFiftyFifty = config.initalTurnsForFiftyFifty;
            ArrayList<Integer> discarded = new ArrayList<Integer>();
            discarded.add(0);
            discarded.add(1);
            discarded.add(2);
            discarded.add(3);
            discarded.remove(gameState.correctAnswerIndex);
            Collections.shuffle(discarded);
            discarded.remove(2);
            for (int i : discarded) {
              Button btn = answerButtons[i];
              btn.setEnabled(false);
              btn.setSelection(false);
              btn.setBackground(new Color(display, 50, 50, 50));
            }
          }
        });

    final Runnable timer =
        new Runnable() {
          public void run() {
            if (shlPonyTrivia.isDisposed()) {
              return;
            }
            gameState.remaining_time -= 1;
            display.timerExec(1000, this);
            updateTimeLabel.run();
            if (gameState.remaining_time <= 0 && gameState.enabled) {
              for (Button btn : answerButtons) {
                btn.setSelection(false);
              }
              answerQuestion.widgetSelected(null);
            }
          }
        };
    display.timerExec(1000, timer);

    btnNext.addSelectionListener(answerQuestion);

    bgMusicThread.setDaemon(true);
    bgMusicThread.start();
  }
Ejemplo n.º 15
0
  public TitleBar(final Window parent, final int size, int flags) {
    this.flags = flags;

    composite = new Composite(parent.getContentPanel(), SWT.NONE);

    composite.setSize(parent.getSize().x, size);

    buttonListener =
        new Listener() {
          public void handleEvent(Event event) {
            if (event.type == SWT.MouseUp) {
              // If the click is still on the button.
              if (event.x >= 0 && event.x < size && event.y >= 0 && event.y < size) {
                if (event.widget == closeButton) {
                  parent.close();
                } else if (event.widget == restoreButton) {
                  dontSetX = true;
                  parent.setMaximized(!parent.isMaximized());
                } else if (event.widget == minimizeButton) {
                  parent.setMinimized(true);
                }
              }
            } else if (event.type == SWT.MouseEnter) {
              Label button = (Label) event.widget;

              button.setBackground(hoverColor);
            } else if (event.type == SWT.MouseExit) {
              Label button = (Label) event.widget;

              button.setBackground(normalColor);
            }
          }
        };

    addButtons();

    titleLabel = new Label(composite, SWT.NONE);
    FontData fd = titleLabel.getFont().getFontData()[0];
    fd.setHeight(14);
    titleLabel.setFont(new Font(Display.getDefault(), fd));

    titleGC = new GC(titleLabel);
    setTitle(parent.getTitle());

    iconLabel = new Label(composite, SWT.NONE);
    setIcon(parent.getIcon());

    dontSetX = true;
    wasRestored = true;
    wasMaximized = parent.isMaximized();

    ControlListener resizeListener =
        new ControlListener() {
          public void controlResized(ControlEvent e) {
            composite.setSize(parent.getClientArea().width, size);

            setTitleLocation();

            layoutButtons();

            if (parent.isMaximized()) {
              if (restoreButton != null) {
                restoreButton.setImage(restoreImage);
              }
            } else {
              if (wasMaximized && !dontSetX) {
                parent.setLocation(mouseX - parent.getSize().x / 2, parent.getLocation().y);
              }

              if (restoreButton != null) {
                restoreButton.setImage(maximizeImage);
              }
            }

            dontSetX = false;

            wasRestored = false;

            wasMaximized = false;

            if (parent.isFullscreen()) {
              if (minimizeButton != null) {
                minimizeButton.setEnabled(false); // .setVisible(false);
              }
              if (restoreButton != null) {
                restoreButton.setEnabled(false); // .setVisible(false);
              }
            } else {
              if (minimizeButton != null) {
                minimizeButton.setEnabled(true); // .setVisible(true);
              }
              if (restoreButton != null) {
                restoreButton.setEnabled(true); // .setVisible(true);
              }
            }
          }

          public void controlMoved(ControlEvent e) {}
        };

    parent.addControlListener(resizeListener);

    final Tracker tracker = new Tracker(parent.getShell(), SWT.NONE);

    tracker.addControlListener(
        new ControlListener() {
          public void controlResized(ControlEvent e) {}

          public void controlMoved(ControlEvent e) {
            if (parent.isMaximized()) {
              parent.setMaximized(false);
            }

            Point loc =
                new Point(
                    tracker.getRectangles()[0].x + 99999, tracker.getRectangles()[0].y + 99999);

            int dx = loc.x - startX;
            int dy = loc.y - startY;

            parent.setLocation(parent.getLocation().x + dx, parent.getLocation().y + dy);

            startX = loc.x;
            startY = loc.y;
          }
        });

    Listener moveListener =
        new Listener() {
          public void handleEvent(Event event) {
            if (!parent.isFullscreen()) {
              if (event.type == SWT.MouseDown) {
                dragging = true;

                Control control = (Control) event.widget;

                mouseX = event.x + parent.getBorderSize() + control.getLocation().x;
                mouseY = event.y + parent.getBorderSize() + control.getLocation().y;

                wasMaximized = parent.isMaximized();

                startX = 0;
                startY = 0;

                tracker.setRectangles(new Rectangle[] {new Rectangle(-99999, -99999, 0, 0)});
                tracker.open();

                tracker.close();
                dragging = false;

                if (parent.getLocation().y + mouseY <= 0) {
                  wasRestored = true;
                  parent.setMaximized(true);
                }
              } else if (event.type == SWT.MouseDoubleClick) {
                dontSetX = true;
                wasRestored = true;
                parent.setMaximized(!parent.isMaximized());
              }
            }
          }
        };

    titleLabel.addListener(SWT.MouseDown, moveListener);
    titleLabel.addListener(SWT.MouseDoubleClick, moveListener);
    composite.addListener(SWT.MouseDown, moveListener);
    composite.addListener(SWT.MouseDoubleClick, moveListener);

    parent.addWindowListener(
        new WindowListener() {
          public boolean titleChanged(String newTitle) {
            setTitle(newTitle);

            return true;
          }

          public boolean iconChanged(Image newIcon) {
            setIcon(newIcon);

            return true;
          }
        });

    composite.setBackgroundMode(SWT.INHERIT_DEFAULT);
  }
Ejemplo n.º 16
0
  private void createContent() {
    GridData gridData;

    Composite composite = new Composite(this, SWT.NONE);
    composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    composite.setLayout(new GridLayout(3, false));

    FontRegistry fontRegistry = new FontRegistry(shell.getDisplay());
    fontRegistry.put(
        "WidgetTitle",
        new FontData[] {new FontData("Arial", 10, SWT.BOLD)}); // $NON-NLS-1$ //$NON-NLS-2$

    Label label = new Label(composite, SWT.NONE);
    label.setFont(fontRegistry.get("WidgetTitle")); // $NON-NLS-1$
    label.setText(Messages.getString("RTCTypeToRTTypeWidget.3")); // $NON-NLS-1$
    gridData = new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 3, 1);
    label.setLayoutData(gridData);

    Label titleBarSeparator = new Label(composite, SWT.HORIZONTAL | SWT.SEPARATOR);
    titleBarSeparator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));

    Label currentTerminoRelationTypeLabel = new Label(composite, SWT.NONE);
    currentTerminoRelationTypeLabel.setText(
        Messages.getString("RTCTypeToRTTypeWidget.4") + " :"); // $NON-NLS-1$ //$NON-NLS-2$

    currentTerminoRelationTypeText = new Text(composite, SWT.SINGLE | SWT.BORDER);
    currentTerminoRelationTypeText.setLayoutData(
        new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));

    Label associatedTypeLabel = new Label(composite, SWT.NONE);
    associatedTypeLabel.setLayoutData(
        new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 1, 2));
    associatedTypeLabel.setText(
        Messages.getString("RTCTypeToRTTypeWidget.6") + " :"); // $NON-NLS-1$ //$NON-NLS-2$

    rtTypeListViewer = new ListViewer(composite, SWT.BORDER | SWT.V_SCROLL);
    rtTypeListViewer.setContentProvider(new RTTypeContentProvider());
    rtTypeListViewer.setLabelProvider(new RTLabelProvider());
    gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 2);
    gridData.heightHint = 100;
    rtTypeListViewer.getList().setLayoutData(gridData);

    rtTypeListViewer.addSelectionChangedListener(
        new ISelectionChangedListener() {

          public void selectionChanged(SelectionChangedEvent event) {

            IStructuredSelection selection = (IStructuredSelection) event.getSelection();

            if (selection.getFirstElement() != null) {

              unlinkAction.setEnabled(true);

              currentRTType = (ITypeRelationTermino) selection.getFirstElement();

              propertyChangeSupport.firePropertyChange(
                  rtTypeSelectionEventType, null, currentRTType);

            } else {

              unlinkAction.setEnabled(false);
            }
          }
        });

    Label newRTTypeLabel = new Label(composite, SWT.NONE);
    gridData = new GridData();
    gridData.verticalAlignment = SWT.CENTER;
    newRTTypeLabel.setLayoutData(gridData);
    newRTTypeLabel.setText(
        Messages.getString("RTCTypeToRTTypeWidget.8") + " :"); // $NON-NLS-1$ //$NON-NLS-2$

    newRTTypeText = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.WRAP);
    gridData = new GridData();
    gridData.horizontalAlignment = SWT.FILL;
    gridData.widthHint = 150;
    gridData.grabExcessHorizontalSpace = true;
    newRTTypeText.setLayoutData(gridData);

    Button newRTTypeButton = new Button(composite, SWT.NONE);
    String imageId = org.dafoe.terminologiclevel.Activator.NEW_IMG_ID;
    ImageDescriptor imgDesc =
        org.dafoe.terminologiclevel.Activator.getDefault()
            .getImageRegistry()
            .getDescriptor(imageId);
    Image imageAdd = imgDesc.createImage();
    newRTTypeButton.setImage(imageAdd);
    newRTTypeButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, true, false));

    newRTTypeButton.addSelectionListener(
        new SelectionAdapter() {

          public void widgetSelected(SelectionEvent e) {

            String newRTTypeLabel = newRTTypeText.getText().trim();
            ;

            if (newRTTypeLabel.compareTo("") != 0) { // $NON-NLS-1$

              ITypeRelationTermino testRTType = DatabaseAdapter.getRTTypeByLabel(newRTTypeLabel);

              // there isn't another RT type with the same label
              if (testRTType == null) {

                ITypeRelationTermino newRTType = DatabaseAdapter.createRelationType(newRTTypeLabel);

                org.dafoe.terminoontologiclevel.common.DatabaseAdapter.linkRTCTypeWithRTType(
                    currentRTCType, newRTType);

                newRTTypeText.setText(""); // $NON-NLS-1$

                updateContent(currentRTCType);

                propertyChangeSupport.firePropertyChange(newRTEventType, null, newRTType);

              } else {

                String msg =
                    Messages.getString("RTCTypeToRTTypeWidget.12")
                        + newRTTypeLabel
                        + Messages.getString(
                            "RTCTypeToRTTypeWidget.13"); //$NON-NLS-1$ //$NON-NLS-2$
                msg += Messages.getString("RTCTypeToRTTypeWidget.14"); // $NON-NLS-1$

                MessageDialog.openWarning(
                    shell, Messages.getString("RTCTypeToRTTypeWidget.15"), msg); // $NON-NLS-1$

                newRTTypeText.selectAll();
              }
            }
          }
        });

    composite.addListener(
        SWT.Resize,
        new Listener() {
          public void handleEvent(Event event) {
            Rectangle rect = RTCTypeToRTTypeWidget.this.getClientArea();
            Image newImage = new Image(shell.getDisplay(), Math.max(1, rect.width), 1);
            GC gc = new GC(newImage);
            gc.setForeground(terminologic_level_color);
            gc.setBackground(terminoontologic_level_color);
            gc.fillGradientRectangle(rect.x, rect.y, rect.width, 1, false);
            gc.dispose();
            RTCTypeToRTTypeWidget.this.setBackgroundImage(newImage);
            if (oldImage != null) {
              oldImage.dispose();
            }
            oldImage = newImage;
          }
        });

    makeActions();

    hookPopupMenu();
  }
Ejemplo n.º 17
0
  /**
   * Creates a new <code>java.awt.Frame</code>. This frame is the root for the AWT components that
   * will be embedded within the composite. In order for the embedding to succeed, the composite
   * must have been created with the SWT.EMBEDDED style.
   *
   * <p>IMPORTANT: As of JDK1.5, the embedded frame does not receive mouse events. When a
   * lightweight component is added as a child of the embedded frame, the cursor does not change. In
   * order to work around both these problems, it is strongly recommended that a heavyweight
   * component such as <code>java.awt.Panel</code> be added to the frame as the root of all
   * components.
   *
   * @param parent the parent <code>Composite</code> of the new <code>java.awt.Frame</code>
   * @return a <code>java.awt.Frame</code> to be the parent of the embedded AWT components
   * @exception IllegalArgumentException
   *     <ul>
   *       <li>ERROR_NULL_ARGUMENT - if the parent is null
   *       <li>ERROR_INVALID_ARGUMENT - if the parent Composite does not have the SWT.EMBEDDED style
   *     </ul>
   *
   * @since 3.0
   */
  public static Frame new_Frame(final Composite parent) {
    if (parent == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
    if ((parent.getStyle() & SWT.EMBEDDED) == 0) {
      SWT.error(SWT.ERROR_INVALID_ARGUMENT);
    }
    int /*long*/ handle = parent.embeddedHandle;
    /*
     * Some JREs have implemented the embedded frame constructor to take an integer
     * and other JREs take a long.  To handle this binary incompatibility, use
     * reflection to create the embedded frame.
     */
    Class clazz = null;
    try {
      String className =
          embeddedFrameClass != null ? embeddedFrameClass : "sun.awt.X11.XEmbeddedFrame";
      clazz = Class.forName(className);
    } catch (Throwable e) {
      SWT.error(SWT.ERROR_NOT_IMPLEMENTED, e, " [need JDK 1.5 or greater]");
    }
    initializeSwing();
    Object value = null;
    Constructor constructor = null;
    try {
      constructor = clazz.getConstructor(new Class[] {int.class, boolean.class});
      value =
          constructor.newInstance(new Object[] {new Integer((int) /*64*/ handle), Boolean.TRUE});
    } catch (Throwable e1) {
      try {
        constructor = clazz.getConstructor(new Class[] {long.class, boolean.class});
        value = constructor.newInstance(new Object[] {new Long(handle), Boolean.TRUE});
      } catch (Throwable e2) {
        SWT.error(SWT.ERROR_NOT_IMPLEMENTED, e2);
      }
    }
    final Frame frame = (Frame) value;
    parent.setData(EMBEDDED_FRAME_KEY, frame);
    if (Device.DEBUG) {
      loadLibrary();
      setDebug(frame, true);
    }
    try {
      /* Call registerListeners() to make XEmbed focus traversal work */
      Method method = clazz.getMethod("registerListeners", null);
      if (method != null) method.invoke(value, null);
    } catch (Throwable e) {
    }
    final AWTEventListener awtListener =
        new AWTEventListener() {
          public void eventDispatched(AWTEvent event) {
            if (event.getID() == WindowEvent.WINDOW_OPENED) {
              final Window window = (Window) event.getSource();
              if (window.getParent() == frame) {
                parent
                    .getDisplay()
                    .asyncExec(
                        new Runnable() {
                          public void run() {
                            if (parent.isDisposed()) return;
                            Shell shell = parent.getShell();
                            loadLibrary();
                            int /*long*/ awtHandle = getAWTHandle(window);
                            if (awtHandle == 0) return;
                            int /*long*/ xWindow =
                                OS.gdk_x11_drawable_get_xid(
                                    OS.GTK_WIDGET_WINDOW(OS.gtk_widget_get_toplevel(shell.handle)));
                            OS.XSetTransientForHint(
                                OS.gdk_x11_display_get_xdisplay(OS.gdk_display_get_default()),
                                awtHandle,
                                xWindow);
                          }
                        });
              }
            }
          }
        };
    frame.getToolkit().addAWTEventListener(awtListener, AWTEvent.WINDOW_EVENT_MASK);
    final Listener shellListener =
        new Listener() {
          public void handleEvent(Event e) {
            switch (e.type) {
              case SWT.Deiconify:
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_DEICONIFIED));
                      }
                    });
                break;
              case SWT.Iconify:
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_ICONIFIED));
                      }
                    });
                break;
            }
          }
        };
    Shell shell = parent.getShell();
    shell.addListener(SWT.Deiconify, shellListener);
    shell.addListener(SWT.Iconify, shellListener);

    Listener listener =
        new Listener() {
          public void handleEvent(Event e) {
            switch (e.type) {
              case SWT.Dispose:
                Shell shell = parent.getShell();
                shell.removeListener(SWT.Deiconify, shellListener);
                shell.removeListener(SWT.Iconify, shellListener);
                parent.setVisible(false);
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        frame.getToolkit().removeAWTEventListener(awtListener);
                        frame.dispose();
                      }
                    });
                break;
              case SWT.Resize:
                if (Library.JAVA_VERSION >= Library.JAVA_VERSION(1, 6, 0)) {
                  final Rectangle clientArea = parent.getClientArea();
                  EventQueue.invokeLater(
                      new Runnable() {
                        public void run() {
                          frame.setSize(clientArea.width, clientArea.height);
                        }
                      });
                }
                break;
            }
          }
        };
    parent.addListener(SWT.Dispose, listener);
    parent.addListener(SWT.Resize, listener);

    parent
        .getDisplay()
        .asyncExec(
            new Runnable() {
              public void run() {
                if (parent.isDisposed()) return;
                final Rectangle clientArea = parent.getClientArea();
                EventQueue.invokeLater(
                    new Runnable() {
                      public void run() {
                        frame.setSize(clientArea.width, clientArea.height);
                        frame.validate();
                      }
                    });
              }
            });
    return frame;
  }