/*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.e4.ui.internal.workbench.swt.AbstractPartRenderer#createWidget
   * (org.eclipse.e4.ui.model.application.ui.MUIElement, java.lang.Object)
   */
  @Override
  public Object createWidget(final MUIElement element, Object parent) {
    if (!(element instanceof MToolBar) || !(parent instanceof Composite)) return null;

    final MToolBar toolbarModel = (MToolBar) element;
    ToolBar newTB = createToolbar(toolbarModel, (Composite) parent);
    bindWidget(element, newTB);
    processContribution(toolbarModel, toolbarModel.getElementId());

    Control renderedCtrl = newTB;
    MUIElement parentElement = element.getParent();
    if (parentElement instanceof MTrimBar) {
      element.getTags().add("Draggable"); // $NON-NLS-1$

      setCSSInfo(element, newTB);

      boolean vertical = false;
      MTrimBar bar = (MTrimBar) parentElement;
      vertical = bar.getSide() == SideValue.LEFT || bar.getSide() == SideValue.RIGHT;
      IEclipseContext parentContext = getContextForParent(element);
      CSSRenderingUtils cssUtils = parentContext.get(CSSRenderingUtils.class);
      if (cssUtils != null) {
        renderedCtrl = (Composite) cssUtils.frameMeIfPossible(newTB, null, vertical, true);
      }
    }

    return renderedCtrl;
  }
 public static boolean processAddition(
     final MTrimBar trimBar,
     MTrimContribution contribution,
     List<MTrimElement> contributions,
     HashSet<String> existingToolbarIds) {
   int idx = getIndex(trimBar, contribution.getPositionInParent());
   if (idx == -1) {
     return false;
   }
   for (MTrimElement item : contribution.getChildren()) {
     if (item instanceof MToolBar && existingToolbarIds.contains(item.getElementId())) {
       // skip this, it's already there
       continue;
     }
     MTrimElement copy = (MTrimElement) EcoreUtil.copy((EObject) item);
     if (DEBUG) {
       trace("addTrimContribution " + copy, trimBar.getWidget(), trimBar); // $NON-NLS-1$
     }
     trimBar.getChildren().add(idx++, copy);
     contributions.add(copy);
     if (copy instanceof MToolBar && copy.getElementId() != null) {
       existingToolbarIds.add(copy.getElementId());
     }
   }
   return true;
 }
  private void resetPerspectiveModel(
      MPerspective persp, MWindow window, boolean removeSharedPlaceholders) {
    if (persp == null) {
      return;
    }

    if (removeSharedPlaceholders) {
      // Remove any views (Placeholders) from the shared area
      EPartService ps = window.getContext().get(EPartService.class);
      List<MArea> areas = findElements(window, null, MArea.class, null);
      if (areas.size() == 1) {
        MArea area = areas.get(0);

        // Strip out the placeholders in visible stacks
        List<MPlaceholder> phList = findElements(area, null, MPlaceholder.class, null);
        for (MPlaceholder ph : phList) {
          ps.hidePart((MPart) ph.getRef());
          ph.getParent().getChildren().remove(ph);
        }

        // Prevent shared stacks ids from clashing with the ones in the perspective
        List<MPartStack> stacks = findElements(area, null, MPartStack.class, null);
        for (MPartStack stack : stacks) {
          String generatedId = "PartStack@" + Integer.toHexString(stack.hashCode()); // $NON-NLS-1$
          stack.setElementId(generatedId);
        }

        // Also remove any min/max tags on the area (or its placeholder)
        MUIElement areaPresentation = area;
        if (area.getCurSharedRef() != null) {
          areaPresentation = area.getCurSharedRef();
        }

        areaPresentation.getTags().remove(IPresentationEngine.MAXIMIZED);
        areaPresentation.getTags().remove(IPresentationEngine.MINIMIZED);
        areaPresentation.getTags().remove(IPresentationEngine.MINIMIZED_BY_ZOOM);
      }
    }

    // Remove any minimized stacks for this perspective
    List<MTrimBar> bars = findElements(window, null, MTrimBar.class, null);
    List<MToolControl> toRemove = new ArrayList<>();
    for (MTrimBar bar : bars) {
      for (MUIElement barKid : bar.getChildren()) {
        if (!(barKid instanceof MToolControl)) {
          continue;
        }
        String id = barKid.getElementId();
        if (id != null && id.contains(persp.getElementId())) {
          toRemove.add((MToolControl) barKid);
        }
      }
    }

    for (MToolControl toolControl : toRemove) {
      // Close any open fast view
      toolControl.setToBeRendered(false);
      toolControl.getParent().getChildren().remove(toolControl);
    }
  }
 int getOrientation(final MUIElement element) {
   MUIElement theParent = element.getParent();
   if (theParent instanceof MTrimBar) {
     MTrimBar trimContainer = (MTrimBar) theParent;
     SideValue side = trimContainer.getSide();
     if (side.getValue() == SideValue.LEFT_VALUE || side.getValue() == SideValue.RIGHT_VALUE)
       return SWT.VERTICAL;
   }
   return SWT.HORIZONTAL;
 }
  @Override
  public MTrimBar getTrim(MTrimmedWindow window, SideValue sv) {
    List<MTrimBar> bars = window.getTrimBars();
    for (MTrimBar bar : bars) {
      if (bar.getSide() == sv) {
        return bar;
      }
    }

    // Didn't find a trim bar for the side, make one
    MTrimBar newBar = BasicFactoryImpl.eINSTANCE.createTrimBar();

    // Assign default ids to the trim bars to match legacy eclipse
    if (sv == SideValue.TOP) {
      newBar.setElementId("org.eclipse.ui.main.menu"); // $NON-NLS-1$
    } else if (sv == SideValue.BOTTOM) {
      newBar.setElementId("org.eclipse.ui.trim.status"); // $NON-NLS-1$
    } else if (sv == SideValue.LEFT) {
      newBar.setElementId("org.eclipse.ui.trim.vertical1"); // $NON-NLS-1$
    } else if (sv == SideValue.RIGHT) {
      newBar.setElementId("org.eclipse.ui.trim.vertical2"); // $NON-NLS-1$
    }

    newBar.setSide(sv);
    window.getTrimBars().add(newBar);
    return newBar;
  }
  @Override
  public void createWidget(MUIElement element, MElementContainer<MUIElement> parent) {
    if (!(element instanceof MTrimBar)) {
      return;
    }
    final MTrimBar trimBar = (MTrimBar) element;

    ToolBar toolBar = new ToolBar();

    switch (trimBar.getSide().getValue()) {
      case SideValue.TOP_VALUE:
      case SideValue.BOTTOM_VALUE:
        toolBar.setOrientation(Orientation.HORIZONTAL);
        break;
      case SideValue.LEFT_VALUE:
      case SideValue.RIGHT_VALUE:
        toolBar.setOrientation(Orientation.VERTICAL);
        break;
    }

    element.setWidget(toolBar);
  }
  private void testTrimContainer_Side(
      SideValue applicationState, SideValue userChange, SideValue newApplicationState) {
    MApplication application = createApplication();

    MTrimmedWindow window = createTrimmedWindow(application);

    MTrimBar trimBar = BasicFactoryImpl.eINSTANCE.createTrimBar();
    trimBar.setSide(applicationState);
    window.getTrimBars().add(trimBar);

    saveModel();

    ModelReconciler reconciler = createModelReconciler();
    reconciler.recordChanges(application);

    trimBar.setSide(userChange);

    Object serialize = reconciler.serialize();

    application = createApplication();
    window = (MTrimmedWindow) application.getChildren().get(0);
    trimBar = window.getTrimBars().get(0);

    trimBar.setSide(newApplicationState);

    Collection<ModelDelta> deltas = constructDeltas(application, serialize);

    assertEquals(newApplicationState, trimBar.getSide());

    applyAll(deltas);

    if (userChange == applicationState) {
      // no change from the user, the new state is applied
      assertEquals(newApplicationState, trimBar.getSide());
    } else {
      // user change must override application state
      assertEquals(userChange, trimBar.getSide());
    }
  }
  /**
   * Modify the given workbench window shell bits to show the tool bar toggle button.
   *
   * @param window the window to modify
   * @since 3.2
   */
  @SuppressWarnings("restriction")
  protected void modifyWindowShell(MWindow window) {
    if (window.getWidget() == null) {
      return;
    }
    if (window.getMainMenu() == null) {
      return;
    }
    redirectHandledMenuItems(window.getMainMenu());

    // the toolbar button is not available since MacOS X 10.7
    if (OS.VERSION >= 0x1070) {
      return;
    }
    // only add the button when either the cool bar or perspective bar
    // is initially visible. This is so that RCP applications can choose to
    // use this fragment without fear that their explicitly invisible bars
    // can't be shown.
    boolean trimInitiallyVisible = false;
    if (window instanceof MTrimmedWindow && !((MTrimmedWindow) window).getTrimBars().isEmpty()) {
      for (MTrimBar tb : ((MTrimmedWindow) window).getTrimBars()) {
        if (tb.isVisible()) {
          trimInitiallyVisible = true;
        }
      }
    }

    // It would also be worth checking if there's a command defined
    // for COMMAND_ID_TOGGLE_COOLBAR
    if (trimInitiallyVisible) {
      Shell shell = ((Control) window.getWidget()).getShell();
      NSWindow nsWindow = shell.view.window();
      // Add an empty, hidden tool bar to the window. Without this the
      // tool bar button at the top right of the window will not
      // appear even when setShowsToolbarButton(true) is called.
      // Unfortunately cannot just call shell.getToolBar() as it
      // allocates a properly-sized toolbar
      NSToolbar dummyBar = new NSToolbar();
      dummyBar.alloc();
      dummyBar.initWithIdentifier(NSString.stringWith("SWTToolbar")); // $NON-NLS-1$
      dummyBar.setVisible(false);
      nsWindow.setToolbar(dummyBar);
      dummyBar.release();
      nsWindow.setShowsToolbarButton(true);

      // Override the target and action of the toolbar button so we can
      // control it.
      try {
        Object fieldValue = wrapPointer(NSWindowToolbarButton);
        NSButton toolbarButton =
            (NSButton)
                invokeMethod(
                    NSWindow.class,
                    nsWindow,
                    "standardWindowButton",
                    new Object[] {fieldValue}); // $NON-NLS-1$
        if (toolbarButton != null) {
          toolbarButton.setTarget(delegate);
          invokeMethod(
              NSControl.class,
              toolbarButton,
              "setAction", //$NON-NLS-1$
              new Object[] {wrapPointer(sel_toolbarButtonClicked_)});
        }
      } catch (Exception e) {
        // theoretically, one of
        // SecurityException,Illegal*Exception,InvocationTargetException,NoSuch*Exception
        // not expected to happen at all.
        log(e);
      }
    }
  }
  @PostConstruct
  void createWidget(Composite parent, MToolControl toolControl) {
    psME = toolControl;
    MUIElement meParent = psME.getParent();
    int orientation = SWT.HORIZONTAL;
    if (meParent instanceof MTrimBar) {
      MTrimBar bar = (MTrimBar) meParent;
      if (bar.getSide() == SideValue.RIGHT || bar.getSide() == SideValue.LEFT)
        orientation = SWT.VERTICAL;
    }
    comp = new Composite(parent, SWT.NONE);
    RowLayout layout = new RowLayout(SWT.HORIZONTAL);
    layout.marginLeft = layout.marginRight = 8;
    layout.marginBottom = 4;
    layout.marginTop = 6;
    comp.setLayout(layout);
    psTB = new ToolBar(comp, SWT.FLAT | SWT.WRAP | SWT.RIGHT + orientation);
    comp.addPaintListener(
        new PaintListener() {

          public void paintControl(PaintEvent e) {
            paint(e);
          }
        });
    toolParent = ((Control) toolControl.getParent().getWidget());
    toolParent.addPaintListener(
        new PaintListener() {

          public void paintControl(PaintEvent e) {
            if (borderColor == null) borderColor = e.display.getSystemColor(SWT.COLOR_BLACK);
            e.gc.setForeground(borderColor);
            Rectangle bounds = ((Control) e.widget).getBounds();
            e.gc.drawLine(0, bounds.height - 1, bounds.width, bounds.height - 1);
          }
        });

    comp.addDisposeListener(
        new DisposeListener() {
          public void widgetDisposed(DisposeEvent e) {
            dispose();
          }
        });

    psTB.addMenuDetectListener(
        new MenuDetectListener() {
          public void menuDetected(MenuDetectEvent e) {
            ToolBar tb = (ToolBar) e.widget;
            Point p = new Point(e.x, e.y);
            p = psTB.getDisplay().map(null, psTB, p);
            ToolItem item = tb.getItem(p);
            if (item == null) E4Util.message("  ToolBar menu"); // $NON-NLS-1$
            else {
              MPerspective persp = (MPerspective) item.getData();
              if (persp == null) E4Util.message("  Add button Menu"); // $NON-NLS-1$
              else openMenuFor(item, persp);
            }
          }
        });

    psTB.addDisposeListener(
        new DisposeListener() {
          public void widgetDisposed(DisposeEvent e) {
            disposeTBImages();
          }
        });

    psTB.getAccessible()
        .addAccessibleListener(
            new AccessibleAdapter() {
              public void getName(AccessibleEvent e) {
                if (0 <= e.childID && e.childID < psTB.getItemCount()) {
                  ToolItem item = psTB.getItem(e.childID);
                  if (item != null) {
                    e.result = item.getToolTipText();
                  }
                }
              }
            });

    hookupDnD(psTB);

    final ToolItem createItem = new ToolItem(psTB, SWT.PUSH);
    createItem.setImage(getOpenPerspectiveImage());
    createItem.setToolTipText(WorkbenchMessages.OpenPerspectiveDialogAction_tooltip);
    createItem.addSelectionListener(
        new SelectionListener() {
          public void widgetSelected(SelectionEvent e) {
            selectPerspective();
          }

          public void widgetDefaultSelected(SelectionEvent e) {
            selectPerspective();
          }
        });
    new ToolItem(psTB, SWT.SEPARATOR);

    MPerspectiveStack stack = getPerspectiveStack();
    if (stack != null) {
      // Create an item for each perspective that should show up
      for (MPerspective persp : stack.getChildren()) {
        if (persp.isToBeRendered()) {
          addPerspectiveItem(persp);
        }
      }
    }
  }