private void initializedPerspectiveSwticherPanel(MPerspectiveStack perspectiveStack) {
    if (perspectiveSwitcherPanel != null) return;
    // initialize perspective switcher panel
    perspectiveStackForSwitcher = perspectiveStack;
    boolean iconsOnly = perspectiveStackForSwitcher.getTags().contains(Tags.ICONS_ONLY);

    perspectiveSwitcherPanel = new HorizontalLayout();
    perspectiveSwitcherPanel.setStyleName("perspectivepanel");
    perspectiveSwitcherPanel.setSizeUndefined();

    Button openPerspectiveButton = new Button("Open");
    openPerspectiveButton.addStyleName("vaaclipsebutton");
    openPerspectiveButton.addStyleName("icononly");
    openPerspectiveButton.setIcon(
        new ThemeResource("../vaaclipse_default_theme/img/open_perspective.png"));
    perspectiveSwitcherPanel.addComponent(openPerspectiveButton);

    openPerspectiveButton.addListener(
        new Button.ClickListener() {

          @Override
          public void buttonClick(ClickEvent event) {
            openOpenPerspectiveWindow();

            // change focus
            Component parent = event.getButton().getParent();
            while (parent != null) {
              if (parent instanceof Component.Focusable) {
                ((Component.Focusable) parent).focus();
                break;
              } else {
                parent = parent.getParent();
              }
            }
          }
        });

    // add separator between openPerspectiveButton and perspective's buttons
    Label separator = new Label();
    separator.setSizeUndefined();
    separator.addStyleName("horizontalseparator");
    separator.setHeight("100%");
    perspectiveSwitcherPanel.addComponent(separator);

    // add buttons to perspective switch panel
    for (final MPerspective perspective : perspectiveStackForSwitcher.getChildren()) {
      Component button = createPerspectiveButton(perspective);
      if (button != null) perspectiveSwitcherPanel.addComponent(button);
    }
  }
        public void handleEvent(Event event) {
          if (psTB.isDisposed()) {
            return;
          }

          MUIElement changedElement = (MUIElement) event.getProperty(UIEvents.EventTags.ELEMENT);

          if (psME == null || !(changedElement instanceof MPerspectiveStack)) return;

          MWindow perspWin = modelService.getTopLevelWindowFor(changedElement);
          MWindow switcherWin = modelService.getTopLevelWindowFor(psME);
          if (perspWin != switcherWin) return;

          MPerspectiveStack perspStack = (MPerspectiveStack) changedElement;
          if (!perspStack.isToBeRendered()) return;

          MPerspective selElement = perspStack.getSelectedElement();
          for (ToolItem ti : psTB.getItems()) {
            ti.setSelection(ti.getData() == selElement);
          }
        }
  @Override
  public void removePerspectiveModel(MPerspective persp, MWindow window) {
    // pick a new perspective to become active (if any)
    MUIElement psElement = persp.getParent();
    MPerspectiveStack ps = (MPerspectiveStack) psElement;
    boolean foundNewSelection = false;
    if (ps.getSelectedElement() == persp) {
      for (MPerspective p : ps.getChildren()) {
        if (p != persp && p.isToBeRendered()) {
          ps.setSelectedElement(p);
          foundNewSelection = true;
          break;
        }
      }

      if (!foundNewSelection) {
        ps.setSelectedElement(null);
      }
    }

    // Remove transient elements (minimized stacks, detached windows)
    resetPerspectiveModel(persp, window, false);

    // unrender the perspective and remove it
    persp.setToBeRendered(false);
    ps.getChildren().remove(persp);
  }
  @Override
  public void processContents(MElementContainer<MUIElement> element) {
    if (element.getChildren().isEmpty()) return;

    MPerspectiveStack perspectiveStack = (MPerspectiveStack) (MElementContainer<?>) element;
    MPerspective selectedPerspective = perspectiveStack.getSelectedElement();

    if (selectedPerspective == null) {
      selectedPerspective = (MPerspective) findFirstRenderableAndVisibleElement(perspectiveStack);
      if (selectedPerspective != null) switchPerspective(selectedPerspective);
    } else if (!selectedPerspective.isToBeRendered() || !selectedPerspective.isVisible()) {
      selectedPerspective = (MPerspective) findFirstRenderableAndVisibleElement(perspectiveStack);
      if (selectedPerspective != null) switchPerspective(selectedPerspective);
      else perspectiveStack.setSelectedElement(null);
    } else {
      // reset selected element (set selected element handler will work)
      perspectiveStack.setSelectedElement(null);
      switchPerspective(selectedPerspective);
    }

    refreshPerspectiveStackVisibility(perspectiveStack);
  }
        public void handleEvent(Event event) {
          Object element = event.getProperty(UIEvents.EventTags.ELEMENT);

          if (!(element instanceof MPerspectiveStack)) return;

          MPerspectiveStack stack = (MPerspectiveStack) element;
          if (stack.getRenderer() != PerspectiveStackRenderer.this) return;
          PerspectiveStackRenderer psr = (PerspectiveStackRenderer) stack.getRenderer();

          // Gather up the elements that are being 'hidden' by this change
          MUIElement oldSel = (MUIElement) event.getProperty(UIEvents.EventTags.OLD_VALUE);
          if (oldSel != null) {
            List<MUIElement> goingHidden = new ArrayList<MUIElement>();
          }

          if (oldSel != null) {
            perspective_button.get(oldSel).setCheckedState(false);
            perspective_button.get(oldSel).setSwitchStateByUserClickEnabled(true);

            hideElementRecursive(oldSel);
          }

          ((VerticalLayout) stack.getWidget()).removeAllComponents();

          if (stack.getSelectedElement() != null) {
            showElementRecursive(stack.getSelectedElement());
            ((VerticalLayout) stack.getWidget())
                .addComponent((Component) stack.getSelectedElement().getWidget());
            perspective_button.get(stack.getSelectedElement()).setCheckedState(true);
            perspective_button
                .get(stack.getSelectedElement())
                .setSwitchStateByUserClickEnabled(false);
          } else if (oldSel instanceof MElementContainer<?>)
            disconnectReferencedElementsFromPerspectiveWidgets(
                (MElementContainer<? extends MUIElement>) oldSel);
        }
  @Override
  public void doProcessContent(MPerspectiveStack element) {
    WPerspectiveStack<N, I, IC> stack = getWidget(element);
    List<WStackItem<I, IC>> items = new ArrayList<WStackItem<I, IC>>();
    WStackItem<I, IC> initalItem = null;

    for (MPerspective e : element.getChildren()) {
      // Precreate the rendering context for the subitem
      AbstractRenderer<MPerspective, ?> renderer = factory.getRenderer(e);
      if (renderer != null && e.isToBeRendered() && e.isVisible()) {
        WStackItem<I, IC> item = createStackItem(stack, e, renderer);
        items.add(item);

        if (e == element.getSelectedElement()) {
          initalItem = item;
        }
      }
    }

    if (!items.isEmpty()) {
      if (initalItem == null || items.size() == 1 || items.get(0) == initalItem) {
        stack.addItems(items);
      } else {
        stack.addItem(initalItem);
        if (items.get(items.size() - 1) == initalItem) {
          stack.addItems(0, items.subList(0, items.size() - 1));
        } else {
          int idx = items.indexOf(initalItem);
          stack.addItems(0, items.subList(0, idx));
          stack.addItems(items.subList(idx + 1, items.size()));
        }
      }
    }

    if (element.getSelectedElement() != null) {
      handleSelectedElement(element, null, element.getSelectedElement());
    } else if (!element.getChildren().isEmpty()) {
      // TODO Should this be done through the part service????
      element.setSelectedElement(element.getChildren().get(0));
    }
  }
 private void refreshPerspectiveStackVisibility(MPerspectiveStack stack) {
   perspectiveSwitcherPanel.setVisible(stack.getChildren().size() > 0);
 }
  private Component createPerspectiveButton(final MPerspective perspective) {
    if (!perspective.isVisible()) return null;
    boolean iconsOnly = perspectiveStackForSwitcher.getTags().contains(Tags.ICONS_ONLY);
    String label = iconsOnly ? null : Commons.trim(perspective.getLabel());
    String iconURI = Commons.trim(perspective.getIconURI());

    final TwoStateToolbarButton button = new TwoStateToolbarButton(label, iconURI);

    if (perspective.getTooltip() != null) {
      button.setDescription(perspective.getLocalizedTooltip());
    }

    button.addListener(
        new ClickListener() {

          public void buttonClick(ClickEvent event) {
            MPerspectiveStack perspectiveStack =
                (MPerspectiveStack) (MElementContainer<?>) perspective.getParent();
            switchPerspective(perspective);
          }
        });

    // TODO: replace VerticalLayout on more thin layout (for example SimpleLayout addon which
    // consist of just one div)
    //		 VerticalLayout wrapperLayout = new VerticalLayout();
    //		 wrapperLayout.setSizeUndefined();
    //		 wrapperLayout.addComponent(button);
    //		 wrapperLayout.addListener(new LayoutEvents.LayoutClickListener() {
    //
    //			 @Override
    //			 public void layoutClick(LayoutClickEvent event)
    //			 {
    //				 if (LayoutClickEvent.BUTTON_RIGHT == event.getButton())
    //				 {
    //					 lastClickedPerspective = perspective;
    ////					 menu.open(event.getClientX(), event.getClientY());
    //				 }
    //			 }
    //		 });

    // Create context menu
    // Context menu
    ContextMenu menu = new ContextMenu();
    contextMenu2Button.put(menu, button);
    button2ContextMenu.put(button, menu);

    final ContextMenuItem showTextItem;

    final ContextMenuItem closeItem = menu.addItem("Close");
    // closeItem.setSeparatorVisible(true);

    if (iconsOnly) showTextItem = menu.addItem("Show Text");
    else showTextItem = menu.addItem("Hide Text");

    // showTextItem.addStyleName("close-perspective-item"); //bugfixing style for ie9 (context menu
    // addon has bug for ie9)

    menu.addItemClickListener(
        new ContextMenu.ContextMenuItemClickListener() {

          @Override
          public void contextMenuItemClicked(ContextMenuItemClickEvent event) {
            ContextMenuItem clickedItem = (ContextMenuItem) event.getSource();

            if (clickedItem == closeItem) {
              if (perspective == activePerspective) {
                MPerspective prevRenderableAndVisiblePerspective = null,
                    nextRenderableAndVisiblePerspective = null;
                boolean startSearch = false;
                for (MPerspective p : perspectiveStackForSwitcher.getChildren()) {
                  if (startSearch && p.isToBeRendered() && p.isVisible()) {
                    nextRenderableAndVisiblePerspective = p;
                    break;
                  }

                  if (p == perspective) startSearch = true;

                  if (!startSearch && p.isToBeRendered() && p.isVisible()) {
                    prevRenderableAndVisiblePerspective = p;
                  }
                }

                MPerspective newSelectedPerspective =
                    nextRenderableAndVisiblePerspective != null
                        ? nextRenderableAndVisiblePerspective
                        : prevRenderableAndVisiblePerspective;

                if (newSelectedPerspective != null) switchPerspective(newSelectedPerspective);
              }

              perspective.setToBeRendered(false);
            } else if (clickedItem == showTextItem) {
              if (perspectiveStackForSwitcher.getTags().contains(Tags.ICONS_ONLY))
                perspectiveStackForSwitcher.getTags().remove(Tags.ICONS_ONLY);
              else perspectiveStackForSwitcher.getTags().add(Tags.ICONS_ONLY);
            }
          }
        });

    menu.setAsContextMenuOf(button);

    perspective_button.put(perspective, button);
    // return wrapperLayout;
    return button;
  }
  @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);
        }
      }
    }
  }