diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryActionContributionItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryActionContributionItem.cpp index 127fb03d93..319bd839b1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryActionContributionItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryActionContributionItem.cpp @@ -1,981 +1,987 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryActionContributionItem.h" #include +#include #include #include namespace berry { ActionContributionItem::ActionContributionItem(Action* action) : ContributionItem(action->GetId()), action(action) { } bool ActionContributionItem::operator==(const Object* o) const { if (const ActionContributionItem* aci = dynamic_cast(o)) { return action == aci->action; } return false; } -std::size_t ActionContributionItem::HashCode() const +uint ActionContributionItem::HashCode() const { return qHash(action); } void ActionContributionItem::Fill(QStatusBar* parent) { // if (widget == null && parent != null) { // int flags = SWT.PUSH; // if (action != null) { // if (action.getStyle() == IAction.AS_CHECK_BOX) { // flags = SWT.TOGGLE; // } // if (action.getStyle() == IAction.AS_RADIO_BUTTON) { // flags = SWT.RADIO; // } // } // Button b = new Button(parent, flags); // b.setData(this); // b.addListener(SWT.Dispose, getButtonListener()); // // Don't hook a dispose listener on the parent // b.addListener(SWT.Selection, getButtonListener()); // if (action.getHelpListener() != null) { // b.addHelpListener(action.getHelpListener()); // } // widget = b; // update(null); // // Attach some extra listeners. // action.addPropertyChangeListener(propertyListener); // if (action != null) { // String commandId = action.getActionDefinitionId(); // ExternalActionManager.ICallback callback = ExternalActionManager // .getInstance().getCallback(); // if ((callback != null) && (commandId != null)) { // callback.addPropertyChangeListener(commandId, // actionTextListener); // } // } // } } QAction *ActionContributionItem::Fill(QMenu* parent, QAction* before) { if (parent != 0) { if (before) { parent->insertAction(before, action); } else { parent->addAction(action); } action->setData(QVariant::fromValue(Object::Pointer(this))); //action.addListener(SWT.Dispose, getMenuItemListener()); //action.addListener(SWT.Selection, getMenuItemListener()); //if (action.getHelpListener() != null) //{ // mi.addHelpListener(action.getHelpListener()); //} if (action->menu()) { // // just create a proxy for now, if the user shows it then // // fill it in // Menu subMenu = new Menu(parent); // subMenu.addListener(SWT.Show, getMenuCreatorListener()); // subMenu.addListener(SWT.Hide, getMenuCreatorListener()); // mi.setMenu(subMenu); } Update(QString()); // // Attach some extra listeners. // action.addPropertyChangeListener(propertyListener); // if (action != null) { // String commandId = action.getActionDefinitionId(); // ExternalActionManager.ICallback callback = ExternalActionManager // .getInstance().getCallback(); // if ((callback != null) && (commandId != null)) { // callback.addPropertyChangeListener(commandId, // actionTextListener); // } // } } return action; } -QAction *ActionContributionItem::Fill(QToolBar* parent, int index) +QAction*ActionContributionItem::Fill(QMenuBar* menu, QAction* before) +{ + return NULL; +} + +QAction *ActionContributionItem::Fill(QToolBar* parent, QAction* before) { // if (widget == null && parent != null) { // int flags = SWT.PUSH; // if (action != null) { // int style = action.getStyle(); // if (style == IAction.AS_CHECK_BOX) { // flags = SWT.CHECK; // } else if (style == IAction.AS_RADIO_BUTTON) { // flags = SWT.RADIO; // } else if (style == IAction.AS_DROP_DOWN_MENU) { // flags = SWT.DROP_DOWN; // } // } // ToolItem ti = null; // if (index >= 0) { // ti = new ToolItem(parent, flags, index); // } else { // ti = new ToolItem(parent, flags); // } // ti.setData(this); // ti.addListener(SWT.Selection, getToolItemListener()); // ti.addListener(SWT.Dispose, getToolItemListener()); // widget = ti; // update(null); // // Attach some extra listeners. // action.addPropertyChangeListener(propertyListener); // if (action != null) { // String commandId = action.getActionDefinitionId(); // ExternalActionManager.ICallback callback = ExternalActionManager // .getInstance().getCallback(); // if ((callback != null) && (commandId != null)) { // callback.addPropertyChangeListener(commandId, // actionTextListener); // } // } // } return 0; } Action* ActionContributionItem::GetAction() const { return action; } ActionContributionItem::~ActionContributionItem() { //holdMenu = null; } ContributionItem::Modes ActionContributionItem::GetMode() const { return mode; } bool ActionContributionItem::IsDynamic() const { // if (qobject_cast(action->parentWidget())) // { // // Optimization. Only recreate the item is the check or radio style // // has changed. // boolean itemIsCheck = (widget.getStyle() & SWT.CHECK) != 0; // boolean actionIsCheck = getAction() != null // && getAction().getStyle() == IAction.AS_CHECK_BOX; // boolean itemIsRadio = (widget.getStyle() & SWT.RADIO) != 0; // boolean actionIsRadio = getAction() != null // && getAction().getStyle() == IAction.AS_RADIO_BUTTON; // return (itemIsCheck != actionIsCheck) // || (itemIsRadio != actionIsRadio); // } return false; } bool ActionContributionItem::IsEnabled() const { return action != 0 && action->isEnabled(); } bool ActionContributionItem::IsVisible() const { return ContributionItem::IsVisible() && IsCommandActive(); } void ActionContributionItem::SetMode(Modes mode) { this->mode = mode; Update(); } void ActionContributionItem::Update() { Update(QString()); } void ActionContributionItem::Update(const QString& propertyName) { // if (widget != 0) // { // // determine what to do // boolean textChanged = propertyName == null // || propertyName.equals(IAction.TEXT); // boolean imageChanged = propertyName == null // || propertyName.equals(IAction.IMAGE); // boolean tooltipTextChanged = propertyName == null // || propertyName.equals(IAction.TOOL_TIP_TEXT); // boolean enableStateChanged = propertyName == null // || propertyName.equals(IAction.ENABLED) // || propertyName // .equals(IContributionManagerOverrides.P_ENABLED); // boolean checkChanged = (action.getStyle() == IAction.AS_CHECK_BOX || action // .getStyle() == IAction.AS_RADIO_BUTTON) // && (propertyName == null || propertyName // .equals(IAction.CHECKED)); // if (widget instanceof ToolItem) { // ToolItem ti = (ToolItem) widget; // String text = action.getText(); // // the set text is shown only if there is no image or if forced // // by MODE_FORCE_TEXT // boolean showText = text != null // && ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action)); // // only do the trimming if the text will be used // if (showText && text != null) { // text = Action.removeAcceleratorText(text); // text = Action.removeMnemonics(text); // } // if (textChanged) { // String textToSet = showText ? text : ""; //$NON-NLS-1$ // boolean rightStyle = (ti.getParent().getStyle() & SWT.RIGHT) != 0; // if (rightStyle || !ti.getText().equals(textToSet)) { // // In addition to being required to update the text if // // it // // gets nulled out in the action, this is also a // // workaround // // for bug 50151: Using SWT.RIGHT on a ToolBar leaves // // blank space // ti.setText(textToSet); // } // } // if (imageChanged) { // // only substitute a missing image if it has no text // updateImages(!showText); // } // if (tooltipTextChanged || textChanged) { // String toolTip = action.getToolTipText(); // if ((toolTip == null) || (toolTip.length() == 0)) { // toolTip = text; // } // ExternalActionManager.ICallback callback = ExternalActionManager // .getInstance().getCallback(); // String commandId = action.getActionDefinitionId(); // if ((callback != null) && (commandId != null) // && (toolTip != null)) { // String acceleratorText = callback // .getAcceleratorText(commandId); // if (acceleratorText != null // && acceleratorText.length() != 0) { // toolTip = JFaceResources.format( // "Toolbar_Tooltip_Accelerator", //$NON-NLS-1$ // new Object[] { toolTip, acceleratorText }); // } // } // // if the text is showing, then only set the tooltip if // // different // if (!showText || toolTip != null && !toolTip.equals(text)) { // ti.setToolTipText(toolTip); // } else { // ti.setToolTipText(null); // } // } // if (enableStateChanged) { // boolean shouldBeEnabled = action.isEnabled() // && isEnabledAllowed(); // if (ti.getEnabled() != shouldBeEnabled) { // ti.setEnabled(shouldBeEnabled); // } // } // if (checkChanged) { // boolean bv = action.isChecked(); // if (ti.getSelection() != bv) { // ti.setSelection(bv); // } // } // return; // } // if (widget instanceof MenuItem) { // MenuItem mi = (MenuItem) widget; // if (textChanged) { // int accelerator = 0; // String acceleratorText = null; // IAction updatedAction = getAction(); // String text = null; // accelerator = updatedAction.getAccelerator(); // ExternalActionManager.ICallback callback = ExternalActionManager // .getInstance().getCallback(); // // Block accelerators that are already in use. // if ((accelerator != 0) && (callback != null) // && (callback.isAcceleratorInUse(accelerator))) { // accelerator = 0; // } // /* // * Process accelerators on GTK in a special way to avoid Bug // * 42009. We will override the native input method by // * allowing these reserved accelerators to be placed on the // * menu. We will only do this for "Ctrl+Shift+[0-9A-FU]". // */ // final String commandId = updatedAction // .getActionDefinitionId(); // if ((Util.isGtk()) && (callback instanceof IBindingManagerCallback) // && (commandId != null)) { // final IBindingManagerCallback bindingManagerCallback = (IBindingManagerCallback) callback; // final IKeyLookup lookup = KeyLookupFactory.getDefault(); // final TriggerSequence[] triggerSequences = bindingManagerCallback // .getActiveBindingsFor(commandId); // for (int i = 0; i < triggerSequences.length; i++) { // final TriggerSequence triggerSequence = triggerSequences[i]; // final Trigger[] triggers = triggerSequence // .getTriggers(); // if (triggers.length == 1) { // final Trigger trigger = triggers[0]; // if (trigger instanceof KeyStroke) { // final KeyStroke currentKeyStroke = (KeyStroke) trigger; // final int currentNaturalKey = currentKeyStroke // .getNaturalKey(); // if ((currentKeyStroke.getModifierKeys() == (lookup // .getCtrl() | lookup.getShift())) // && ((currentNaturalKey >= '0' && currentNaturalKey <= '9') // || (currentNaturalKey >= 'A' && currentNaturalKey <= 'F') || (currentNaturalKey == 'U'))) { // accelerator = currentKeyStroke // .getModifierKeys() // | currentNaturalKey; // acceleratorText = triggerSequence // .format(); // break; // } // } // } // } // } // if (accelerator == 0) { // if ((callback != null) && (commandId != null)) { // acceleratorText = callback // .getAcceleratorText(commandId); // } // } // IContributionManagerOverrides overrides = null; // if (getParent() != null) { // overrides = getParent().getOverrides(); // } // if (overrides != null) { // text = getParent().getOverrides().getText(this); // } // mi.setAccelerator(accelerator); // if (text == null) { // text = updatedAction.getText(); // } // if (text != null && acceleratorText == null) { // // use extracted accelerator text in case accelerator // // cannot be fully represented in one int (e.g. // // multi-stroke keys) // acceleratorText = LegacyActionTools // .extractAcceleratorText(text); // if (acceleratorText == null && accelerator != 0) { // acceleratorText = Action // .convertAccelerator(accelerator); // } // } // if (text == null) { // text = ""; //$NON-NLS-1$ // } else { // text = Action.removeAcceleratorText(text); // } // if (acceleratorText == null) { // mi.setText(text); // } else { // mi.setText(text + '\t' + acceleratorText); // } // } // if (imageChanged) { // updateImages(false); // } // if (enableStateChanged) { // boolean shouldBeEnabled = action.isEnabled() // && isEnabledAllowed(); // if (mi.getEnabled() != shouldBeEnabled) { // mi.setEnabled(shouldBeEnabled); // } // } // if (checkChanged) { // boolean bv = action.isChecked(); // if (mi.getSelection() != bv) { // mi.setSelection(bv); // } // } // return; // } // if (widget instanceof Button) { // Button button = (Button) widget; // if (imageChanged) { // updateImages(false); // } // if (textChanged) { // String text = action.getText(); // boolean showText = text != null && ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action)); // // only do the trimming if the text will be used // if (showText) { // text = Action.removeAcceleratorText(text); // } // String textToSet = showText ? text : ""; //$NON-NLS-1$ // button.setText(textToSet); // } // if (tooltipTextChanged) { // button.setToolTipText(action.getToolTipText()); // } // if (enableStateChanged) { // boolean shouldBeEnabled = action.isEnabled() // && isEnabledAllowed(); // if (button.getEnabled() != shouldBeEnabled) { // button.setEnabled(shouldBeEnabled); // } // } // if (checkChanged) { // boolean bv = action.isChecked(); // if (button.getSelection() != bv) { // button.setSelection(bv); // } // } // return; // } //} } bool ActionContributionItem::IsEnabledAllowed() const { if (this->GetParent() == 0) { return true; } int value = GetParent()->GetOverrides()->GetEnabled(this); return (value == -1) ? true : value; } //QString ActionContributionItem::ShortenText(const QString& textValue, QToolButton* item) //{ //if (textValue == null) { // return null; //} //GC gc = new GC(item.getParent()); //int maxWidth = item.getImage().getBounds().width * 4; //if (gc.textExtent(textValue).x < maxWidth) { // gc.dispose(); // return textValue; //} //for (int i = textValue.length(); i > 0; i--) { // String test = textValue.substring(0, i); // test = test + ellipsis; // if (gc.textExtent(test).x < maxWidth) { // gc.dispose(); // return test; // } //} //gc.dispose(); //// If for some reason we fall through abort //return textValue; //} //Listener ActionContributionItem::GetToolItemListener() //{ //if (toolItemListener == null) { // toolItemListener = new Listener() { // public void handleEvent(Event event) { // switch (event.type) { // case SWT.Dispose: // handleWidgetDispose(event); // break; // case SWT.Selection: // Widget ew = event.widget; // if (ew != null) { // handleWidgetSelection(event, ((ToolItem) ew) // .getSelection()); // } // break; // } // } // }; //} //return toolItemListener; //} //void ActionContributionItem::HandleWidgetDispose(Event e) //{ //// Check if our widget is the one being disposed. //if (e.widget == widget) { // // Dispose of the menu creator. // if (action.getStyle() == IAction.AS_DROP_DOWN_MENU // && menuCreatorCalled) { // IMenuCreator mc = action.getMenuCreator(); // if (mc != null) { // mc.dispose(); // } // } // // Unhook all of the listeners. // action.removePropertyChangeListener(propertyListener); // if (action != null) { // String commandId = action.getActionDefinitionId(); // ExternalActionManager.ICallback callback = ExternalActionManager // .getInstance().getCallback(); // if ((callback != null) && (commandId != null)) { // callback.removePropertyChangeListener(commandId, // actionTextListener); // } // } // // Clear the widget field. // widget = null; // disposeOldImages(); //} //} //void ActionContributionItem::HandleWidgetSelection(Event e, bool selection) //{ //Widget item = e.widget; //if (item != null) { // int style = item.getStyle(); // if ((style & (SWT.TOGGLE | SWT.CHECK)) != 0) { // if (action.getStyle() == IAction.AS_CHECK_BOX) { // action.setChecked(selection); // } // } else if ((style & SWT.RADIO) != 0) { // if (action.getStyle() == IAction.AS_RADIO_BUTTON) { // action.setChecked(selection); // } // } else if ((style & SWT.DROP_DOWN) != 0) { // if (e.detail == 4) { // on drop-down button // if (action.getStyle() == IAction.AS_DROP_DOWN_MENU) { // IMenuCreator mc = action.getMenuCreator(); // menuCreatorCalled = true; // ToolItem ti = (ToolItem) item; // // we create the menu as a sub-menu of "dummy" so that // // we can use // // it in a cascading menu too. // // If created on a SWT control we would get an SWT // // error... // // Menu dummy= new Menu(ti.getParent()); // // Menu m= mc.getMenu(dummy); // // dummy.dispose(); // if (mc != null) { // Menu m = mc.getMenu(ti.getParent()); // if (m != null) { // // position the menu below the drop down item // Point point = ti.getParent().toDisplay( // new Point(e.x, e.y)); // m.setLocation(point.x, point.y); // waiting // // for SWT // // 0.42 // m.setVisible(true); // return; // we don't fire the action // } // } // } // } // } // ExternalActionManager.IExecuteCallback callback = null; // String actionDefinitionId = action.getActionDefinitionId(); // if (actionDefinitionId != null) { // Object obj = ExternalActionManager.getInstance() // .getCallback(); // if (obj instanceof ExternalActionManager.IExecuteCallback) { // callback = (ExternalActionManager.IExecuteCallback) obj; // } // } // // Ensure action is enabled first. // // See 1GAN3M6: ITPUI:WINNT - Any IAction in the workbench can be // // executed while disabled. // if (action.isEnabled()) { // boolean trace = Policy.TRACE_ACTIONS; // long ms = 0L; // if (trace) { // ms = System.currentTimeMillis(); // System.out.println("Running action: " + action.getText()); //$NON-NLS-1$ // } // IPropertyChangeListener resultListener = null; // if (callback != null) { // resultListener = new IPropertyChangeListener() { // public void propertyChange(PropertyChangeEvent event) { // // Check on result // if (event.getProperty().equals(IAction.RESULT)) { // if (event.getNewValue() instanceof Boolean) { // result = (Boolean) event.getNewValue(); // } // } // } // }; // action.addPropertyChangeListener(resultListener); // callback.preExecute(action, e); // } // action.runWithEvent(e); // if (callback != null) { // if (result == null || result.equals(Boolean.TRUE)) { // callback.postExecuteSuccess(action, Boolean.TRUE); // } else { // callback.postExecuteFailure(action, // new ExecutionException(action.getText() // + " returned failure.")); //$NON-NLS-1$ // } // } // if (resultListener!=null) { // result = null; // action.removePropertyChangeListener(resultListener); // } // if (trace) { // System.out.println((System.currentTimeMillis() - ms) // + " ms to run action: " + action.getText()); //$NON-NLS-1$ // } // } else { // if (callback != null) { // callback.notEnabled(action, new NotEnabledException(action // .getText() // + " is not enabled.")); //$NON-NLS-1$ // } // } //} //} //bool ActionContributionItem::HasImages(Action* actionToCheck) const //{ // return actionToCheck.getImageDescriptor() != null // || actionToCheck.getHoverImageDescriptor() != null // || actionToCheck.getDisabledImageDescriptor() != null; //} bool ActionContributionItem::IsCommandActive() const { Action* actionToCheck = GetAction(); if (actionToCheck != 0) { QString commandId = actionToCheck->GetActionDefinitionId(); ExternalActionManager.ICallback callback = ExternalActionManager .getInstance().getCallback(); if (callback != null) { return callback.isActive(commandId); } } return true; } //bool ActionContributionItem::UpdateImages(bool forceImage) //{ // ResourceManager parentResourceManager = JFaceResources.getResources(); // if (widget instanceof ToolItem) { // if (USE_COLOR_ICONS) { // ImageDescriptor image = action.getHoverImageDescriptor(); // if (image == null) { // image = action.getImageDescriptor(); // } // ImageDescriptor disabledImage = action // .getDisabledImageDescriptor(); // // Make sure there is a valid image. // if (image == null && forceImage) { // image = ImageDescriptor.getMissingImageDescriptor(); // } // LocalResourceManager localManager = new LocalResourceManager( // parentResourceManager); // // performance: more efficient in SWT to set disabled and hot // // image before regular image // ((ToolItem) widget) // .setDisabledImage(disabledImage == null ? null // : localManager // .createImageWithDefault(disabledImage)); // ((ToolItem) widget).setImage(image == null ? null // : localManager.createImageWithDefault(image)); // disposeOldImages(); // imageManager = localManager; // return image != null; // } // ImageDescriptor image = action.getImageDescriptor(); // ImageDescriptor hoverImage = action.getHoverImageDescriptor(); // ImageDescriptor disabledImage = action.getDisabledImageDescriptor(); // // If there is no regular image, but there is a hover image, // // convert the hover image to gray and use it as the regular image. // if (image == null && hoverImage != null) { // image = ImageDescriptor.createWithFlags(action // .getHoverImageDescriptor(), SWT.IMAGE_GRAY); // } else { // // If there is no hover image, use the regular image as the // // hover image, // // and convert the regular image to gray // if (hoverImage == null && image != null) { // hoverImage = image; // image = ImageDescriptor.createWithFlags(action // .getImageDescriptor(), SWT.IMAGE_GRAY); // } // } // // Make sure there is a valid image. // if (hoverImage == null && image == null && forceImage) { // image = ImageDescriptor.getMissingImageDescriptor(); // } // // Create a local resource manager to remember the images we've // // allocated for this tool item // LocalResourceManager localManager = new LocalResourceManager( // parentResourceManager); // // performance: more efficient in SWT to set disabled and hot image // // before regular image // ((ToolItem) widget).setDisabledImage(disabledImage == null ? null // : localManager.createImageWithDefault(disabledImage)); // ((ToolItem) widget).setHotImage(hoverImage == null ? null // : localManager.createImageWithDefault(hoverImage)); // ((ToolItem) widget).setImage(image == null ? null : localManager // .createImageWithDefault(image)); // // Now that we're no longer referencing the old images, clear them // // out. // disposeOldImages(); // imageManager = localManager; // return image != null; // } else if (widget instanceof Item || widget instanceof Button) { // // Use hover image if there is one, otherwise use regular image. // ImageDescriptor image = action.getHoverImageDescriptor(); // if (image == null) { // image = action.getImageDescriptor(); // } // // Make sure there is a valid image. // if (image == null && forceImage) { // image = ImageDescriptor.getMissingImageDescriptor(); // } // // Create a local resource manager to remember the images we've // // allocated for this widget // LocalResourceManager localManager = new LocalResourceManager( // parentResourceManager); // if (widget instanceof Item) { // ((Item) widget).setImage(image == null ? null : localManager // .createImageWithDefault(image)); // } else if (widget instanceof Button) { // ((Button) widget).setImage(image == null ? null : localManager // .createImageWithDefault(image)); // } // // Now that we're no longer referencing the old images, clear them // // out. // disposeOldImages(); // imageManager = localManager; // return image != null; // } // return false; //} //void ActionContributionItem::DisposeOldImages() //{ // if (imageManager != null) { // imageManager.dispose(); // imageManager = null; // } //} //Listener ActionContributionItem::getMenuCreatorListener() { // if (menuCreatorListener == null) { // menuCreatorListener = new Listener() { // public void handleEvent(Event event) { // switch (event.type) { // case SWT.Show: // handleShowProxy((Menu) event.widget); // break; // case SWT.Hide: // handleHideProxy((Menu) event.widget); // break; // } // } // }; // } // return menuCreatorListener; //} //void ActionContributionItem::HandleShowProxy(QMenu* proxy) //{ // proxy.removeListener(SWT.Show, getMenuCreatorListener()); // IMenuCreator mc = action.getMenuCreator(); // menuCreatorCalled = true; // if (mc == null) { // return; // } // holdMenu = mc.getMenu(proxy.getParentMenu()); // if (holdMenu == null) { // return; // } // copyMenu(holdMenu, proxy); //} //void ActionContributionItem::CopyMenu(QMenu* realMenu, QMenu* proxy) { // if (realMenu.isDisposed() || proxy.isDisposed()) { // return; // } // // we notify the real menu so it can populate itself if it was // // listening for SWT.Show // realMenu.notifyListeners(SWT.Show, null); // final Listener passThrough = new Listener() { // public void handleEvent(Event event) { // if (!event.widget.isDisposed()) { // Widget realItem = (Widget) event.widget.getData(); // if (!realItem.isDisposed()) { // int style = event.widget.getStyle(); // if (event.type == SWT.Selection // && ((style & (SWT.TOGGLE | SWT.CHECK | SWT.RADIO)) != 0) // && realItem instanceof MenuItem) { // ((MenuItem) realItem) // .setSelection(((MenuItem) event.widget) // .getSelection()); // } // event.widget = realItem; // realItem.notifyListeners(event.type, event); // } // } // } // }; // MenuItem[] items = realMenu.getItems(); // for (int i = 0; i < items.length; i++) { // final MenuItem realItem = items[i]; // final MenuItem proxyItem = new MenuItem(proxy, realItem.getStyle()); // proxyItem.setData(realItem); // proxyItem.setAccelerator(realItem.getAccelerator()); // proxyItem.setEnabled(realItem.getEnabled()); // proxyItem.setImage(realItem.getImage()); // proxyItem.setSelection(realItem.getSelection()); // proxyItem.setText(realItem.getText()); // // pass through any events // proxyItem.addListener(SWT.Selection, passThrough); // proxyItem.addListener(SWT.Arm, passThrough); // proxyItem.addListener(SWT.Help, passThrough); // final Menu itemMenu = realItem.getMenu(); // if (itemMenu != null) { // // create a proxy for any sub menu items // final Menu subMenu = new Menu(proxy); // subMenu.setData(itemMenu); // proxyItem.setMenu(subMenu); // subMenu.addListener(SWT.Show, new Listener() { // public void handleEvent(Event event) { // event.widget.removeListener(SWT.Show, this); // if (event.type == SWT.Show) { // copyMenu(itemMenu, subMenu); // } // } // }); // subMenu.addListener(SWT.Help, passThrough); // subMenu.addListener(SWT.Hide, passThrough); // } // } //} //void ActionContributionItem::HandleHideProxy(QMenu* proxy) //{ // proxy.removeListener(SWT.Hide, getMenuCreatorListener()); // proxy.getDisplay().asyncExec(new Runnable() { // public void run() { // if (!proxy.isDisposed()) { // MenuItem parentItem = proxy.getParentItem(); // proxy.dispose(); // parentItem.setMenu(holdMenu); // } // if (holdMenu != null && !holdMenu.isDisposed()) { // holdMenu.notifyListeners(SWT.Hide, null); // } // holdMenu = null; // } // }); //} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryActionContributionItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryActionContributionItem.h index a92e0b410c..474089d903 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryActionContributionItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryActionContributionItem.h @@ -1,292 +1,294 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYACTIONCONTRIBUTIONITEM_H #define BERRYACTIONCONTRIBUTIONITEM_H #include "berryContributionItem.h" namespace berry { class Action; /** * A contribution item which delegates to an action. *

* This class may be instantiated; it is not intended to be subclassed. *

* @noextend This class is not intended to be subclassed by clients. */ class ActionContributionItem : public ContributionItem { public: /** * Creates a new contribution item from the given action. The id of the * action is used as the id of the item. * * @param action * the action */ ActionContributionItem(Action* action); ~ActionContributionItem(); /** * Compares this action contribution item with another object. Two action * contribution items are equal if they refer to the identical Action. */ bool operator==(const Object* o) const; - std::size_t HashCode() const; + uint HashCode() const; /** * The ActionContributionItem implementation of this * IContributionItem method creates an SWT * Button for the action using the action's style. If the * action's checked property has been set, the button is created and primed * to the value of the checked property. */ void Fill(QStatusBar* parent); /** * The ActionContributionItem implementation of this * IContributionItem method creates an SWT * MenuItem for the action using the action's style. If the * action's checked property has been set, a button is created and primed to * the value of the checked property. If the action's menu creator property * has been set, a cascading submenu is created. */ QAction* Fill(QMenu* parent, QAction *before); + QAction* Fill(QMenuBar* menu, QAction* before); + /** * The ActionContributionItem implementation of this , * IContributionItem method creates an SWT * ToolItem for the action using the action's style. If the * action's checked property has been set, a button is created and primed to * the value of the checked property. If the action's menu creator property * has been set, a drop-down tool item is created. */ - QAction* Fill(QToolBar* parent, int index); + QAction* Fill(QToolBar* parent, QAction* before); /** * Returns the action associated with this contribution item. * * @return the action */ Action* GetAction() const; /** * Returns the presentation mode, which is the bitwise-or of the * MODE_* constants. The default mode setting is 0, meaning * that for menu items, both text and image are shown (if present), but for * tool items, the text is shown only if there is no image. * * @return the presentation mode settings */ Modes GetMode() const; /** * The action item implementation of this IContributionItem * method returns true for menu items and false * for everything else. */ bool IsDynamic() const; /* * Method declared on IContributionItem. */ bool IsEnabled() const; /** * The ActionContributionItem implementation of this * ContributionItem method extends the super implementation * by also checking whether the command corresponding to this action is * active. */ bool IsVisible() const; /** * Sets the presentation mode, which is the bitwise-or of the * MODE_* constants. * * @param mode * the presentation mode settings */ void SetMode(Modes mode); /** * The action item implementation of this IContributionItem * method calls update(null). */ void Update(); /** * Synchronizes the UI with the given property. * * @param propertyName * the name of the property, or null meaning all * applicable properties */ void Update(const QString& propertyName); protected: /** * Returns true if this item is allowed to enable, * false otherwise. * * @return if this item is allowed to be enabled */ bool IsEnabledAllowed() const; /** * Shorten the given text t so that its length doesn't exceed * the width of the given ToolItem.The default implementation replaces * characters in the center of the original string with an ellipsis ("..."). * Override if you need a different strategy. * * @param textValue * the text to shorten * @param item * the tool item the text belongs to * @return the shortened string * */ //QString ShortenText(const QString& textValue, QToolButton* item); private: /** * Returns the listener for SWT tool item widget events. * * @return a listener for tool item events */ //Listener GetToolItemListener(); /** * Handles a widget dispose event for the widget corresponding to this item. */ //void HandleWidgetDispose(Event e); /** * Handles a widget selection event. */ //void HandleWidgetSelection(Event e, bool selection); /** * Returns whether the given action has any images. * * @param actionToCheck * the action * @return true if the action has any images, * false if not */ //bool HasImages(Action* actionToCheck) const; /** * Returns whether the command corresponding to this action is active. */ bool IsCommandActive() const; /** * Updates the images for this action. * * @param forceImage * true if some form of image is compulsory, and * false if it is acceptable for this item to have * no image * @return true if there are images for this action, * false if not */ //bool UpdateImages(bool forceImage); /** * Dispose any images allocated for this contribution item */ //void DisposeOldImages(); /** * Handle show and hide on the proxy menu for IAction.AS_DROP_DOWN_MENU * actions. * * @return the appropriate listener */ //Listener getMenuCreatorListener(); /** * The proxy menu is being shown, we better get the real menu. * * @param proxy * the proxy menu */ //void HandleShowProxy(QMenu* proxy); /** * Create MenuItems in the proxy menu that can execute the real menu items * if selected. Create proxy menus for any real item submenus. * * @param realMenu * the real menu to copy from * @param proxy * the proxy menu to populate */ //void CopyMenu(QMenu* realMenu, QMenu* proxy); /** * The proxy menu is being hidden, so we need to make it go away. * * @param proxy * the proxy menu */ //void HandleHideProxy(QMenu* proxy); private: /** * This is the easiest way to hold the menu until we can swap it in to the * proxy. */ //QMenu* holdMenu = null; //bool menuCreatorCalled = false; /** a string inserted in the middle of text that has been shortened */ //static const QString ellipsis = "..."; /** * Stores the result of the action. False when the action returned failure. */ bool result; // = null; /** * The presentation mode. */ Modes mode; // = 0; /** * The action. */ Action* action; }; } #endif // BERRYACTIONCONTRIBUTIONITEM_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp index 8b956a2a1e..014d771451 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp @@ -1,733 +1,736 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryCommandContributionItem.h" #include "berryIMenuService.h" #include "berryICommandService.h" #include "berryICommandImageService.h" #include "berryIContributionManager.h" #include "berryIElementReference.h" #include "berryIElementUpdater.h" #include "berryUIElement.h" #include #include #include #include #include #include #include #include "../berryImageDescriptor.h" #include "../berryDisplay.h" #include "../berryAsyncRunnable.h" #include "../handlers/berryIHandlerService.h" #include "../services/berryIServiceLocator.h" #include "../internal/berryCommandContributionItemParameter.h" #include "../internal/berryWorkbenchPlugin.h" #include #include #include #include namespace berry { ContributionItem::Modes CommandContributionItem::modes = ContributionItem::MODE_FORCE_TEXT; //class CommandUIElementListener : public IUIElementListener //{ //private: // CommandContributionItem* item; // public: // CommandUIElementListener(CommandContributionItem* item); // void UIElementDisposed(UIElement* item); //void UIElementSelected(SmartPointer item); //}; CommandContributionItem::CommandContributionItem( const SmartPointer& contributionParameters) : ContributionItem(contributionParameters->id) , action(0) , checkedState(false) { this->icon = contributionParameters->icon; this->label = contributionParameters->label; this->mnemonic = contributionParameters->mnemonic; this->tooltip = contributionParameters->tooltip; this->style = contributionParameters->style; this->helpContextId = contributionParameters->helpContextId; this->visibleEnabled = contributionParameters->visibleEnabled; this->mode = contributionParameters->mode; menuService = contributionParameters->serviceLocator->GetService(); commandService = contributionParameters->serviceLocator->GetService(); handlerService = contributionParameters->serviceLocator->GetService(); // bindingService = (IBindingService) contributionParameters.serviceLocator // .getService(IBindingService.class); this->CreateCommand(contributionParameters->commandId, contributionParameters->parameters); if (command) { try { class CommandUIElement : public UIElement { private: CommandContributionItem* item; public: CommandUIElement(CommandContributionItem* item, IServiceLocator* serviceLocator) : UIElement(serviceLocator), item(item) {} void SetText(const QString& text) { item->SetText(text); } void SetToolTip(const QString& text) { item->SetToolTip(text); } void SetIcon(const QIcon& icon) { item->SetIcon(icon); } void SetChecked(bool checked) { item->SetChecked(checked); } void SetDropDownId(const QString& id) { item->dropDownMenuOverride = id; } }; UIElement::Pointer callback(new CommandUIElement(this, contributionParameters->serviceLocator)); elementRef = commandService->RegisterElementForCommand(command, callback); command->GetCommand()->AddCommandListener(this->GetCommandListener()); this->SetImages(contributionParameters->serviceLocator, contributionParameters->iconStyle); if (contributionParameters->helpContextId.isEmpty()) { try { this->helpContextId = commandService->GetHelpContextId( contributionParameters->commandId); } catch (const NotDefinedException& /*e*/) { // it's OK to not have a helpContextId } } // IWorkbenchLocationService::Pointer wls = contributionParameters.serviceLocator // ->GetService(IWorkbenchLocationService::GetManifestName()).Cast(); // const IWorkbench* workbench = wls->GetWorkbench();; // if (workbench != 0 && !helpContextId.empty()) { // this->workbenchHelpSystem = workbench->GetHelpSystem(); // } } catch (const NotDefinedException& /*e*/) { WorkbenchPlugin::Log(QString("Unable to register menu item \"") + this->GetId() + "\", command \"" + contributionParameters->commandId + "\" not defined"); } } } QAction* CommandContributionItem::Fill(QMenu* parent, QAction* before) { if (!command) { return 0; } if (action || parent == 0) { return 0; } // Menus don't support the pulldown style Style tmpStyle = style; if (tmpStyle == STYLE_PULLDOWN) tmpStyle = STYLE_PUSH; QAction* item = 0; if (before) { item = new QAction(icon, label, parent); parent->insertAction(before, item); } else { item = parent->addAction(icon, label); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(item, helpContextId); // } connect(item, SIGNAL(triggered()), this, SLOT(HandleWidgetSelection())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); return item; } QAction *CommandContributionItem::Fill(QToolBar *parent, QAction *before) { if (!command) { return 0; } if (action || parent == 0) { return 0; } QAction* item = 0; if (before) { item = parent->addAction(icon, label); } else { item = new QAction(icon, label, parent); parent->insertAction(before, item); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); //item->AddListener(this->GetItemListener()); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); return item; } void CommandContributionItem::Update() { this->Update(QString()); } void CommandContributionItem::Update(const QString& /*id*/) { if (action) { QWidget* parent = action->parentWidget(); if(qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateToolItem(); } } } void CommandContributionItem::UpdateMenuItem() { QString text = label; if (text.isEmpty()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } text = UpdateMnemonic(text); // String keyBindingText = null; // if (command != null) // { // TriggerSequence binding = bindingService // .getBestActiveBindingFor(command); // if (binding != null) // { // keyBindingText = binding.format(); // } // } // if (text != null) // { // if (keyBindingText == null) // { // item.setText(text); // } // else // { // item.setText(text + '\t' + keyBindingText); // } // } if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } void CommandContributionItem::UpdateToolItem() { QString text = label; QString tooltip = label; if (text.isNull()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); tooltip = command->GetCommand()->GetDescription(); if (tooltip.trimmed().isEmpty()) { tooltip = text; } } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } if ((icon.isNull() || (mode & MODE_FORCE_TEXT) == MODE_FORCE_TEXT) && !text.isNull()) { action->setText(text); } QString toolTipText = GetToolTipText(tooltip); action->setToolTip(toolTipText); if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } CommandContributionItem::~CommandContributionItem() { if (elementRef) { commandService->UnregisterElement(elementRef); } if (commandListener) { command->GetCommand()->RemoveCommandListener(commandListener.data()); } } bool CommandContributionItem::IsEnabled() const { if (command) { command->GetCommand()->SetEnabled(menuService->GetCurrentState()); return command->GetCommand()->IsEnabled(); } return false; } bool CommandContributionItem::IsVisible() const { if (visibleEnabled) { return ContributionItem::IsVisible() && this->IsEnabled(); } return ContributionItem::IsVisible(); } void CommandContributionItem::SetImages(IServiceLocator* locator, const QString& iconStyle) { if (icon.isNull()) { ICommandImageService* service = locator->GetService(); - icon = service->GetImage(command->GetId(), iconStyle); + if (service) + { + icon = service->GetImage(command->GetId(), iconStyle); + } } } ICommandListener* CommandContributionItem::GetCommandListener() { if (!commandListener) { class MyCommandListener : public ICommandListener { private: CommandContributionItem* item; public: MyCommandListener(CommandContributionItem* item) : item(item) {} void CommandChanged(const SmartPointer& commandEvent) { if (commandEvent->IsHandledChanged() || commandEvent->IsEnabledChanged() || commandEvent->IsDefinedChanged()) { item->UpdateCommandProperties(commandEvent); } } }; commandListener.reset(new MyCommandListener(this)); } return commandListener.data(); } void CommandContributionItem::UpdateCommandProperties(const SmartPointer< const CommandEvent> commandEvent) { if (commandEvent->IsHandledChanged()) { dropDownMenuOverride = ""; } if (!action) { return; } Display* display = Display::GetDefault(); typedef AsyncRunnable, CommandContributionItem > UpdateRunnable; Poco::Runnable* update = new UpdateRunnable(this, &CommandContributionItem::UpdateCommandPropertiesInUI, commandEvent); if (display->InDisplayThread()) { update->run(); } else { display->AsyncExec(update); } } void CommandContributionItem::UpdateCommandPropertiesInUI(const SmartPointer< const CommandEvent>& commandEvent) { if (commandEvent->GetCommand()->IsDefined()) { this->Update(); } if (commandEvent->IsEnabledChanged() || commandEvent->IsHandledChanged()) { if (visibleEnabled) { IContributionManager* parent = this->GetParent(); if (parent) { parent->Update(true); } } } } bool CommandContributionItem::ShouldRestoreAppearance(const SmartPointer& handler) { // if no handler or handler doesn't implement IElementUpdater, // restore the contributed elements if (handler.IsNull()) return true; if (!(handler.Cast())) return true; // special case, if its HandlerProxy, then check the actual handler // if (handler instanceof HandlerProxy) { // HandlerProxy handlerProxy = (HandlerProxy) handler; // IHandler actualHandler = handlerProxy.getHandler(); // return shouldRestoreAppearance(actualHandler); // } return false; } SmartPointer CommandContributionItem::GetCommand() const { return command; } void CommandContributionItem::CreateCommand(const QString &commandId, const QHash ¶meters) { if (commandId.isEmpty()) { // StatusManager.getManager().handle(StatusUtil.newStatus(IStatus.ERROR, // "Unable to create menu item \"" + getId() // + "\", no command id", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", no command id"; return; } Command::Pointer cmd = commandService->GetCommand(commandId); if (!cmd->IsDefined()) { // StatusManager.getManager().handle(StatusUtil.newStatus( // IStatus.ERROR, "Unable to create menu item \"" + getId() // + "\", command \"" + commandId + "\" not defined", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", command \"" << commandId.toStdString() << "\" not defined"; return; } command = ParameterizedCommand::GenerateCommand(cmd, parameters); } QString CommandContributionItem::GetToolTipText(const QString& text) const { QString tooltipText = tooltip; if (tooltip.isNull()) { if (!text.isNull()) { tooltipText = text; } else { tooltipText = ""; } } // TriggerSequence activeBinding = bindingService // .getBestActiveBindingFor(command); // if (activeBinding != null && !activeBinding.isEmpty()) // { // String acceleratorText = activeBinding.format(); // if (acceleratorText != null // && acceleratorText.length() != 0) // { // tooltipText = NLS.bind(CommandMessages.Tooltip_Accelerator, // tooltipText, acceleratorText); // } // } return tooltipText; } QString CommandContributionItem::UpdateMnemonic(const QString &s) { if (mnemonic.isNull() || s.isEmpty()) { return s; } int idx = s.indexOf(mnemonic); if (idx == -1) { return s; } return s.left(idx) + '&' + s.mid(idx); } //SmartPointer CommandContributionItem::GetItemListener() //{ // if (!itemListener) // { // itemListener = new CommandUIElementListener(this); // } // return itemListener; //} void CommandContributionItem::HandleWidgetSelection() { // // Special check for ToolBar dropdowns... // if (this->OpenDropDownMenu(event)) // //return; if ((style & STYLE_CHECK) != 0) { checkedState = action->isChecked(); } try { handlerService->ExecuteCommand(command, UIElement::Pointer(0)); } catch (const ExecutionException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotDefinedException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotEnabledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotHandledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } } void CommandContributionItem::connectNotify(const char *signal) { qDebug() << "Connected to:" << signal; } void CommandContributionItem::disconnectNotify(const char *signal) { qDebug() << "Disconnected from:" << signal; } //TODO Tool item drop down menu contributions //bool CommandContributionItem::OpenDropDownMenu(SmartPointer event) //{ //Widget item = event.widget; //if (item != null) //{ // int style = item.getStyle(); // if ((style & SWT.DROP_DOWN) != 0) // { // if (event.detail == 4) // { // on drop-down button // ToolItem ti = (ToolItem) item; // // final MenuManager menuManager = new MenuManager(); // Menu menu = menuManager.createContextMenu(ti.getParent()); // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(menu, helpContextId); // } // menuManager.addMenuListener(new IMenuListener() // { // public void menuAboutToShow(IMenuManager manager) // { // String id = getId(); // if (dropDownMenuOverride != null) // { // id = dropDownMenuOverride; // } // menuService.populateContributionManager( // menuManager, "menu:" + id); //$NON-NLS-1$ // } // }); // // // position the menu below the drop down item // Point point = ti.getParent().toDisplay( // new Point(event.x, event.y)); // menu.setLocation(point.x, point.y); // waiting for SWT // // 0.42 // menu.setVisible(true); // return true; // we don't fire the action // } // } //} // //return false; //} void CommandContributionItem::SetIcon(const QIcon &icon) { this->icon = icon; this->UpdateIcons(); } void CommandContributionItem::UpdateIcons() { action->setIcon(icon); } void CommandContributionItem::SetText(const QString &text) { label = text; this->Update(); } void CommandContributionItem::SetChecked(bool checked) { if (checkedState == checked) { return; } checkedState = checked; action->setChecked(checkedState); } void CommandContributionItem::SetToolTip(const QString &text) { tooltip = text; action->setToolTip(text); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.cpp index 9746bd1074..16ed9d2653 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.cpp @@ -1,408 +1,376 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "berryContributionManager.h" #include "berryIContributionManagerOverrides.h" #include "berryIContributionItem.h" -//#include "berryActionContributionItem.h" namespace berry { -//void ContributionManager::Add(Action *action) -//{ -// Q_ASSERT_X(action, "nullcheck", "Action must not be null"); -// IContributionItem::Pointer item(new ActionContributionItem(action)); -// Add(item); -//} - void ContributionManager::Add(const SmartPointer& item) { Q_ASSERT_X(item, "nullcheck", "Item must not be null"); if (AllowItem(item.GetPointer())) { contributions.append(item); ItemAdded(item); } } -//void ContributionManager::AppendToGroup(const QString& groupName, Action *action) -//{ -// IContributionItem::Pointer item(new ActionContributionItem(action)); -// AddToGroup(groupName, item, true); -//} - void ContributionManager::AppendToGroup(const QString& groupName, const SmartPointer& item) { AddToGroup(groupName, item, true); } SmartPointer ContributionManager::Find(const QString& id) const { QListIterator e(contributions); while (e.hasNext()) { IContributionItem::Pointer item = e.next(); QString itemId = item->GetId(); if (itemId.compare(id, Qt::CaseInsensitive) != 0) { return item; } } return IContributionItem::Pointer(0); } QList > ContributionManager::GetItems() const { return contributions; } int ContributionManager::GetSize() { return contributions.size(); } SmartPointer ContributionManager::GetOverrides() { if (overrides.IsNull()) { struct _DefaultOverride : public IContributionManagerOverrides { - int GetEnabled(IContributionItem* /*item*/) const { + int GetEnabled(const IContributionItem* /*item*/) const { return -1; } - int GetVisible(IContributionItem* /*item*/) const { + int GetVisible(const IContributionItem* /*item*/) const { return -1; } }; overrides = new _DefaultOverride; } return overrides; } int ContributionManager::IndexOf(const QString& id) { int i = 0; foreach(IContributionItem::Pointer item, contributions) { QString itemId = item->GetId(); if (item->GetId().compare(id, Qt::CaseInsensitive) == 0) { return i; } ++i; } return -1; } void ContributionManager::Insert(int index, const SmartPointer& item) { if (index > contributions.size()) { QString msg = QString("inserting ") + item->GetId() + " at " + QString::number(index); throw std::invalid_argument(msg.toStdString()); } if (AllowItem(item.GetPointer())) { contributions.insert(index, item); ItemAdded(item); } } -//void ContributionManager::InsertAfter(const QString& ID, Action *action) -//{ -// IContributionItem::Pointer item(new ActionContributionItem(action)); -// InsertAfter(ID, item); -//} - void ContributionManager::InsertAfter(const QString& ID, const SmartPointer& item) { IContributionItem::Pointer ci = Find(ID); if (ci.IsNull()) { throw ctkInvalidArgumentException(QString("can't find ID") + ID); } int ix = contributions.indexOf(ci); if (ix >= 0) { // BERRY_INFO << "insert after: " << ix; if (AllowItem(item.GetPointer())) { contributions.insert(ix + 1, item); ItemAdded(item); } } } -//void ContributionManager::InsertBefore(const QString& ID, Action *action) -//{ -// IContributionItem::Pointer item(new ActionContributionItem(action)); -// InsertBefore(ID, item); -//} - void ContributionManager::InsertBefore(const QString& ID, const SmartPointer& item) { IContributionItem::Pointer ci = Find(ID); if (ci.IsNull()) { throw ctkInvalidArgumentException(QString("can't find ID ") + ID); } int ix = contributions.indexOf(ci); if (ix >= 0) { // BERRY_INFO << "insert before: " << ix; if (AllowItem(item.GetPointer())) { contributions.insert(ix, item); ItemAdded(item); } } } bool ContributionManager::IsDirty() const { if (isDirty) { return true; } if (HasDynamicItems()) { foreach (IContributionItem::Pointer item, contributions) { if (item->IsDirty()) { return true; } } } return false; } bool ContributionManager::IsEmpty() const { return contributions.empty(); } void ContributionManager::MarkDirty() { SetDirty(true); } -//void ContributionManager::PrependToGroup(const QString& groupName, Action *action) -//{ -// IContributionItem::Pointer item(new ActionContributionItem(action)); -// AddToGroup(groupName, item, false); -//} - void ContributionManager::PrependToGroup(const QString& groupName, const SmartPointer& item) { AddToGroup(groupName, item, false); } SmartPointer ContributionManager::Remove(const QString& ID) { IContributionItem::Pointer ci = Find(ID); if (ci.IsNull()) { return ci; } return Remove(ci); } SmartPointer ContributionManager::Remove(const SmartPointer& item) { if (contributions.removeAll(item)) { ItemRemoved(item); return item; } return IContributionItem::Pointer(0); } void ContributionManager::RemoveAll() { QList items = GetItems(); contributions.clear(); foreach (IContributionItem::Pointer item, items) { ItemRemoved(item); } dynamicItems = 0; MarkDirty(); } bool ContributionManager::ReplaceItem(const QString& identifier, const SmartPointer& replacementItem) { if (identifier.isNull()) { return false; } const int index = IndexOf(identifier); if (index < 0) { return false; // couldn't find the item. } // Remove the old item. const IContributionItem::Pointer oldItem = contributions.at(index); ItemRemoved(oldItem); // Add the new item. contributions.replace(index, replacementItem); ItemAdded(replacementItem); // throws NPE if (replacementItem == null) // Go through and remove duplicates. QMutableListIterator i(contributions); i.toBack(); while (i.hasPrevious()) { IContributionItem::Pointer item = i.previous(); if ((item.IsNotNull()) && (identifier == item->GetId())) { // if (Policy.TRACE_TOOLBAR) { // System.out // .println("Removing duplicate on replace: " + identifier); // } i.remove(); ItemRemoved(item); } } return true; // success } void ContributionManager::SetOverrides(const SmartPointer& newOverrides) { overrides = newOverrides; } ContributionManager::ContributionManager() : isDirty(true), dynamicItems(0) { // Do nothing. } bool ContributionManager::AllowItem(IContributionItem* /*itemToAdd*/) { return true; } void ContributionManager::DumpStatistics() { int size = contributions.size(); BERRY_INFO << this->ToString(); BERRY_INFO << " Number of elements: " << size; int sum = 0; for (int i = 0; i < size; i++) { if (contributions.at(i)->IsVisible()) { ++sum; } } BERRY_INFO << " Number of visible elements: " << sum; BERRY_INFO << " Is dirty: " << IsDirty(); } bool ContributionManager::HasDynamicItems() const { return (dynamicItems > 0); } int ContributionManager::IndexOf(const SmartPointer& item) const { return contributions.indexOf(item); } void ContributionManager::ItemAdded(const SmartPointer& item) { item->SetParent(this); MarkDirty(); if (item->IsDynamic()) { dynamicItems++; } } void ContributionManager::ItemRemoved(const SmartPointer& item) { item->SetParent(0); MarkDirty(); if (item->IsDynamic()) { dynamicItems--; } } void ContributionManager::SetDirty(bool dirty) { isDirty = dirty; } void ContributionManager::InternalSetItems(const QList >& items) { contributions.clear(); for (int i = 0; i < items.size(); ++i) { if (AllowItem(items[i].GetPointer())) { contributions.append(items[i]); } } } void ContributionManager::AddToGroup(const QString& groupName, const SmartPointer& item, bool append) { QMutableListIterator items(contributions); for (int i = 0; items.hasNext(); ++i) { IContributionItem::Pointer o = items.next(); if (o->IsGroupMarker()) { QString id = o->GetId(); if (id.compare(groupName, Qt::CaseInsensitive) == 0) { ++i; if (append) { for (; items.hasNext(); ++i) { IContributionItem::Pointer ci = items.next(); if (ci->IsGroupMarker()) { break; } } } if (AllowItem(item.GetPointer())) { contributions.insert(i, item); ItemAdded(item); } return; } } } throw ctkInvalidArgumentException(QString("Group not found: ") + groupName); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManager.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManager.h index 8e8ff07e47..d060f54bc3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManager.h @@ -1,252 +1,192 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYICONTRIBUTIONMANAGER_H #define BERRYICONTRIBUTIONMANAGER_H #include #include namespace berry { //struct Action; struct IContributionItem; struct IContributionManagerOverrides; /** * A contribution manager organizes contributions to such UI components * as menus, toolbars and status lines. *

* A contribution manager keeps track of a list of contribution * items. Each contribution item may has an optional identifier, which can be used * to retrieve items from a manager, and for positioning items relative to * each other. The list of contribution items can be subdivided into named groups * using special contribution items that serve as group markers. *

*

* The IContributionManager interface provides general * protocol for adding, removing, and retrieving contribution items. * It also provides convenience methods that make it convenient * to contribute actions. This interface should be implemented * by all objects that wish to manage contributions. *

*

* There are several implementions of this interface in this package, * including ones for menus ({@link MenuManager MenuManager}), * tool bars ({@link ToolBarManager ToolBarManager}), * and status lines ({@link StatusLineManager StatusLineManager}). *

*/ struct IContributionManager : public virtual Object { berryObjectMacro(berry::IContributionManager) - /* - * Adds an action as a contribution item to this manager. - * Equivalent to add(new ActionContributionItem(action)). - * - * @param action the action, this cannot be null - */ - //virtual void Add(Action* action) = 0; - /** * Adds a contribution item to this manager. * * @param item the contribution item, this cannot be null */ virtual void Add(const SmartPointer& item) = 0; - /* - * Adds a contribution item for the given action at the end of the group - * with the given name. - * Equivalent to - * appendToGroup(groupName,new ActionContributionItem(action)). - * - * @param groupName the name of the group - * @param action the action - * @exception std::invalid_argument if there is no group with - * the given name - */ - //virtual void AppendToGroup(const QString& groupName, Action* action) = 0; - /** * Adds a contribution item to this manager at the end of the group * with the given name. * * @param groupName the name of the group * @param item the contribution item * @exception std::invalid_argument if there is no group with * the given name */ virtual void AppendToGroup(const QString& groupName, const SmartPointer& item) = 0; /** * Finds the contribution item with the given id. * * @param id the contribution item id * @return the contribution item, or null if * no item with the given id can be found */ virtual SmartPointer Find(const QString& id) const = 0; /** * Returns all contribution items known to this manager. * * @return a list of contribution items */ virtual QList > GetItems() const = 0; /** * Returns the overrides for the items of this manager. * * @return the overrides for the items of this manager */ virtual SmartPointer GetOverrides() = 0; - /* - * Inserts a contribution item for the given action after the item - * with the given id. - * Equivalent to - * insertAfter(id,new ActionContributionItem(action)). - * - * @param id the contribution item id - * @param action the action to insert - * @exception IllegalArgumentException if there is no item with - * the given id - */ - //virtual void InsertAfter(const QString& id, Action* action) = 0; - /** * Inserts a contribution item after the item with the given id. * * @param id the contribution item id * @param item the contribution item to insert * @exception IllegalArgumentException if there is no item with * the given id */ virtual void InsertAfter(const QString& id, const SmartPointer& item) = 0; - /* - * Inserts a contribution item for the given action before the item - * with the given id. - * Equivalent to - * InsertBefore(id,new ActionContributionItem(action)). - * - * @param id the contribution item id - * @param action the action to insert - * @exception IllegalArgumentException if there is no item with - * the given id - */ - //virtual void InsertBefore(const QString& id, Action* action) = 0; - /** * Inserts a contribution item before the item with the given id. * * @param id the contribution item id * @param item the contribution item to insert * @exception IllegalArgumentException if there is no item with * the given id */ virtual void InsertBefore(const QString& id, const SmartPointer& item) = 0; /** * Returns whether the list of contributions has recently changed and * has yet to be reflected in the corresponding widgets. * * @return true if this manager is dirty, and false * if it is up-to-date */ virtual bool IsDirty() const = 0; /** * Returns whether this manager has any contribution items. * * @return true if there are no items, and * false otherwise */ virtual bool IsEmpty() const = 0; /** * Marks this contribution manager as dirty. */ virtual void MarkDirty() = 0; - /* - * Adds a contribution item for the given action at the beginning of the - * group with the given name. - * Equivalent to - * prependToGroup(groupName,new ActionContributionItem(action)). - * - * @param groupName the name of the group - * @param action the action - * @exception IllegalArgumentException if there is no group with - * the given name - */ - //virtual void PrependToGroup(const QString& groupName, Action* action) = 0; - /** * Adds a contribution item to this manager at the beginning of the * group with the given name. * * @param groupName the name of the group * @param item the contribution item * @exception IllegalArgumentException if there is no group with * the given name */ virtual void PrependToGroup(const QString& groupName, const SmartPointer& item) = 0; /** * Removes and returns the contribution item with the given id from this manager. * Returns null if this manager has no contribution items * with the given id. * * @param id the contribution item id * @return the item that was found and removed, or null if none */ virtual SmartPointer Remove(const QString& id) = 0; /** * Removes the given contribution item from the contribution items * known to this manager. * * @param item the contribution item * @return the item parameter if the item was removed, * and null if it was not found */ virtual SmartPointer Remove(const SmartPointer& item) = 0; /** * Removes all contribution items from this manager. */ virtual void RemoveAll() = 0; /** * Updates this manager's underlying widget(s) with any changes which * have been made to it or its items. Normally changes to a contribution * manager merely mark it as dirty, without updating the underlying widgets. * This brings the underlying widgets up to date with any changes. * * @param force true means update even if not dirty, * and false for normal incremental updating */ virtual void Update(bool force) = 0; }; } #endif // BERRYICONTRIBUTIONMANAGER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManagerOverrides.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManagerOverrides.h index 22d20c8354..17977b1c06 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManagerOverrides.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManagerOverrides.h @@ -1,79 +1,79 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYICONTRIBUTIONMANAGEROVERRIDES_H #define BERRYICONTRIBUTIONMANAGEROVERRIDES_H #include #include #include namespace berry { struct IContributionItem; /** * This interface is used by instances of IContributionItem * to determine if the values for certain properties have been overriden * by their manager. *

* This interface is internal to the framework; it should not be implemented outside * the framework. *

* * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IContributionManagerOverrides : virtual Object { berryObjectMacro(berry::IContributionManagerOverrides) /** * Id for the enabled property. Value is "enabled". */ static const QString P_ENABLED; /** * Find out the enablement of the item * @param item the contribution item for which the enable override value is * determined * @param defaultValue the default value * @return
    *
  • 1 if the given contribution item should be enabled
  • *
  • 0 if the item should not be enabled
  • *
  • -1 if the item may determine its own enablement
  • *
*/ - virtual int GetEnabled(IContributionItem* item) const = 0; + virtual int GetEnabled(const IContributionItem* item) const = 0; /** * Visiblity override. * * @param item the contribution item in question * @return
    *
  • 1 if the given contribution item should be visible
  • *
  • 0 if the item should not be visible
  • *
  • -1 if the item may determine its own visibility
  • *
*/ - virtual int GetVisible(IContributionItem* item) const = 0; + virtual int GetVisible(const IContributionItem* item) const = 0; }; } #endif // BERRYICONTRIBUTIONMANAGEROVERRIDES_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.cpp index 4ea4d19af3..4e5cbf423c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.cpp @@ -1,726 +1,728 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryMenuManager.h" #include "berryIContributionManagerOverrides.h" #include "berrySubContributionItem.h" #include "internal/berryMMMenuListener.h" #include #include class QMenuProxy { public: QMenu* menu; QMenuBar* menuBar; enum Type { MenuBar, Menu }; QMenuProxy(Type type, QWidget* parent = 0) : menu(0), menuBar(0) { switch (type) { case MenuBar: menuBar = new QMenuBar(parent); case Menu: menu = new QMenu(parent); } } bool isMenuBar() const { return menuBar != 0; } void setTitle(const QString& title) { if (menu) menu->setTitle(title); } void setIcon(const QIcon& icon) { if (menu) menu->setIcon(icon); } QList actions() const { return menu ? menu->actions() : menuBar->actions(); } void removeAction(QAction* action) { menu ? menu->removeAction(action) : menuBar->removeAction(action); } bool isEnabled() const { return menu ? menu->isEnabled() : menuBar->isEnabled(); } void setEnabled(bool enabled) { menu ? menu->setEnabled(enabled) : menuBar->setEnabled(enabled); } }; namespace berry { struct NullOverrides: public IContributionManagerOverrides { public: - int GetEnabled(IContributionItem* /*item*/) const + int GetEnabled(const IContributionItem* /*item*/) const { return -1; } - int GetVisible(IContributionItem* /*item*/) const + int GetVisible(const IContributionItem* /*item*/) const { return -1; } }; //struct GuiTkMenuListener : public GuiTk::IMenuListener //{ //public: // GuiTkMenuListener(MenuManager::Pointer manager) : // manager(manager) // { // } // void MenuAboutToHide() // { // // ApplicationWindow.resetDescription(e.widget); // MenuManager::Pointer(manager)->HandleAboutToHide(); // } // void MenuAboutToShow() // { // MenuManager::Pointer(manager)->HandleAboutToShow(); // } //private: // MenuManager::WeakPtr manager; //}; MenuManager::MenuManager(const QString& text, const QString& id) : id(id), menu(0), menuItem(0), menuListener(new MMMenuListener(this)) , menuText(text), parent(0) , removeAllWhenShown(false), visible(true) { } MenuManager::MenuManager(const QString& text, const QIcon& image, const QString& id) : id(id), menu(0), menuItem(0), menuListener(new MMMenuListener(this)) , menuText(text), image(image) , parent(0), removeAllWhenShown(false), visible(true) { } bool MenuManager::IsDirty() const { return ContributionManager::IsDirty(); } MenuManager::~MenuManager() { delete menu; } //void MenuManager::AddMenuListener(SmartPointer listener) //{ // menuEvents.AddListener(listener); //} QMenu* MenuManager::CreateContextMenu(QWidget* parent) { if (!menu) { menu = new QMenuProxy(QMenuProxy::Menu, parent); this->InitializeMenu(); } return menu->menu; } QMenuBar* MenuManager::CreateMenuBar(QWidget* parent) { if (!menu) { menu = new QMenuProxy(QMenuProxy::MenuBar, parent); this->Update(false); } return menu->menuBar; } void MenuManager::Fill(QStatusBar* /*parent*/) { } QAction* MenuManager::Fill(QToolBar* /*parent*/, QAction* /*before*/) { return 0; } QAction* MenuManager::Fill(QMenu* parent, QAction* before) { return this->FillMenu(parent, before); } QAction* MenuManager::Fill(QMenuBar* parent, QAction* before) { return this->FillMenu(parent, before); } QAction* MenuManager::FillMenu(QWidget* parent, QAction* before) { if (!menuItem) { menuItem = new QAction(parent); if (parent) { parent->insertAction(before, menuItem); } menuItem->setText(GetMenuText()); menuItem->setIcon(image); if(!menu) { menu = new QMenuProxy(QMenuProxy::Menu, parent); } if (!menu->isMenuBar()) menuItem->setMenu(menu->menu); this->InitializeMenu(); this->SetDirty(true); } return menuItem; } IMenuManager::Pointer MenuManager::FindMenuUsingPath(const QString& path) const { IContributionItem::Pointer item(this->FindUsingPath(path)); if (IMenuManager::Pointer manager = item.Cast()) { return manager; } return IMenuManager::Pointer(0); } IContributionItem::Pointer MenuManager::FindUsingPath(const QString& path) const { QString id(path); QString rest; int separator = path.indexOf('/'); if (separator != -1) { id = path.left(separator); rest = path.mid(separator + 1); } else { return ContributionManager::Find(path); } IContributionItem::Pointer item(ContributionManager::Find(id)); if (IMenuManager::Pointer manager = item.Cast()) { return manager->FindUsingPath(rest); } return IContributionItem::Pointer(0); } QString MenuManager::GetId() const { return id; } QMenu* MenuManager::GetMenu() const { return menu->menu; } QString MenuManager::GetMenuText() const { if (definitionId == "") { return menuText; } // ExternalActionManager::ICallback callback = ExternalActionManager // .getInstance().getCallback(); // if (callback != null) // { // String shortCut = callback.getAcceleratorText(definitionId); // if (shortCut == null) // { // return menuText; // } // return menuText + "\t" + shortCut; //$NON-NLS-1$ // } return menuText; } QIcon MenuManager::GetImage() const { return image; } SmartPointer MenuManager::GetOverrides() { if (!overrides) { if (!parent) { overrides = new NullOverrides(); } else { overrides = parent->GetOverrides(); } ContributionManager::SetOverrides(overrides); } return overrides; } IContributionManager* MenuManager::GetParent() const { return parent; } bool MenuManager::GetRemoveAllWhenShown() const { return removeAllWhenShown; } bool MenuManager::IsDynamic() const { return false; } bool MenuManager::IsEnabled() const { return true; } bool MenuManager::IsGroupMarker() const { return false; } bool MenuManager::IsSeparator() const { return false; } bool MenuManager::IsVisible() const { if (!visible) { return false; // short circuit calculations in this case } if (removeAllWhenShown) { // we have no way of knowing if the menu has children return true; } // menus aren't visible if all of its children are invisible (or only contains visible separators). bool visibleChildren = false; foreach(IContributionItem::Pointer item, this->GetItems()) { if (item->IsVisible() && !item->IsSeparator()) { visibleChildren = true; break; } } return visibleChildren; } void MenuManager::MarkDirty() { ContributionManager::MarkDirty(); // Can't optimize by short-circuiting when the first dirty manager is encountered, // since non-visible children are not even processed. // That is, it's possible to have a dirty sub-menu under a non-dirty parent menu // even after the parent menu has been updated. // If items are added/removed in the sub-menu, we still need to propagate the dirty flag up, // even if the sub-menu is already dirty, since the result of isVisible() may change // due to the added/removed items. IContributionManager* p = this->GetParent(); if (p) { p->MarkDirty(); } } //void MenuManager::RemoveMenuListener(SmartPointer listener) //{ // menuEvents.RemoveListener(listener); //} void MenuManager::SaveWidgetState() { } void MenuManager::SetOverrides(SmartPointer newOverrides) { overrides = newOverrides; ContributionManager::SetOverrides(overrides); } void MenuManager::SetParent(IContributionManager* manager) { parent = manager; } void MenuManager::SetRemoveAllWhenShown(bool removeAll) { this->removeAllWhenShown = removeAll; } void MenuManager::SetVisible(bool visible) { this->visible = visible; } void MenuManager::SetActionDefinitionId(const QString& definitionId) { this->definitionId = definitionId; } void MenuManager::Update() { this->UpdateMenuItem(); } void MenuManager::Update(const QString& /*property*/) { } void MenuManager::Update(bool force) { this->Update(force, false); } void MenuManager::UpdateAll(bool force) { this->Update(force, true); } //void MenuManager::FireAboutToShow(IMenuManager::Pointer manager) //{ // menuEvents.menuAboutToShow(manager); //} //void MenuManager::FireAboutToHide(IMenuManager::Pointer manager) //{ // menuEvents.menuAboutToHide(manager); //} //void MenuManager::HandleAboutToShow() //{ // if (removeAllWhenShown) // { // this->RemoveAll(); // } // this->FireAboutToShow(IMenuManager::Pointer(this)); // this->Update(false, false); //} //void MenuManager::HandleAboutToHide() //{ // this->FireAboutToHide(IMenuManager::Pointer(this)); //} void MenuManager::InitializeMenu() { menu->setTitle(GetMenuText()); menu->setIcon(GetImage()); //menuListener = new GuiTkMenuListener(MenuManager::Pointer(this)); if (!menu->isMenuBar()) { QObject::connect(menu->menu, SIGNAL(aboutToShow()), menuListener.data(), SLOT(HandleAboutToShow())); } //menu->AddMenuListener(menuListener); // Don't do an update(true) here, in case menu is never opened. // Always do it lazily in handleAboutToShow(). } //void MenuManager::DisposeOldImages() //{ // if (imageManager) // { // imageManager.dispose(); // imageManager = null; // } //} void MenuManager::UpdateMenuItem() { if (menuItem && menu) { bool enabled = removeAllWhenShown || menu->actions().size() > 0; if (menu->isEnabled() != enabled) { menuItem->setEnabled(enabled); } } } //QList > MenuManager::GetMenuItems() //{ // if (menu) // { // return menu->GetItems(); // } // return QList(); //} //SmartPointer MenuManager::GetMenuItem(unsigned int index) //{ // if (menu) // { // return menu->GetItem(index); // } // return IMenuItem::Pointer(0); //} //unsigned int MenuManager::GetMenuItemCount() //{ // if (menu) // { // return menu->GetItemCount(); // } // return 0; //} void MenuManager::DoItemFill(IContributionItem::Pointer ci, QAction* before) { if (menu->isMenuBar()) { ci->Fill(menu->menuBar, before); } else { ci->Fill(menu->menu, before); } } void MenuManager::Update(bool force, bool recursive) { if (ContributionManager::IsDirty() || force) { if (menu) { // clean contains all active items without double separators QList items = this->GetItems(); QList clean; IContributionItem::Pointer separator; foreach (IContributionItem::Pointer ci, items) { if (!ci->IsVisible()) { continue; } if (ci->IsSeparator()) { // delay creation until necessary // (handles both adjacent separators, and separator at end) separator = ci; } else { if (separator) { if (clean.size() > 0) { clean.push_back(separator); } separator = 0; } clean.push_back(ci); } } // remove obsolete (removed or non active) QList mi = menu->actions(); for (int i = 0; i < mi.size(); i++) { Object::Pointer data = mi[i]->data().value(); if (!data || !clean.contains(data.Cast())) { menu->removeAction(mi[i]); } else if (IContributionItem::Pointer ci = data.Cast()) { if(ci->IsDynamic() && ci->IsDirty()) { menu->removeAction(mi[i]); delete mi[i]; } } } // add new mi = menu->actions(); int srcIx = 0; int destIx = 0; for (QList::Iterator e = clean.begin(); e != clean.end(); ++e) { IContributionItem::Pointer src(*e); IContributionItem::Pointer dest; // get corresponding item in widget if (srcIx < mi.size()) { dest = mi[srcIx]->data().value().Cast(); } else { dest = 0; } if (dest && src == dest) { srcIx++; destIx++; } else if (dest && dest->IsSeparator() && src->IsSeparator()) { mi[srcIx]->setData(QVariant::fromValue(src)); srcIx++; destIx++; } else { int start = menu->actions().size(); - this->DoItemFill(src, destIx < 1 ? 0 : menu->actions().at(destIx-1)); + qDebug() << "***** Filling item destIx = " << destIx << " (size: " << start << ")"; + this->DoItemFill(src, destIx >= start ? NULL : menu->actions().at(destIx)); int newItems = menu->actions().size() - start; + qDebug() << "***** New items: " << newItems; for (int i = 0; i < newItems; ++i) { menu->actions().at(destIx++)->setData(QVariant::fromValue(src)); } } // May be we can optimize this call. If the menu has just // been created via the call src.fill(fMenuBar, destIx) then // the menu has already been updated with update(true) // (see MenuManager). So if force is true we do it again. But // we can't set force to false since then information for the // sub sub menus is lost. if (recursive) { IContributionItem::Pointer item(src); if (SubContributionItem::Pointer subItem = item.Cast()) { item = subItem->GetInnerItem(); } if (IMenuManager::Pointer mm = item.Cast()) { mm->UpdateAll(force); } } } // remove any old menu items not accounted for for (; srcIx < mi.size(); srcIx++) { menu->removeAction(mi[srcIx]); delete mi[srcIx]; } this->SetDirty(false); } } else { // I am not dirty. Check if I must recursivly walk down the hierarchy. if (recursive) { foreach (IContributionItem::Pointer ci, this->GetItems()) { if (IMenuManager::Pointer mm = ci.Cast()) { if (mm->IsVisible()) { mm->UpdateAll(force); } } } } } this->UpdateMenuItem(); } void MenuManager::DumpActionInfo(QMenuProxy* menu) { if (menu->isMenuBar()) { qDebug() << "QMenuBar [" << menu->menuBar << "]"; DumpActionInfo(menu->menuBar, 1); } else { qDebug() << "QMenu [" << menu->menu << "]" << menu->menu; DumpActionInfo(menu->menu, 1); } } void MenuManager::DumpActionInfo(QWidget* widget, int level) { QString indent = " |"; for (int i = 0; i < level; ++i) indent += "--"; foreach(QAction* action, widget->actions()) { qDebug() << qPrintable(indent) << action->text() << "[" << action << "]"; if (action->menu()) { DumpActionInfo(action->menu(), level+1); } } } }